blob: 4ae5a02779ee98b0ce9b9f1a1f8c122a35be4f0c [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>
Wei Jiaf2ae3e12016-10-27 17:10:59 -070036#include <private/android_filesystem_config.h>
Andy Hung2ddee192015-12-18 17:34:44 -080037#include <audio_utils/conversion.h>
Eric Laurent81784c32012-11-19 14:55:58 -080038#include <audio_utils/primitives.h>
Andy Hung98ef9782014-03-04 14:46:50 -080039#include <audio_utils/format.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070040#include <audio_utils/minifloat.h>
Mikhail Naganov9fe94012016-10-14 14:57:40 -070041#include <system/audio_effects/effect_ns.h>
42#include <system/audio_effects/effect_aec.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070043#include <system/audio.h>
Eric Laurent81784c32012-11-19 14:55:58 -080044
45// NBAIO implementations
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070046#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080047#include <media/nbaio/AudioStreamOutSink.h>
48#include <media/nbaio/MonoPipe.h>
49#include <media/nbaio/MonoPipeReader.h>
50#include <media/nbaio/Pipe.h>
51#include <media/nbaio/PipeReader.h>
52#include <media/nbaio/SourceAudioBufferProvider.h>
Wei Jia3f273d12015-11-24 09:06:49 -080053#include <mediautils/BatteryNotifier.h>
Eric Laurent81784c32012-11-19 14:55:58 -080054
55#include <powermanager/PowerManager.h>
56
Eric Laurent81784c32012-11-19 14:55:58 -080057#include "AudioFlinger.h"
58#include "AudioMixer.h"
Andy Hungd330ee42015-04-20 13:23:41 -070059#include "BufferProviders.h"
Eric Laurent81784c32012-11-19 14:55:58 -080060#include "FastMixer.h"
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070061#include "FastCapture.h"
Eric Laurent81784c32012-11-19 14:55:58 -080062#include "ServiceUtilities.h"
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -070063#include "mediautils/SchedulingPolicyService.h"
Eric Laurent81784c32012-11-19 14:55:58 -080064
Eric Laurent81784c32012-11-19 14:55:58 -080065#ifdef ADD_BATTERY_DATA
66#include <media/IMediaPlayerService.h>
67#include <media/IMediaDeathNotifier.h>
68#endif
69
Eric Laurent81784c32012-11-19 14:55:58 -080070#ifdef DEBUG_CPU_USAGE
71#include <cpustats/CentralTendencyStatistics.h>
72#include <cpustats/ThreadCpuUsage.h>
73#endif
74
Glenn Kastenc05b8d72016-03-24 09:48:17 -070075#include "AutoPark.h"
76
Eric Laurent81784c32012-11-19 14:55:58 -080077// ----------------------------------------------------------------------------
78
79// Note: the following macro is used for extremely verbose logging message. In
80// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
81// 0; but one side effect of this is to turn all LOGV's as well. Some messages
82// are so verbose that we want to suppress them even when we have ALOG_ASSERT
83// turned on. Do not uncomment the #def below unless you really know what you
84// are doing and want to see all of the extremely verbose messages.
85//#define VERY_VERY_VERBOSE_LOGGING
86#ifdef VERY_VERY_VERBOSE_LOGGING
87#define ALOGVV ALOGV
88#else
89#define ALOGVV(a...) do { } while(0)
90#endif
91
Andy Hung6770c6f2015-04-07 13:43:36 -070092// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -070093#define max(a, b) ((a) > (b) ? (a) : (b))
Andy Hung6770c6f2015-04-07 13:43:36 -070094template <typename T>
95static inline T min(const T& a, const T& b)
96{
97 return a < b ? a : b;
98}
Glenn Kasten49d00ad2014-07-21 11:22:03 -070099
Andy Hungd330ee42015-04-20 13:23:41 -0700100#ifndef ARRAY_SIZE
Chih-Hung Hsiehbf291732016-05-17 15:16:07 -0700101#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
Andy Hungd330ee42015-04-20 13:23:41 -0700102#endif
103
Eric Laurent81784c32012-11-19 14:55:58 -0800104namespace android {
105
106// retry counts for buffer fill timeout
107// 50 * ~20msecs = 1 second
108static const int8_t kMaxTrackRetries = 50;
109static const int8_t kMaxTrackStartupRetries = 50;
110// allow less retry attempts on direct output thread.
111// direct outputs can be a scarce resource in audio hardware and should
112// be released as quickly as possible.
113static const int8_t kMaxTrackRetriesDirect = 2;
Eric Laurente93cc032016-05-05 10:15:10 -0700114
Eric Laurent51716182016-02-29 18:00:56 -0800115
Eric Laurent81784c32012-11-19 14:55:58 -0800116
117// don't warn about blocked writes or record buffer overflows more often than this
118static const nsecs_t kWarningThrottleNs = seconds(5);
119
120// RecordThread loop sleep time upon application overrun or audio HAL read error
121static const int kRecordThreadSleepUs = 5000;
122
Eric Laurent10351942014-05-08 18:49:52 -0700123// maximum time to wait in sendConfigEvent_l() for a status to be received
124static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800125
126// minimum sleep time for the mixer thread loop when tracks are active but in underrun
127static const uint32_t kMinThreadSleepTimeUs = 5000;
128// maximum divider applied to the active sleep time in the mixer thread loop
129static const uint32_t kMaxThreadSleepTimeShift = 2;
130
Andy Hung09a50072014-02-27 14:30:47 -0800131// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700132// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800133static const uint32_t kMinNormalSinkBufferSizeMs = 20;
134// maximum normal sink buffer size
135static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800136
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700137// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
138// FIXME This should be based on experimentally observed scheduling jitter
139static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
140
Eric Laurent972a1732013-09-04 09:42:59 -0700141// Offloaded output thread standby delay: allows track transition without going to standby
142static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
143
Eric Laurent51716182016-02-29 18:00:56 -0800144// Direct output thread minimum sleep time in idle or active(underrun) state
145static const nsecs_t kDirectMinSleepTimeUs = 10000;
146
Glenn Kasten1b291842016-07-18 14:55:21 -0700147// The universal constant for ubiquitous 20ms value. The value of 20ms seems to provide a good
148// balance between power consumption and latency, and allows threads to be scheduled reliably
149// by the CFS scheduler.
150// FIXME Express other hardcoded references to 20ms with references to this constant and move
151// it appropriately.
152#define FMS_20 20
Eric Laurent51716182016-02-29 18:00:56 -0800153
Eric Laurent81784c32012-11-19 14:55:58 -0800154// Whether to use fast mixer
155static const enum {
156 FastMixer_Never, // never initialize or use: for debugging only
157 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
158 // normal mixer multiplier is 1
159 FastMixer_Static, // initialize if needed, then use all the time if initialized,
160 // multiplier is calculated based on min & max normal mixer buffer size
161 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
162 // multiplier is calculated based on min & max normal mixer buffer size
163 // FIXME for FastMixer_Dynamic:
164 // Supporting this option will require fixing HALs that can't handle large writes.
165 // For example, one HAL implementation returns an error from a large write,
166 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
167 // We could either fix the HAL implementations, or provide a wrapper that breaks
168 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
169} kUseFastMixer = FastMixer_Static;
170
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700171// Whether to use fast capture
172static const enum {
173 FastCapture_Never, // never initialize or use: for debugging only
174 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
175 FastCapture_Static, // initialize if needed, then use all the time if initialized
176} kUseFastCapture = FastCapture_Static;
177
Eric Laurent81784c32012-11-19 14:55:58 -0800178// Priorities for requestPriority
179static const int kPriorityAudioApp = 2;
180static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700181static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800182
Glenn Kastenea38ee72016-04-18 11:08:01 -0700183// IAudioFlinger::createTrack() has an in/out parameter 'pFrameCount' for the total size of the
184// track buffer in shared memory. Zero on input means to use a default value. For fast tracks,
185// AudioFlinger derives the default from HAL buffer size and 'fast track multiplier'.
Glenn Kasten03490092014-05-27 12:30:54 -0700186
187// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800188static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800189
Glenn Kasten03490092014-05-27 12:30:54 -0700190// The minimum and maximum allowed values
191static const int kFastTrackMultiplierMin = 1;
192static const int kFastTrackMultiplierMax = 2;
193
194// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
195static int sFastTrackMultiplier = kFastTrackMultiplier;
196
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700197// See Thread::readOnlyHeap().
198// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
199// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
200// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Glenn Kasten9f81de32014-07-27 15:02:23 -0700201static const size_t kRecordThreadReadOnlyHeapSize = 0x2000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700202
Eric Laurent81784c32012-11-19 14:55:58 -0800203// ----------------------------------------------------------------------------
204
Glenn Kasten03490092014-05-27 12:30:54 -0700205static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
206
207static void sFastTrackMultiplierInit()
208{
209 char value[PROPERTY_VALUE_MAX];
210 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
211 char *endptr;
212 unsigned long ul = strtoul(value, &endptr, 0);
213 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
214 sFastTrackMultiplier = (int) ul;
215 }
216 }
217}
218
219// ----------------------------------------------------------------------------
220
Eric Laurent81784c32012-11-19 14:55:58 -0800221#ifdef ADD_BATTERY_DATA
222// To collect the amplifier usage
223static void addBatteryData(uint32_t params) {
224 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
225 if (service == NULL) {
226 // it already logged
227 return;
228 }
229
230 service->addBatteryData(params);
231}
232#endif
233
Andy Hung3f0c9022016-01-15 17:49:46 -0800234// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
235struct {
236 // call when you acquire a partial wakelock
237 void acquire(const sp<IBinder> &wakeLockToken) {
238 pthread_mutex_lock(&mLock);
239 if (wakeLockToken.get() == nullptr) {
240 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
241 } else {
242 if (mCount == 0) {
243 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
244 }
245 ++mCount;
246 }
247 pthread_mutex_unlock(&mLock);
248 }
249
250 // call when you release a partial wakelock.
251 void release(const sp<IBinder> &wakeLockToken) {
252 if (wakeLockToken.get() == nullptr) {
253 return;
254 }
255 pthread_mutex_lock(&mLock);
256 if (--mCount < 0) {
257 ALOGE("negative wakelock count");
258 mCount = 0;
259 }
260 pthread_mutex_unlock(&mLock);
261 }
262
263 // retrieves the boottime timebase offset from monotonic.
264 int64_t getBoottimeOffset() {
265 pthread_mutex_lock(&mLock);
266 int64_t boottimeOffset = mBoottimeOffset;
267 pthread_mutex_unlock(&mLock);
268 return boottimeOffset;
269 }
270
271 // Adjusts the timebase offset between TIMEBASE_MONOTONIC
272 // and the selected timebase.
273 // Currently only TIMEBASE_BOOTTIME is allowed.
274 //
275 // This only needs to be called upon acquiring the first partial wakelock
276 // after all other partial wakelocks are released.
277 //
278 // We do an empirical measurement of the offset rather than parsing
279 // /proc/timer_list since the latter is not a formal kernel ABI.
280 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
281 int clockbase;
282 switch (timebase) {
283 case ExtendedTimestamp::TIMEBASE_BOOTTIME:
284 clockbase = SYSTEM_TIME_BOOTTIME;
285 break;
286 default:
287 LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
288 break;
289 }
290 // try three times to get the clock offset, choose the one
291 // with the minimum gap in measurements.
292 const int tries = 3;
293 nsecs_t bestGap, measured;
294 for (int i = 0; i < tries; ++i) {
295 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
296 const nsecs_t tbase = systemTime(clockbase);
297 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
298 const nsecs_t gap = tmono2 - tmono;
299 if (i == 0 || gap < bestGap) {
300 bestGap = gap;
301 measured = tbase - ((tmono + tmono2) >> 1);
302 }
303 }
304
305 // to avoid micro-adjusting, we don't change the timebase
306 // unless it is significantly different.
307 //
308 // Assumption: It probably takes more than toleranceNs to
309 // suspend and resume the device.
310 static int64_t toleranceNs = 10000; // 10 us
311 if (llabs(*offset - measured) > toleranceNs) {
312 ALOGV("Adjusting timebase offset old: %lld new: %lld",
313 (long long)*offset, (long long)measured);
314 *offset = measured;
315 }
316 }
317
318 pthread_mutex_t mLock;
319 int32_t mCount;
320 int64_t mBoottimeOffset;
321} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
Eric Laurent81784c32012-11-19 14:55:58 -0800322
323// ----------------------------------------------------------------------------
324// CPU Stats
325// ----------------------------------------------------------------------------
326
327class CpuStats {
328public:
329 CpuStats();
330 void sample(const String8 &title);
331#ifdef DEBUG_CPU_USAGE
332private:
333 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
334 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
335
336 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
337
338 int mCpuNum; // thread's current CPU number
339 int mCpukHz; // frequency of thread's current CPU in kHz
340#endif
341};
342
343CpuStats::CpuStats()
344#ifdef DEBUG_CPU_USAGE
345 : mCpuNum(-1), mCpukHz(-1)
346#endif
347{
348}
349
Glenn Kasten0f11b512014-01-31 16:18:54 -0800350void CpuStats::sample(const String8 &title
351#ifndef DEBUG_CPU_USAGE
352 __unused
353#endif
354 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800355#ifdef DEBUG_CPU_USAGE
356 // get current thread's delta CPU time in wall clock ns
357 double wcNs;
358 bool valid = mCpuUsage.sampleAndEnable(wcNs);
359
360 // record sample for wall clock statistics
361 if (valid) {
362 mWcStats.sample(wcNs);
363 }
364
365 // get the current CPU number
366 int cpuNum = sched_getcpu();
367
368 // get the current CPU frequency in kHz
369 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
370
371 // check if either CPU number or frequency changed
372 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
373 mCpuNum = cpuNum;
374 mCpukHz = cpukHz;
375 // ignore sample for purposes of cycles
376 valid = false;
377 }
378
379 // if no change in CPU number or frequency, then record sample for cycle statistics
380 if (valid && mCpukHz > 0) {
381 double cycles = wcNs * cpukHz * 0.000001;
382 mHzStats.sample(cycles);
383 }
384
385 unsigned n = mWcStats.n();
386 // mCpuUsage.elapsed() is expensive, so don't call it every loop
387 if ((n & 127) == 1) {
388 long long elapsed = mCpuUsage.elapsed();
389 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
390 double perLoop = elapsed / (double) n;
391 double perLoop100 = perLoop * 0.01;
392 double perLoop1k = perLoop * 0.001;
393 double mean = mWcStats.mean();
394 double stddev = mWcStats.stddev();
395 double minimum = mWcStats.minimum();
396 double maximum = mWcStats.maximum();
397 double meanCycles = mHzStats.mean();
398 double stddevCycles = mHzStats.stddev();
399 double minCycles = mHzStats.minimum();
400 double maxCycles = mHzStats.maximum();
401 mCpuUsage.resetElapsed();
402 mWcStats.reset();
403 mHzStats.reset();
404 ALOGD("CPU usage for %s over past %.1f secs\n"
405 " (%u mixer loops at %.1f mean ms per loop):\n"
406 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
407 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
408 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
409 title.string(),
410 elapsed * .000000001, n, perLoop * .000001,
411 mean * .001,
412 stddev * .001,
413 minimum * .001,
414 maximum * .001,
415 mean / perLoop100,
416 stddev / perLoop100,
417 minimum / perLoop100,
418 maximum / perLoop100,
419 meanCycles / perLoop1k,
420 stddevCycles / perLoop1k,
421 minCycles / perLoop1k,
422 maxCycles / perLoop1k);
423
424 }
425 }
426#endif
427};
428
429// ----------------------------------------------------------------------------
430// ThreadBase
431// ----------------------------------------------------------------------------
432
Glenn Kasten97b7b752014-09-28 13:04:24 -0700433// static
434const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
435{
436 switch (type) {
437 case MIXER:
438 return "MIXER";
439 case DIRECT:
440 return "DIRECT";
441 case DUPLICATING:
442 return "DUPLICATING";
443 case RECORD:
444 return "RECORD";
445 case OFFLOAD:
446 return "OFFLOAD";
447 default:
448 return "unknown";
449 }
450}
451
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800452String8 devicesToString(audio_devices_t devices)
453{
454 static const struct mapping {
455 audio_devices_t mDevices;
456 const char * mString;
457 } mappingsOut[] = {
Glenn Kasten818da522015-12-02 13:53:26 -0800458 {AUDIO_DEVICE_OUT_EARPIECE, "EARPIECE"},
459 {AUDIO_DEVICE_OUT_SPEAKER, "SPEAKER"},
460 {AUDIO_DEVICE_OUT_WIRED_HEADSET, "WIRED_HEADSET"},
461 {AUDIO_DEVICE_OUT_WIRED_HEADPHONE, "WIRED_HEADPHONE"},
462 {AUDIO_DEVICE_OUT_BLUETOOTH_SCO, "BLUETOOTH_SCO"},
463 {AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET, "BLUETOOTH_SCO_HEADSET"},
464 {AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT, "BLUETOOTH_SCO_CARKIT"},
465 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, "BLUETOOTH_A2DP"},
466 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,"BLUETOOTH_A2DP_HEADPHONES"},
467 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER, "BLUETOOTH_A2DP_SPEAKER"},
468 {AUDIO_DEVICE_OUT_AUX_DIGITAL, "AUX_DIGITAL"},
469 {AUDIO_DEVICE_OUT_HDMI, "HDMI"},
470 {AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET,"ANLG_DOCK_HEADSET"},
471 {AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET,"DGTL_DOCK_HEADSET"},
472 {AUDIO_DEVICE_OUT_USB_ACCESSORY, "USB_ACCESSORY"},
473 {AUDIO_DEVICE_OUT_USB_DEVICE, "USB_DEVICE"},
474 {AUDIO_DEVICE_OUT_TELEPHONY_TX, "TELEPHONY_TX"},
475 {AUDIO_DEVICE_OUT_LINE, "LINE"},
476 {AUDIO_DEVICE_OUT_HDMI_ARC, "HDMI_ARC"},
477 {AUDIO_DEVICE_OUT_SPDIF, "SPDIF"},
478 {AUDIO_DEVICE_OUT_FM, "FM"},
479 {AUDIO_DEVICE_OUT_AUX_LINE, "AUX_LINE"},
480 {AUDIO_DEVICE_OUT_SPEAKER_SAFE, "SPEAKER_SAFE"},
481 {AUDIO_DEVICE_OUT_IP, "IP"},
Eric Laurent58545be2016-02-22 18:54:20 -0800482 {AUDIO_DEVICE_OUT_BUS, "BUS"},
Glenn Kasten818da522015-12-02 13:53:26 -0800483 {AUDIO_DEVICE_NONE, "NONE"}, // must be last
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800484 }, mappingsIn[] = {
Glenn Kasten818da522015-12-02 13:53:26 -0800485 {AUDIO_DEVICE_IN_COMMUNICATION, "COMMUNICATION"},
486 {AUDIO_DEVICE_IN_AMBIENT, "AMBIENT"},
487 {AUDIO_DEVICE_IN_BUILTIN_MIC, "BUILTIN_MIC"},
488 {AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET, "BLUETOOTH_SCO_HEADSET"},
489 {AUDIO_DEVICE_IN_WIRED_HEADSET, "WIRED_HEADSET"},
490 {AUDIO_DEVICE_IN_AUX_DIGITAL, "AUX_DIGITAL"},
491 {AUDIO_DEVICE_IN_VOICE_CALL, "VOICE_CALL"},
492 {AUDIO_DEVICE_IN_TELEPHONY_RX, "TELEPHONY_RX"},
493 {AUDIO_DEVICE_IN_BACK_MIC, "BACK_MIC"},
494 {AUDIO_DEVICE_IN_REMOTE_SUBMIX, "REMOTE_SUBMIX"},
495 {AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET, "ANLG_DOCK_HEADSET"},
496 {AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET, "DGTL_DOCK_HEADSET"},
497 {AUDIO_DEVICE_IN_USB_ACCESSORY, "USB_ACCESSORY"},
498 {AUDIO_DEVICE_IN_USB_DEVICE, "USB_DEVICE"},
499 {AUDIO_DEVICE_IN_FM_TUNER, "FM_TUNER"},
500 {AUDIO_DEVICE_IN_TV_TUNER, "TV_TUNER"},
501 {AUDIO_DEVICE_IN_LINE, "LINE"},
502 {AUDIO_DEVICE_IN_SPDIF, "SPDIF"},
503 {AUDIO_DEVICE_IN_BLUETOOTH_A2DP, "BLUETOOTH_A2DP"},
504 {AUDIO_DEVICE_IN_LOOPBACK, "LOOPBACK"},
505 {AUDIO_DEVICE_IN_IP, "IP"},
Eric Laurent58545be2016-02-22 18:54:20 -0800506 {AUDIO_DEVICE_IN_BUS, "BUS"},
Glenn Kasten818da522015-12-02 13:53:26 -0800507 {AUDIO_DEVICE_NONE, "NONE"}, // must be last
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800508 };
509 String8 result;
510 audio_devices_t allDevices = AUDIO_DEVICE_NONE;
511 const mapping *entry;
512 if (devices & AUDIO_DEVICE_BIT_IN) {
513 devices &= ~AUDIO_DEVICE_BIT_IN;
514 entry = mappingsIn;
515 } else {
516 entry = mappingsOut;
517 }
518 for ( ; entry->mDevices != AUDIO_DEVICE_NONE; entry++) {
519 allDevices = (audio_devices_t) (allDevices | entry->mDevices);
520 if (devices & entry->mDevices) {
521 if (!result.isEmpty()) {
522 result.append("|");
523 }
524 result.append(entry->mString);
525 }
526 }
527 if (devices & ~allDevices) {
528 if (!result.isEmpty()) {
529 result.append("|");
530 }
531 result.appendFormat("0x%X", devices & ~allDevices);
532 }
533 if (result.isEmpty()) {
534 result.append(entry->mString);
535 }
536 return result;
537}
538
539String8 inputFlagsToString(audio_input_flags_t flags)
540{
541 static const struct mapping {
542 audio_input_flags_t mFlag;
543 const char * mString;
544 } mappings[] = {
Glenn Kasten818da522015-12-02 13:53:26 -0800545 {AUDIO_INPUT_FLAG_FAST, "FAST"},
546 {AUDIO_INPUT_FLAG_HW_HOTWORD, "HW_HOTWORD"},
547 {AUDIO_INPUT_FLAG_RAW, "RAW"},
548 {AUDIO_INPUT_FLAG_SYNC, "SYNC"},
549 {AUDIO_INPUT_FLAG_NONE, "NONE"}, // must be last
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800550 };
551 String8 result;
552 audio_input_flags_t allFlags = AUDIO_INPUT_FLAG_NONE;
553 const mapping *entry;
554 for (entry = mappings; entry->mFlag != AUDIO_INPUT_FLAG_NONE; entry++) {
555 allFlags = (audio_input_flags_t) (allFlags | entry->mFlag);
556 if (flags & entry->mFlag) {
557 if (!result.isEmpty()) {
558 result.append("|");
559 }
560 result.append(entry->mString);
561 }
562 }
563 if (flags & ~allFlags) {
564 if (!result.isEmpty()) {
565 result.append("|");
566 }
567 result.appendFormat("0x%X", flags & ~allFlags);
568 }
569 if (result.isEmpty()) {
570 result.append(entry->mString);
571 }
572 return result;
573}
574
575String8 outputFlagsToString(audio_output_flags_t flags)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700576{
577 static const struct mapping {
578 audio_output_flags_t mFlag;
579 const char * mString;
580 } mappings[] = {
Glenn Kasten818da522015-12-02 13:53:26 -0800581 {AUDIO_OUTPUT_FLAG_DIRECT, "DIRECT"},
582 {AUDIO_OUTPUT_FLAG_PRIMARY, "PRIMARY"},
583 {AUDIO_OUTPUT_FLAG_FAST, "FAST"},
584 {AUDIO_OUTPUT_FLAG_DEEP_BUFFER, "DEEP_BUFFER"},
585 {AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,"COMPRESS_OFFLOAD"},
586 {AUDIO_OUTPUT_FLAG_NON_BLOCKING, "NON_BLOCKING"},
587 {AUDIO_OUTPUT_FLAG_HW_AV_SYNC, "HW_AV_SYNC"},
588 {AUDIO_OUTPUT_FLAG_RAW, "RAW"},
589 {AUDIO_OUTPUT_FLAG_SYNC, "SYNC"},
590 {AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO, "IEC958_NONAUDIO"},
591 {AUDIO_OUTPUT_FLAG_NONE, "NONE"}, // must be last
Glenn Kasten97b7b752014-09-28 13:04:24 -0700592 };
593 String8 result;
594 audio_output_flags_t allFlags = AUDIO_OUTPUT_FLAG_NONE;
595 const mapping *entry;
596 for (entry = mappings; entry->mFlag != AUDIO_OUTPUT_FLAG_NONE; entry++) {
597 allFlags = (audio_output_flags_t) (allFlags | entry->mFlag);
598 if (flags & entry->mFlag) {
599 if (!result.isEmpty()) {
600 result.append("|");
601 }
602 result.append(entry->mString);
603 }
604 }
605 if (flags & ~allFlags) {
606 if (!result.isEmpty()) {
607 result.append("|");
608 }
609 result.appendFormat("0x%X", flags & ~allFlags);
610 }
611 if (result.isEmpty()) {
612 result.append(entry->mString);
613 }
614 return result;
615}
616
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800617const char *sourceToString(audio_source_t source)
618{
619 switch (source) {
620 case AUDIO_SOURCE_DEFAULT: return "default";
621 case AUDIO_SOURCE_MIC: return "mic";
622 case AUDIO_SOURCE_VOICE_UPLINK: return "voice uplink";
623 case AUDIO_SOURCE_VOICE_DOWNLINK: return "voice downlink";
624 case AUDIO_SOURCE_VOICE_CALL: return "voice call";
625 case AUDIO_SOURCE_CAMCORDER: return "camcorder";
626 case AUDIO_SOURCE_VOICE_RECOGNITION: return "voice recognition";
627 case AUDIO_SOURCE_VOICE_COMMUNICATION: return "voice communication";
628 case AUDIO_SOURCE_REMOTE_SUBMIX: return "remote submix";
rago8a397d52015-12-02 11:27:57 -0800629 case AUDIO_SOURCE_UNPROCESSED: return "unprocessed";
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800630 case AUDIO_SOURCE_FM_TUNER: return "FM tuner";
631 case AUDIO_SOURCE_HOTWORD: return "hotword";
632 default: return "unknown";
633 }
634}
635
Eric Laurent81784c32012-11-19 14:55:58 -0800636AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -0700637 audio_devices_t outDevice, audio_devices_t inDevice, type_t type, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -0800638 : Thread(false /*canCallJava*/),
639 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700640 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700641 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800642 // are set by PlaybackThread::readOutputParameters_l() or
643 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700644 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800645 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700646 mPrevOutDevice(AUDIO_DEVICE_NONE), mPrevInDevice(AUDIO_DEVICE_NONE),
647 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800648 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700649 mDeathRecipient(new PMDeathRecipient(this)),
Wei Jia3f273d12015-11-24 09:06:49 -0800650 mSystemReady(systemReady),
651 mNotifiedBatteryStart(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800652{
Eric Laurent296fb132015-05-01 11:38:42 -0700653 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800654}
655
656AudioFlinger::ThreadBase::~ThreadBase()
657{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700658 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700659 mConfigEvents.clear();
660
Eric Laurent81784c32012-11-19 14:55:58 -0800661 // do not lock the mutex in destructor
662 releaseWakeLock_l();
663 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800664 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800665 binder->unlinkToDeath(mDeathRecipient);
666 }
667}
668
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700669status_t AudioFlinger::ThreadBase::readyToRun()
670{
671 status_t status = initCheck();
672 if (status == NO_ERROR) {
673 ALOGI("AudioFlinger's thread %p ready to run", this);
674 } else {
675 ALOGE("No working audio driver found.");
676 }
677 return status;
678}
679
Eric Laurent81784c32012-11-19 14:55:58 -0800680void AudioFlinger::ThreadBase::exit()
681{
682 ALOGV("ThreadBase::exit");
683 // do any cleanup required for exit to succeed
684 preExit();
685 {
686 // This lock prevents the following race in thread (uniprocessor for illustration):
687 // if (!exitPending()) {
688 // // context switch from here to exit()
689 // // exit() calls requestExit(), what exitPending() observes
690 // // exit() calls signal(), which is dropped since no waiters
691 // // context switch back from exit() to here
692 // mWaitWorkCV.wait(...);
693 // // now thread is hung
694 // }
695 AutoMutex lock(mLock);
696 requestExit();
697 mWaitWorkCV.broadcast();
698 }
699 // When Thread::requestExitAndWait is made virtual and this method is renamed to
700 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
701 requestExitAndWait();
702}
703
704status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
705{
Eric Laurent81784c32012-11-19 14:55:58 -0800706 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
707 Mutex::Autolock _l(mLock);
708
Eric Laurent10351942014-05-08 18:49:52 -0700709 return sendSetParameterConfigEvent_l(keyValuePairs);
710}
711
712// sendConfigEvent_l() must be called with ThreadBase::mLock held
713// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
714status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
715{
716 status_t status = NO_ERROR;
717
Eric Laurent72e3f392015-05-20 14:43:50 -0700718 if (event->mRequiresSystemReady && !mSystemReady) {
719 event->mWaitStatus = false;
720 mPendingConfigEvents.add(event);
721 return status;
722 }
Eric Laurent10351942014-05-08 18:49:52 -0700723 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700724 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800725 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700726 mLock.unlock();
727 {
728 Mutex::Autolock _l(event->mLock);
729 while (event->mWaitStatus) {
730 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
731 event->mStatus = TIMED_OUT;
732 event->mWaitStatus = false;
733 }
734 }
735 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800736 }
Eric Laurent10351942014-05-08 18:49:52 -0700737 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800738 return status;
739}
740
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700741void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800742{
743 Mutex::Autolock _l(mLock);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700744 sendIoConfigEvent_l(event, pid);
Eric Laurent81784c32012-11-19 14:55:58 -0800745}
746
747// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700748void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800749{
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700750 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid);
Eric Laurent10351942014-05-08 18:49:52 -0700751 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800752}
753
Eric Laurent72e3f392015-05-20 14:43:50 -0700754void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio)
755{
756 Mutex::Autolock _l(mLock);
757 sendPrioConfigEvent_l(pid, tid, prio);
758}
759
Eric Laurent81784c32012-11-19 14:55:58 -0800760// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
761void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
762{
Eric Laurent10351942014-05-08 18:49:52 -0700763 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio);
764 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800765}
766
Eric Laurent10351942014-05-08 18:49:52 -0700767// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
768status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800769{
Andy Hung2ddee192015-12-18 17:34:44 -0800770 sp<ConfigEvent> configEvent;
771 AudioParameter param(keyValuePair);
772 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700773 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800774 setMasterMono_l(value != 0);
775 if (param.size() == 1) {
776 return NO_ERROR; // should be a solo parameter - we don't pass down
777 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700778 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800779 configEvent = new SetParameterConfigEvent(param.toString());
780 } else {
781 configEvent = new SetParameterConfigEvent(keyValuePair);
782 }
Eric Laurent10351942014-05-08 18:49:52 -0700783 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700784}
785
Eric Laurent1c333e22014-05-20 10:48:17 -0700786status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
787 const struct audio_patch *patch,
788 audio_patch_handle_t *handle)
789{
790 Mutex::Autolock _l(mLock);
791 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
792 status_t status = sendConfigEvent_l(configEvent);
793 if (status == NO_ERROR) {
794 CreateAudioPatchConfigEventData *data =
795 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
796 *handle = data->mHandle;
797 }
798 return status;
799}
800
801status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
802 const audio_patch_handle_t handle)
803{
804 Mutex::Autolock _l(mLock);
805 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
806 return sendConfigEvent_l(configEvent);
807}
808
809
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700810// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700811void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700812{
Eric Laurent10351942014-05-08 18:49:52 -0700813 bool configChanged = false;
814
Eric Laurent81784c32012-11-19 14:55:58 -0800815 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700816 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700817 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800818 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700819 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700820 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700821 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
822 // FIXME Need to understand why this has to be done asynchronously
823 int err = requestPriority(data->mPid, data->mTid, data->mPrio,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700824 true /*asynchronous*/);
825 if (err != 0) {
826 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700827 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700828 }
829 } break;
830 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700831 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700832 ioConfigChanged(data->mEvent, data->mPid);
Eric Laurent10351942014-05-08 18:49:52 -0700833 } break;
834 case CFG_EVENT_SET_PARAMETER: {
835 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
836 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
837 configChanged = true;
Glenn Kastend5418eb2013-08-14 13:11:06 -0700838 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700839 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700840 case CFG_EVENT_CREATE_AUDIO_PATCH: {
841 CreateAudioPatchConfigEventData *data =
842 (CreateAudioPatchConfigEventData *)event->mData.get();
843 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
844 } break;
845 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
846 ReleaseAudioPatchConfigEventData *data =
847 (ReleaseAudioPatchConfigEventData *)event->mData.get();
848 event->mStatus = releaseAudioPatch_l(data->mHandle);
849 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700850 default:
Eric Laurent10351942014-05-08 18:49:52 -0700851 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700852 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800853 }
Eric Laurent10351942014-05-08 18:49:52 -0700854 {
855 Mutex::Autolock _l(event->mLock);
856 if (event->mWaitStatus) {
857 event->mWaitStatus = false;
858 event->mCond.signal();
859 }
860 }
861 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
862 }
863
864 if (configChanged) {
865 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800866 }
Eric Laurent81784c32012-11-19 14:55:58 -0800867}
868
Marco Nelissenb2208842014-02-07 14:00:50 -0800869String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
870 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700871 const audio_channel_representation_t representation =
872 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700873
874 switch (representation) {
875 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
876 if (output) {
877 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
878 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
879 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
880 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
881 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
882 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
883 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
884 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
885 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
886 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
887 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
888 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
889 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
890 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
891 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
892 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
893 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
894 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
895 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
896 } else {
897 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
898 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
899 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
900 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
901 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
902 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
903 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
904 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
905 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
906 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
907 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
908 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
909 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
910 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
911 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
912 }
913 const int len = s.length();
914 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -0700915 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -0700916 s.unlockBuffer(len - 2); // remove trailing ", "
917 }
918 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800919 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700920 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
921 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
922 return s;
923 default:
924 s.appendFormat("unknown mask, representation:%d bits:%#x",
925 representation, audio_channel_mask_get_bits(mask));
926 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800927 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800928}
929
Glenn Kasten0f11b512014-01-31 16:18:54 -0800930void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800931{
932 const size_t SIZE = 256;
933 char buffer[SIZE];
934 String8 result;
935
936 bool locked = AudioFlinger::dumpTryLock(mLock);
937 if (!locked) {
Glenn Kasten97b7b752014-09-28 13:04:24 -0700938 dprintf(fd, "thread %p may be deadlocked\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -0800939 }
940
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800941 dprintf(fd, " Thread name: %s\n", mThreadName);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700942 dprintf(fd, " I/O handle: %d\n", mId);
943 dprintf(fd, " TID: %d\n", getTid());
944 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700945 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700946 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700947 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat));
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700948 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700949 dprintf(fd, " Channel count: %u\n", mChannelCount);
950 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800951 channelMaskToString(mChannelMask, mType != RECORD).string());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700952 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat));
953 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700954 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800955 size_t numConfig = mConfigEvents.size();
956 if (numConfig) {
957 for (size_t i = 0; i < numConfig; i++) {
958 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700959 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800960 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700961 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800962 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700963 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800964 }
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800965 dprintf(fd, " Output device: %#x (%s)\n", mOutDevice, devicesToString(mOutDevice).string());
966 dprintf(fd, " Input device: %#x (%s)\n", mInDevice, devicesToString(mInDevice).string());
967 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, sourceToString(mAudioSource));
Eric Laurent81784c32012-11-19 14:55:58 -0800968
969 if (locked) {
970 mLock.unlock();
971 }
972}
973
974void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
975{
976 const size_t SIZE = 256;
977 char buffer[SIZE];
978 String8 result;
979
Marco Nelissenb2208842014-02-07 14:00:50 -0800980 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000981 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800982 write(fd, buffer, strlen(buffer));
983
Marco Nelissenb2208842014-02-07 14:00:50 -0800984 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800985 sp<EffectChain> chain = mEffectChains[i];
986 if (chain != 0) {
987 chain->dump(fd, args);
988 }
989 }
990}
991
Marco Nelissene14a5d62013-10-03 08:51:24 -0700992void AudioFlinger::ThreadBase::acquireWakeLock(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800993{
994 Mutex::Autolock _l(mLock);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700995 acquireWakeLock_l(uid);
Eric Laurent81784c32012-11-19 14:55:58 -0800996}
997
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100998String16 AudioFlinger::ThreadBase::getWakeLockTag()
999{
1000 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -08001001 case MIXER:
1002 return String16("AudioMix");
1003 case DIRECT:
1004 return String16("AudioDirectOut");
1005 case DUPLICATING:
1006 return String16("AudioDup");
1007 case RECORD:
1008 return String16("AudioIn");
1009 case OFFLOAD:
1010 return String16("AudioOffload");
1011 default:
1012 ALOG_ASSERT(false);
1013 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001014 }
1015}
1016
Marco Nelissene14a5d62013-10-03 08:51:24 -07001017void AudioFlinger::ThreadBase::acquireWakeLock_l(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -08001018{
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001019 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001020 if (mPowerManager != 0) {
1021 sp<IBinder> binder = new BBinder();
Marco Nelissene14a5d62013-10-03 08:51:24 -07001022 status_t status;
1023 if (uid >= 0) {
Eric Laurent547789d2013-10-04 11:46:55 -07001024 status = mPowerManager->acquireWakeLockWithUid(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -07001025 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001026 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -07001027 String16("audioserver"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -07001028 uid,
1029 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -07001030 } else {
Eric Laurent547789d2013-10-04 11:46:55 -07001031 status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -07001032 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001033 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -07001034 String16("audioserver"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -07001035 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -07001036 }
Eric Laurent81784c32012-11-19 14:55:58 -08001037 if (status == NO_ERROR) {
1038 mWakeLockToken = binder;
1039 }
Glenn Kastend7dca052015-03-05 16:05:54 -08001040 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -08001041 }
Wei Jia3f273d12015-11-24 09:06:49 -08001042
1043 if (!mNotifiedBatteryStart) {
Wei Jiaf2ae3e12016-10-27 17:10:59 -07001044 // TODO: call this function for each track when it becomes active.
1045 BatteryNotifier::getInstance().noteStartAudio(AID_AUDIOSERVER);
Wei Jia3f273d12015-11-24 09:06:49 -08001046 mNotifiedBatteryStart = true;
1047 }
Andy Hung3f0c9022016-01-15 17:49:46 -08001048 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -08001049 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
1050 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -08001051}
1052
1053void AudioFlinger::ThreadBase::releaseWakeLock()
1054{
1055 Mutex::Autolock _l(mLock);
1056 releaseWakeLock_l();
1057}
1058
1059void AudioFlinger::ThreadBase::releaseWakeLock_l()
1060{
Andy Hung3f0c9022016-01-15 17:49:46 -08001061 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -08001062 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001063 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001064 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -07001065 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
1066 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -08001067 }
1068 mWakeLockToken.clear();
1069 }
Wei Jia3f273d12015-11-24 09:06:49 -08001070
1071 if (mNotifiedBatteryStart) {
Wei Jiaf2ae3e12016-10-27 17:10:59 -07001072 // TODO: call this function for each track when it becomes inactive.
1073 BatteryNotifier::getInstance().noteStopAudio(AID_AUDIOSERVER);
Wei Jia3f273d12015-11-24 09:06:49 -08001074 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);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07001931 for (audio_session_t session : {
1932 AUDIO_SESSION_OUTPUT_STAGE,
1933 AUDIO_SESSION_OUTPUT_MIX,
1934 sessionId,
1935 }) {
1936 sp<EffectChain> chain = getEffectChain_l(session);
1937 if (chain.get() != nullptr) {
1938 audio_output_flags_t old = *flags;
1939 chain->checkOutputFlagCompatibility(flags);
1940 if (old != *flags) {
1941 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
1942 (int)session, (int)old, (int)*flags);
1943 }
Eric Laurent4c415062016-06-17 16:14:16 -07001944 }
1945 }
1946 }
Eric Laurent122f7e72016-06-29 11:53:29 -07001947 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07001948 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
1949 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08001950 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001951 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
1952 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07001953 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001954 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08001955 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001956 audio_is_linear_pcm(format),
1957 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07001958 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08001959 }
1960 }
1961 // For normal PCM streaming tracks, update minimum frame count.
1962 // For compatibility with AudioTrack calculation, buffer depth is forced
1963 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1964 // This is probably too conservative, but legacy application code may depend on it.
1965 // If you change this calculation, also review the start threshold which is related.
Eric Laurent05067782016-06-01 18:27:28 -07001966 if (!(*flags & AUDIO_OUTPUT_FLAG_FAST)
Phil Burkfdb3c072016-02-09 10:47:02 -08001967 && audio_has_proportional_frames(format) && sharedBuffer == 0) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001968 // this must match AudioTrack.cpp calculateMinFrameCount().
1969 // TODO: Move to a common library
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001970 uint32_t latencyMs = 0;
1971 lStatus = mOutput->stream->getLatency(&latencyMs);
1972 if (lStatus != OK) {
1973 ALOGE("Error when retrieving output stream latency: %d", lStatus);
1974 goto Exit;
1975 }
Eric Laurent81784c32012-11-19 14:55:58 -08001976 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1977 if (minBufCount < 2) {
1978 minBufCount = 2;
1979 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07001980 // For normal mixing tracks, if speed is > 1.0f (normal), AudioTrack
1981 // or the client should compute and pass in a larger buffer request.
Andy Hung0e48d252015-01-26 11:43:15 -08001982 size_t minFrameCount =
Andy Hung8edb8dc2015-03-26 19:13:55 -07001983 minBufCount * sourceFramesNeededWithTimestretch(
1984 sampleRate, mNormalFrameCount,
1985 mSampleRate, AUDIO_TIMESTRETCH_SPEED_NORMAL /*speed*/);
Andy Hung0e48d252015-01-26 11:43:15 -08001986 if (frameCount < minFrameCount) { // including frameCount == 0
Eric Laurent81784c32012-11-19 14:55:58 -08001987 frameCount = minFrameCount;
1988 }
Eric Laurent81784c32012-11-19 14:55:58 -08001989 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001990 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001991
Glenn Kastenc3df8382014-03-13 15:05:25 -07001992 switch (mType) {
1993
1994 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08001995 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08001996 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001997 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1998 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001999 sampleRate, format, channelMask, mOutput, mFormat);
2000 lStatus = BAD_VALUE;
2001 goto Exit;
2002 }
2003 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002004 break;
2005
2006 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002007 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002008 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2009 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002010 sampleRate, format, channelMask, mOutput, mFormat);
2011 lStatus = BAD_VALUE;
2012 goto Exit;
2013 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002014 break;
2015
2016 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002017 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002018 ALOGE("createTrack_l() Bad parameter: format %#x \""
2019 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002020 format, mOutput, mFormat);
2021 lStatus = BAD_VALUE;
2022 goto Exit;
2023 }
Andy Hungcd044842014-08-07 11:04:34 -07002024 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002025 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2026 lStatus = BAD_VALUE;
2027 goto Exit;
2028 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002029 break;
2030
Eric Laurent81784c32012-11-19 14:55:58 -08002031 }
2032
2033 lStatus = initCheck();
2034 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002035 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002036 goto Exit;
2037 }
2038
2039 { // scope for mLock
2040 Mutex::Autolock _l(mLock);
2041
2042 // all tracks in same audio session must share the same routing strategy otherwise
2043 // conflicts will happen when tracks are moved from one output to another by audio policy
2044 // manager
2045 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
2046 for (size_t i = 0; i < mTracks.size(); ++i) {
2047 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002048 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002049 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
2050 if (sessionId == t->sessionId() && strategy != actual) {
2051 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2052 strategy, actual);
2053 lStatus = BAD_VALUE;
2054 goto Exit;
2055 }
2056 }
2057 }
2058
Glenn Kastend79072e2016-01-06 08:41:20 -08002059 track = new Track(this, client, streamType, sampleRate, format,
2060 channelMask, frameCount, NULL, sharedBuffer,
2061 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT);
Glenn Kasten03003332013-08-06 15:40:54 -07002062
Glenn Kasten03003332013-08-06 15:40:54 -07002063 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2064 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002065 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002066 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002067 goto Exit;
2068 }
2069 mTracks.add(track);
2070
2071 sp<EffectChain> chain = getEffectChain_l(sessionId);
2072 if (chain != 0) {
2073 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2074 track->setMainBuffer(chain->inBuffer());
2075 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
2076 chain->incTrackCnt();
2077 }
2078
Eric Laurent05067782016-06-01 18:27:28 -07002079 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002080 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2081 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2082 // so ask activity manager to do this on our behalf
2083 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
2084 }
2085 }
2086
2087 lStatus = NO_ERROR;
2088
2089Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002090 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002091 return track;
2092}
2093
2094uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2095{
2096 return latency;
2097}
2098
2099uint32_t AudioFlinger::PlaybackThread::latency() const
2100{
2101 Mutex::Autolock _l(mLock);
2102 return latency_l();
2103}
2104uint32_t AudioFlinger::PlaybackThread::latency_l() const
2105{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002106 uint32_t latency;
2107 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2108 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002109 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002110 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002111}
2112
2113void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2114{
2115 Mutex::Autolock _l(mLock);
2116 // Don't apply master volume in SW if our HAL can do it for us.
2117 if (mOutput && mOutput->audioHwDev &&
2118 mOutput->audioHwDev->canSetMasterVolume()) {
2119 mMasterVolume = 1.0;
2120 } else {
2121 mMasterVolume = value;
2122 }
2123}
2124
2125void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2126{
2127 Mutex::Autolock _l(mLock);
2128 // Don't apply master mute in SW if our HAL can do it for us.
2129 if (mOutput && mOutput->audioHwDev &&
2130 mOutput->audioHwDev->canSetMasterMute()) {
2131 mMasterMute = false;
2132 } else {
2133 mMasterMute = muted;
2134 }
2135}
2136
2137void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2138{
2139 Mutex::Autolock _l(mLock);
2140 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002141 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002142}
2143
2144void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2145{
2146 Mutex::Autolock _l(mLock);
2147 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002148 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002149}
2150
2151float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2152{
2153 Mutex::Autolock _l(mLock);
2154 return mStreamTypes[stream].volume;
2155}
2156
2157// addTrack_l() must be called with ThreadBase::mLock held
2158status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2159{
2160 status_t status = ALREADY_EXISTS;
2161
Eric Laurent81784c32012-11-19 14:55:58 -08002162 if (mActiveTracks.indexOf(track) < 0) {
2163 // the track is newly added, make sure it fills up all its
2164 // buffers before playing. This is to ensure the client will
2165 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002166 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002167 TrackBase::track_state state = track->mState;
2168 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002169 status = AudioSystem::startOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002170 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002171 mLock.lock();
2172 // abort track was stopped/paused while we released the lock
2173 if (state != track->mState) {
2174 if (status == NO_ERROR) {
2175 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002176 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002177 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002178 mLock.lock();
2179 }
2180 return INVALID_OPERATION;
2181 }
2182 // abort if start is rejected by audio policy manager
2183 if (status != NO_ERROR) {
2184 return PERMISSION_DENIED;
2185 }
2186#ifdef ADD_BATTERY_DATA
2187 // to track the speaker usage
2188 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2189#endif
2190 }
2191
Eric Laurent51716182016-02-29 18:00:56 -08002192 // set retry count for buffer fill
2193 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002194 if (track->isStopping_1()) {
2195 track->mRetryCount = kMaxTrackStopRetriesOffload;
2196 } else {
2197 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2198 }
2199 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002200 } else {
2201 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002202 track->mFillingUpStatus =
2203 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002204 }
2205
Eric Laurent81784c32012-11-19 14:55:58 -08002206 track->mResetDone = false;
2207 track->mPresentationCompleteFrames = 0;
2208 mActiveTracks.add(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002209 mWakeLockUids.add(track->uid());
2210 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07002211 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07002212 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2213 if (chain != 0) {
2214 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2215 track->sessionId());
2216 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002217 }
2218
2219 status = NO_ERROR;
2220 }
2221
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002222 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002223 return status;
2224}
2225
Eric Laurentbfb1b832013-01-07 09:53:42 -08002226bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002227{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002228 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002229 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002230 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2231 track->mState = TrackBase::STOPPED;
2232 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002233 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002234 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002235 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002236 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002237
2238 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002239}
2240
2241void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2242{
2243 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
2244 mTracks.remove(track);
2245 deleteTrackName_l(track->name());
2246 // redundant as track is about to be destroyed, for dumpsys only
2247 track->mName = -1;
2248 if (track->isFastTrack()) {
2249 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002250 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002251 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2252 mFastTrackAvailMask |= 1 << index;
2253 // redundant as track is about to be destroyed, for dumpsys only
2254 track->mFastIndex = -1;
2255 }
2256 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2257 if (chain != 0) {
2258 chain->decTrackCnt();
2259 }
2260}
2261
Eric Laurentede6c3b2013-09-19 14:37:46 -07002262void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002263{
2264 // Thread could be blocked waiting for async
2265 // so signal it to handle state changes immediately
2266 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
2267 // be lost so we also flag to prevent it blocking on mWaitWorkCV
2268 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002269 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002270}
2271
Eric Laurent81784c32012-11-19 14:55:58 -08002272String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2273{
Eric Laurent81784c32012-11-19 14:55:58 -08002274 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002275 String8 out_s8;
2276 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2277 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002278 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002279 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002280}
2281
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002282void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002283 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2284 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002285
Eric Laurent73e26b62015-04-27 16:55:58 -07002286 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002287
2288 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002289 case AUDIO_OUTPUT_OPENED:
2290 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002291 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002292 desc->mChannelMask = mChannelMask;
2293 desc->mSamplingRate = mSampleRate;
2294 desc->mFormat = mFormat;
2295 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002296 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002297 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002298 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002299 break;
2300
Eric Laurent73e26b62015-04-27 16:55:58 -07002301 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002302 default:
2303 break;
2304 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002305 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002306}
2307
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002308void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002309{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002310 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002311}
2312
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002313void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002314{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002315 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002316}
2317
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002318void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002319{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002320 mCallbackThread->setAsyncError();
2321}
2322
Eric Laurent3b4529e2013-09-05 18:09:19 -07002323void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002324{
2325 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002326 // reject out of sequence requests
2327 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2328 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002329 mWaitWorkCV.signal();
2330 }
2331}
2332
Eric Laurent3b4529e2013-09-05 18:09:19 -07002333void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002334{
2335 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002336 // reject out of sequence requests
2337 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
2338 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002339 mWaitWorkCV.signal();
2340 }
2341}
2342
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002343void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002344{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002345 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002346 mSampleRate = mOutput->getSampleRate();
2347 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002348 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002349 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002350 }
Andy Hung9a592762014-07-21 21:56:01 -07002351 if ((mType == MIXER || mType == DUPLICATING)
2352 && !isValidPcmSinkChannelMask(mChannelMask)) {
2353 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2354 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002355 }
Andy Hunge5412692014-05-16 11:25:07 -07002356 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002357
2358 // Get actual HAL format.
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002359 status_t result = mOutput->stream->getFormat(&mHALFormat);
2360 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002361 // Get format from the shim, which will be different than the HAL format
2362 // if playing compressed audio over HDMI passthrough.
2363 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002364 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002365 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002366 }
Andy Hung6146c082014-03-18 11:56:15 -07002367 if ((mType == MIXER || mType == DUPLICATING)
2368 && !isValidPcmSinkFormat(mFormat)) {
2369 LOG_FATAL("HAL format %#x not supported for mixed output",
2370 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002371 }
Phil Burk062e67a2015-02-11 13:40:50 -08002372 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002373 result = mOutput->stream->getBufferSize(&mBufferSize);
2374 LOG_ALWAYS_FATAL_IF(result != OK,
2375 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07002376 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002377 if (mFrameCount & 15) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002378 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002379 mFrameCount);
2380 }
2381
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002382 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
2383 if (mOutput->stream->setCallback(this) == OK) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002384 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002385 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002386 }
2387 }
2388
Eric Laurentd1f69b02014-12-15 14:33:13 -08002389 mHwSupportsPause = false;
2390 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002391 bool supportsPause = false, supportsResume = false;
2392 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
2393 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002394 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002395 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002396 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002397 } else if (supportsResume) {
2398 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08002399 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002400 }
2401 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002402 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2403 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2404 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002405
Andy Hungfbfc3952015-01-15 13:33:51 -08002406 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2407 // For best precision, we use float instead of the associated output
2408 // device format (typically PCM 16 bit).
2409
2410 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2411 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2412 mBufferSize = mFrameSize * mFrameCount;
2413
2414 // TODO: We currently use the associated output device channel mask and sample rate.
2415 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2416 // (if a valid mask) to avoid premature downmix.
2417 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2418 // instead of the output device sample rate to avoid loss of high frequency information.
2419 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2420 }
2421
Andy Hung09a50072014-02-27 14:30:47 -08002422 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002423 double multiplier = 1.0;
2424 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2425 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002426 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2427 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002428
Eric Laurent81784c32012-11-19 14:55:58 -08002429 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2430 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2431 maxNormalFrameCount = maxNormalFrameCount & ~15;
2432 if (maxNormalFrameCount < minNormalFrameCount) {
2433 maxNormalFrameCount = minNormalFrameCount;
2434 }
2435 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2436 if (multiplier <= 1.0) {
2437 multiplier = 1.0;
2438 } else if (multiplier <= 2.0) {
2439 if (2 * mFrameCount <= maxNormalFrameCount) {
2440 multiplier = 2.0;
2441 } else {
2442 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2443 }
2444 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002445 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002446 }
2447 }
2448 mNormalFrameCount = multiplier * mFrameCount;
2449 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002450 if (mType == MIXER || mType == DUPLICATING) {
2451 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2452 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002453 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002454 mNormalFrameCount);
2455
Andy Hung08fb1742015-05-31 23:22:10 -07002456 // Check if we want to throttle the processing to no more than 2x normal rate
2457 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002458 mThreadThrottleTimeMs = 0;
2459 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002460 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2461
Andy Hung010a1a12014-03-13 13:57:33 -07002462 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2463 // Originally this was int16_t[] array, need to remove legacy implications.
2464 free(mSinkBuffer);
2465 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002466 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2467 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2468 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002469 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002470
Andy Hung69aed5f2014-02-25 17:24:40 -08002471 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2472 // drives the output.
2473 free(mMixerBuffer);
2474 mMixerBuffer = NULL;
2475 if (mMixerBufferEnabled) {
2476 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2477 mMixerBufferSize = mNormalFrameCount * mChannelCount
2478 * audio_bytes_per_sample(mMixerBufferFormat);
2479 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2480 }
Andy Hung98ef9782014-03-04 14:46:50 -08002481 free(mEffectBuffer);
2482 mEffectBuffer = NULL;
2483 if (mEffectBufferEnabled) {
2484 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2485 mEffectBufferSize = mNormalFrameCount * mChannelCount
2486 * audio_bytes_per_sample(mEffectBufferFormat);
2487 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2488 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002489
Eric Laurent81784c32012-11-19 14:55:58 -08002490 // force reconfiguration of effect chains and engines to take new buffer size and audio
2491 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002492 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002493 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2494 // matter.
2495 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2496 Vector< sp<EffectChain> > effectChains = mEffectChains;
2497 for (size_t i = 0; i < effectChains.size(); i ++) {
2498 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2499 }
2500}
2501
2502
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002503status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002504{
2505 if (halFrames == NULL || dspFrames == NULL) {
2506 return BAD_VALUE;
2507 }
2508 Mutex::Autolock _l(mLock);
2509 if (initCheck() != NO_ERROR) {
2510 return INVALID_OPERATION;
2511 }
Andy Hung818e7a32016-02-16 18:08:07 -08002512 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002513 *halFrames = framesWritten;
2514
2515 if (isSuspended()) {
2516 // return an estimation of rendered frames when the output is suspended
2517 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002518 *dspFrames = (uint32_t)
2519 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002520 return NO_ERROR;
2521 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002522 status_t status;
2523 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002524 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002525 *dspFrames = (size_t)frames;
2526 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002527 }
2528}
2529
Eric Laurent4c415062016-06-17 16:14:16 -07002530// hasAudioSession_l() must be called with ThreadBase::mLock held
2531uint32_t AudioFlinger::PlaybackThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08002532{
Eric Laurent81784c32012-11-19 14:55:58 -08002533 uint32_t result = 0;
2534 if (getEffectChain_l(sessionId) != 0) {
2535 result = EFFECT_SESSION;
2536 }
2537
2538 for (size_t i = 0; i < mTracks.size(); ++i) {
2539 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002540 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002541 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07002542 if (track->isFastTrack()) {
2543 result |= FAST_SESSION;
2544 }
Eric Laurent81784c32012-11-19 14:55:58 -08002545 break;
2546 }
2547 }
2548
2549 return result;
2550}
2551
Glenn Kastend848eb42016-03-08 13:42:11 -08002552uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08002553{
2554 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2555 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2556 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2557 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2558 }
2559 for (size_t i = 0; i < mTracks.size(); i++) {
2560 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002561 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002562 return AudioSystem::getStrategyForStream(track->streamType());
2563 }
2564 }
2565 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2566}
2567
2568
Phil Burk062e67a2015-02-11 13:40:50 -08002569AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002570{
2571 Mutex::Autolock _l(mLock);
2572 return mOutput;
2573}
2574
Phil Burk062e67a2015-02-11 13:40:50 -08002575AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002576{
2577 Mutex::Autolock _l(mLock);
2578 AudioStreamOut *output = mOutput;
2579 mOutput = NULL;
2580 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2581 // must push a NULL and wait for ack
2582 mOutputSink.clear();
2583 mPipeSink.clear();
2584 mNormalSink.clear();
2585 return output;
2586}
2587
2588// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002589sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08002590{
2591 if (mOutput == NULL) {
2592 return NULL;
2593 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002594 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08002595}
2596
2597uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2598{
2599 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2600}
2601
2602status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2603{
2604 if (!isValidSyncEvent(event)) {
2605 return BAD_VALUE;
2606 }
2607
2608 Mutex::Autolock _l(mLock);
2609
2610 for (size_t i = 0; i < mTracks.size(); ++i) {
2611 sp<Track> track = mTracks[i];
2612 if (event->triggerSession() == track->sessionId()) {
2613 (void) track->setSyncEvent(event);
2614 return NO_ERROR;
2615 }
2616 }
2617
2618 return NAME_NOT_FOUND;
2619}
2620
2621bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2622{
2623 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2624}
2625
2626void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2627 const Vector< sp<Track> >& tracksToRemove)
2628{
2629 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002630 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002631 for (size_t i = 0 ; i < count ; i++) {
2632 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002633 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002634 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002635 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002636#ifdef ADD_BATTERY_DATA
2637 // to track the speaker usage
2638 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2639#endif
2640 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002641 AudioSystem::releaseOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002642 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002643 }
Eric Laurent81784c32012-11-19 14:55:58 -08002644 }
2645 }
2646 }
Eric Laurent81784c32012-11-19 14:55:58 -08002647}
2648
2649void AudioFlinger::PlaybackThread::checkSilentMode_l()
2650{
2651 if (!mMasterMute) {
2652 char value[PROPERTY_VALUE_MAX];
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07002653 if (mOutDevice == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) {
2654 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
2655 return;
2656 }
Eric Laurent81784c32012-11-19 14:55:58 -08002657 if (property_get("ro.audio.silent", value, "0") > 0) {
2658 char *endptr;
2659 unsigned long ul = strtoul(value, &endptr, 0);
2660 if (*endptr == '\0' && ul != 0) {
2661 ALOGD("Silence is golden");
2662 // The setprop command will not allow a property to be changed after
2663 // the first time it is set, so we don't have to worry about un-muting.
2664 setMasterMute_l(true);
2665 }
2666 }
2667 }
2668}
2669
2670// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002671ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002672{
Eric Laurent81784c32012-11-19 14:55:58 -08002673 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002674 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002675 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002676
2677 // If an NBAIO sink is present, use it to write the normal mixer's submix
2678 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002679
Andy Hung010a1a12014-03-13 13:57:33 -07002680 const size_t count = mBytesRemaining / mFrameSize;
2681
Simon Wilson2d590962012-11-29 15:18:50 -08002682 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002683 // update the setpoint when AudioFlinger::mScreenState changes
2684 uint32_t screenState = AudioFlinger::mScreenState;
2685 if (screenState != mScreenState) {
2686 mScreenState = screenState;
2687 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2688 if (pipe != NULL) {
2689 pipe->setAvgFrames((mScreenState & 1) ?
2690 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2691 }
2692 }
Andy Hung010a1a12014-03-13 13:57:33 -07002693 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002694 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002695 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002696 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002697 } else {
2698 bytesWritten = framesWritten;
2699 }
2700 // otherwise use the HAL / AudioStreamOut directly
2701 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002702 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002703
Eric Laurentbfb1b832013-01-07 09:53:42 -08002704 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002705 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2706 mWriteAckSequence += 2;
2707 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002708 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002709 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002710 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002711 // FIXME We should have an implementation of timestamps for direct output threads.
2712 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002713 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurent51716182016-02-29 18:00:56 -08002714
Eric Laurentbfb1b832013-01-07 09:53:42 -08002715 if (mUseAsyncWrite &&
2716 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2717 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002718 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002719 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002720 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002721 }
Eric Laurent81784c32012-11-19 14:55:58 -08002722 }
2723
Eric Laurent81784c32012-11-19 14:55:58 -08002724 mNumWrites++;
2725 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002726 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002727 return bytesWritten;
2728}
2729
2730void AudioFlinger::PlaybackThread::threadLoop_drain()
2731{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002732 bool supportsDrain = false;
2733 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002734 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2735 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002736 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2737 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002738 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002739 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002740 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07002741 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002742 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002743 }
2744}
2745
2746void AudioFlinger::PlaybackThread::threadLoop_exit()
2747{
Eric Laurent275e8e92014-11-30 15:14:47 -08002748 {
2749 Mutex::Autolock _l(mLock);
2750 for (size_t i = 0; i < mTracks.size(); i++) {
2751 sp<Track> track = mTracks[i];
2752 track->invalidate();
2753 }
2754 }
Eric Laurent81784c32012-11-19 14:55:58 -08002755}
2756
2757/*
2758The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002759 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002760 - mActiveSleepTimeUs from activeSleepTimeUs()
2761 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08002762 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
2763 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08002764 - maxPeriod from frame count and sample rate (MIXER only)
2765
2766The parameters that affect these derived values are:
2767 - frame count
2768 - frame size
2769 - sample rate
2770 - device type: A2DP or not
2771 - device latency
2772 - format: PCM or not
2773 - active sleep time
2774 - idle sleep time
2775*/
2776
2777void AudioFlinger::PlaybackThread::cacheParameters_l()
2778{
Andy Hung25c2dac2014-02-27 14:56:00 -08002779 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002780 mActiveSleepTimeUs = activeSleepTimeUs();
2781 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08002782
2783 // make sure standby delay is not too short when connected to an A2DP sink to avoid
2784 // truncating audio when going to standby.
2785 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
2786 if ((mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != 0) {
2787 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
2788 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
2789 }
2790 }
Eric Laurent81784c32012-11-19 14:55:58 -08002791}
2792
Eric Laurent13084622016-05-17 10:51:49 -07002793bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08002794{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002795 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08002796 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07002797 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002798 size_t size = mTracks.size();
2799 for (size_t i = 0; i < size; i++) {
2800 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07002801 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002802 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07002803 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002804 }
2805 }
Eric Laurent13084622016-05-17 10:51:49 -07002806 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08002807}
2808
Haynes Mathew George05317d22016-05-03 16:34:26 -07002809void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2810{
2811 Mutex::Autolock _l(mLock);
2812 invalidateTracks_l(streamType);
2813}
2814
Eric Laurent81784c32012-11-19 14:55:58 -08002815status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2816{
Glenn Kastend848eb42016-03-08 13:42:11 -08002817 audio_session_t session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002818 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2819 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002820 bool ownsBuffer = false;
2821
2822 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Glenn Kastend848eb42016-03-08 13:42:11 -08002823 if (session > AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002824 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002825 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002826 if (mType != DIRECT) {
2827 size_t numSamples = mNormalFrameCount * mChannelCount;
2828 buffer = new int16_t[numSamples];
2829 memset(buffer, 0, numSamples * sizeof(int16_t));
2830 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2831 ownsBuffer = true;
2832 }
2833
2834 // Attach all tracks with same session ID to this chain.
2835 for (size_t i = 0; i < mTracks.size(); ++i) {
2836 sp<Track> track = mTracks[i];
2837 if (session == track->sessionId()) {
2838 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2839 buffer);
2840 track->setMainBuffer(buffer);
2841 chain->incTrackCnt();
2842 }
2843 }
2844
2845 // indicate all active tracks in the chain
2846 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2847 sp<Track> track = mActiveTracks[i].promote();
2848 if (track == 0) {
2849 continue;
2850 }
2851 if (session == track->sessionId()) {
2852 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2853 chain->incActiveTrackCnt();
2854 }
2855 }
2856 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002857 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08002858 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002859 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2860 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002861 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Glenn Kastend848eb42016-03-08 13:42:11 -08002862 // chains list in order to be processed last as it contains output stage effects.
Eric Laurent81784c32012-11-19 14:55:58 -08002863 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2864 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08002865 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08002866 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08002867 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08002868 // Effect chain for other sessions are inserted at beginning of effect
2869 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08002870 // sessions is not important.
2871 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
2872 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX,
2873 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08002874 size_t size = mEffectChains.size();
2875 size_t i = 0;
2876 for (i = 0; i < size; i++) {
2877 if (mEffectChains[i]->sessionId() < session) {
2878 break;
2879 }
2880 }
2881 mEffectChains.insertAt(chain, i);
2882 checkSuspendOnAddEffectChain_l(chain);
2883
2884 return NO_ERROR;
2885}
2886
2887size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2888{
Glenn Kastend848eb42016-03-08 13:42:11 -08002889 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08002890
2891 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2892
2893 for (size_t i = 0; i < mEffectChains.size(); i++) {
2894 if (chain == mEffectChains[i]) {
2895 mEffectChains.removeAt(i);
2896 // detach all active tracks from the chain
2897 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2898 sp<Track> track = mActiveTracks[i].promote();
2899 if (track == 0) {
2900 continue;
2901 }
2902 if (session == track->sessionId()) {
2903 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2904 chain.get(), session);
2905 chain->decActiveTrackCnt();
2906 }
2907 }
2908
2909 // detach all tracks with same session ID from this chain
2910 for (size_t i = 0; i < mTracks.size(); ++i) {
2911 sp<Track> track = mTracks[i];
2912 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002913 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002914 chain->decTrackCnt();
2915 }
2916 }
2917 break;
2918 }
2919 }
2920 return mEffectChains.size();
2921}
2922
2923status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002924 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08002925{
2926 Mutex::Autolock _l(mLock);
2927 return attachAuxEffect_l(track, EffectId);
2928}
2929
2930status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002931 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08002932{
2933 status_t status = NO_ERROR;
2934
2935 if (EffectId == 0) {
2936 track->setAuxBuffer(0, NULL);
2937 } else {
2938 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2939 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2940 if (effect != 0) {
2941 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2942 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2943 } else {
2944 status = INVALID_OPERATION;
2945 }
2946 } else {
2947 status = BAD_VALUE;
2948 }
2949 }
2950 return status;
2951}
2952
2953void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2954{
2955 for (size_t i = 0; i < mTracks.size(); ++i) {
2956 sp<Track> track = mTracks[i];
2957 if (track->auxEffectId() == effectId) {
2958 attachAuxEffect_l(track, 0);
2959 }
2960 }
2961}
2962
2963bool AudioFlinger::PlaybackThread::threadLoop()
2964{
2965 Vector< sp<Track> > tracksToRemove;
2966
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002967 mStandbyTimeNs = systemTime();
Andy Hung69488c42016-05-16 18:43:33 -07002968 nsecs_t lastWriteFinished = -1; // time last server write completed
2969 int64_t lastFramesWritten = -1; // track changes in timestamp server frames written
Eric Laurent81784c32012-11-19 14:55:58 -08002970
2971 // MIXER
2972 nsecs_t lastWarning = 0;
2973
2974 // DUPLICATING
2975 // FIXME could this be made local to while loop?
2976 writeFrames = 0;
2977
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002978 int lastGeneration = 0;
2979
Eric Laurent81784c32012-11-19 14:55:58 -08002980 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002981 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002982
2983 if (mType == MIXER) {
2984 sleepTimeShift = 0;
2985 }
2986
2987 CpuStats cpuStats;
2988 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2989
2990 acquireWakeLock();
2991
Glenn Kasten9e58b552013-01-18 15:09:48 -08002992 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2993 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2994 // and then that string will be logged at the next convenient opportunity.
2995 const char *logString = NULL;
2996
Eric Laurent664539d2013-09-23 18:24:31 -07002997 checkSilentMode_l();
2998
Eric Laurent81784c32012-11-19 14:55:58 -08002999 while (!exitPending())
3000 {
3001 cpuStats.sample(myName);
3002
3003 Vector< sp<EffectChain> > effectChains;
3004
Eric Laurent81784c32012-11-19 14:55:58 -08003005 { // scope for mLock
3006
3007 Mutex::Autolock _l(mLock);
3008
Eric Laurent021cf962014-05-13 10:18:14 -07003009 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07003010
Glenn Kasten9e58b552013-01-18 15:09:48 -08003011 if (logString != NULL) {
3012 mNBLogWriter->logTimestamp();
3013 mNBLogWriter->log(logString);
3014 logString = NULL;
3015 }
3016
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003017 // Gather the framesReleased counters for all active tracks,
Andy Hunge10393e2015-06-12 13:59:33 -07003018 // and associate with the sink frames written out. We need
3019 // this to convert the sink timestamp to the track timestamp.
Andy Hung69488c42016-05-16 18:43:33 -07003020 bool kernelLocationUpdate = false;
Andy Hunge10393e2015-06-12 13:59:33 -07003021 if (mNormalSink != 0) {
Andy Hungc54b1ff2016-02-23 14:07:07 -08003022 // Note: The DuplicatingThread may not have a mNormalSink.
Andy Hung818e7a32016-02-16 18:08:07 -08003023 // We always fetch the timestamp here because often the downstream
Andy Hung69488c42016-05-16 18:43:33 -07003024 // sink will block while writing.
Andy Hung818e7a32016-02-16 18:08:07 -08003025 ExtendedTimestamp timestamp; // use private copy to fetch
3026 (void) mNormalSink->getTimestamp(timestamp);
Andy Hung6d7b1192016-05-07 22:59:48 -07003027
3028 // We keep track of the last valid kernel position in case we are in underrun
3029 // and the normal mixer period is the same as the fast mixer period, or there
3030 // is some error from the HAL.
3031 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3032 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3033 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
3034 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3035 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
3036
3037 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3038 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
3039 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3040 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
Andy Hung69488c42016-05-16 18:43:33 -07003041 }
3042
3043 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3044 kernelLocationUpdate = true;
Andy Hung6d7b1192016-05-07 22:59:48 -07003045 } else {
Eric Laurent122f7e72016-06-29 11:53:29 -07003046 ALOGVV("getTimestamp error - no valid kernel position");
Andy Hung6d7b1192016-05-07 22:59:48 -07003047 }
3048
Andy Hung818e7a32016-02-16 18:08:07 -08003049 // copy over kernel info
3050 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
Andy Hung238fa3d2016-07-28 10:53:22 -07003051 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3052 + mSuspendedFrames; // add frames discarded when suspended
Andy Hung818e7a32016-02-16 18:08:07 -08003053 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
3054 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hungc54b1ff2016-02-23 14:07:07 -08003055 }
3056 // mFramesWritten for non-offloaded tracks are contiguous
3057 // even after standby() is called. This is useful for the track frame
3058 // to sink frame mapping.
Andy Hung69488c42016-05-16 18:43:33 -07003059 bool serverLocationUpdate = false;
3060 if (mFramesWritten != lastFramesWritten) {
3061 serverLocationUpdate = true;
3062 lastFramesWritten = mFramesWritten;
3063 }
3064 // Only update timestamps if there is a meaningful change.
3065 // Either the kernel timestamp must be valid or we have written something.
3066 if (kernelLocationUpdate || serverLocationUpdate) {
3067 if (serverLocationUpdate) {
3068 // use the time before we called the HAL write - it is a bit more accurate
3069 // to when the server last read data than the current time here.
3070 //
3071 // If we haven't written anything, mLastWriteTime will be -1
3072 // and we use systemTime().
3073 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
3074 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastWriteTime == -1
3075 ? systemTime() : mLastWriteTime;
3076 }
3077 const size_t size = mActiveTracks.size();
3078 for (size_t i = 0; i < size; ++i) {
3079 sp<Track> t = mActiveTracks[i].promote();
3080 if (t != 0 && !t->isFastTrack()) {
3081 t->updateTrackFrameInfo(
3082 t->mAudioTrackServerProxy->framesReleased(),
3083 mFramesWritten,
3084 mTimestamp);
3085 }
Andy Hunge10393e2015-06-12 13:59:33 -07003086 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07003087 }
3088
Eric Laurent81784c32012-11-19 14:55:58 -08003089 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003090 if (mSignalPending) {
3091 // A signal was raised while we were unlocked
3092 mSignalPending = false;
3093 } else if (waitingAsyncCallback_l()) {
3094 if (exitPending()) {
3095 break;
3096 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003097 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003098 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003099 releaseWakeLock_l();
3100 released = true;
Mikhail Naganove94c27a2016-08-18 17:31:46 -07003101 mWakeLockUids.clear();
3102 mActiveTracksGeneration++;
Marco Nelissen078538c2015-05-12 09:17:57 -07003103 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003104 ALOGV("wait async completion");
3105 mWaitWorkCV.wait(mLock);
3106 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003107 if (released) {
3108 acquireWakeLock_l();
3109 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003110 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3111 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003112
3113 continue;
3114 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003115 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003116 isSuspended()) {
3117 // put audio hardware into standby after short delay
3118 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003119
3120 threadLoop_standby();
3121
3122 mStandby = true;
3123 }
3124
3125 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
3126 // we're about to wait, flush the binder command buffer
3127 IPCThreadState::self()->flushCommands();
3128
3129 clearOutputTracks();
3130
3131 if (exitPending()) {
3132 break;
3133 }
3134
3135 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003136 mWakeLockUids.clear();
3137 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08003138 // wait until we have something to do...
3139 ALOGV("%s going to sleep", myName.string());
3140 mWaitWorkCV.wait(mLock);
3141 ALOGV("%s waking up", myName.string());
3142 acquireWakeLock_l();
3143
3144 mMixerStatus = MIXER_IDLE;
3145 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3146 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003147 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003148 checkSilentMode_l();
3149
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003150 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3151 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003152 if (mType == MIXER) {
3153 sleepTimeShift = 0;
3154 }
3155
3156 continue;
3157 }
3158 }
Eric Laurent81784c32012-11-19 14:55:58 -08003159 // mMixerStatusIgnoringFastTracks is also updated internally
3160 mMixerStatus = prepareTracks_l(&tracksToRemove);
3161
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003162 // compare with previously applied list
3163 if (lastGeneration != mActiveTracksGeneration) {
3164 // update wakelock
3165 updateWakeLockUids_l(mWakeLockUids);
3166 lastGeneration = mActiveTracksGeneration;
3167 }
3168
Eric Laurent81784c32012-11-19 14:55:58 -08003169 // prevent any changes in effect chain list and in each effect chain
3170 // during mixing and effect process as the audio buffers could be deleted
3171 // or modified if an effect is created or deleted
3172 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003173 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003174
Eric Laurentbfb1b832013-01-07 09:53:42 -08003175 if (mBytesRemaining == 0) {
3176 mCurrentWriteLength = 0;
3177 if (mMixerStatus == MIXER_TRACKS_READY) {
3178 // threadLoop_mix() sets mCurrentWriteLength
3179 threadLoop_mix();
3180 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3181 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003182 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003183 // must be written to HAL
3184 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003185 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003186 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003187 }
3188 }
Andy Hung98ef9782014-03-04 14:46:50 -08003189 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003190 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003191 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3192 // or mSinkBuffer (if there are no effects).
3193 //
3194 // This is done pre-effects computation; if effects change to
3195 // support higher precision, this needs to move.
3196 //
3197 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003198 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003199 if (mMixerBufferValid) {
3200 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3201 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3202
Andy Hung2ddee192015-12-18 17:34:44 -08003203 // mono blend occurs for mixer threads only (not direct or offloaded)
3204 // and is handled here if we're going directly to the sink.
3205 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003206 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3207 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003208 }
3209
Andy Hung98ef9782014-03-04 14:46:50 -08003210 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
3211 mNormalFrameCount * mChannelCount);
3212 }
3213
Eric Laurentbfb1b832013-01-07 09:53:42 -08003214 mBytesRemaining = mCurrentWriteLength;
3215 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003216 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3217 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3218 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3219 mBytesWritten += mBytesRemaining;
3220 mFramesWritten += framesRemaining;
3221 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003222 mBytesRemaining = 0;
3223 }
Eric Laurent81784c32012-11-19 14:55:58 -08003224
Eric Laurentbfb1b832013-01-07 09:53:42 -08003225 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003226 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003227 for (size_t i = 0; i < effectChains.size(); i ++) {
3228 effectChains[i]->process_l();
3229 }
Eric Laurent81784c32012-11-19 14:55:58 -08003230 }
3231 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003232 // Process effect chains for offloaded thread even if no audio
3233 // was read from audio track: process only updates effect state
3234 // and thus does have to be synchronized with audio writes but may have
3235 // to be called while waiting for async write callback
3236 if (mType == OFFLOAD) {
3237 for (size_t i = 0; i < effectChains.size(); i ++) {
3238 effectChains[i]->process_l();
3239 }
3240 }
Eric Laurent81784c32012-11-19 14:55:58 -08003241
Andy Hung98ef9782014-03-04 14:46:50 -08003242 // Only if the Effects buffer is enabled and there is data in the
3243 // Effects buffer (buffer valid), we need to
3244 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003245 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003246 if (mEffectBufferValid) {
3247 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003248
3249 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003250 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3251 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003252 }
3253
Andy Hung98ef9782014-03-04 14:46:50 -08003254 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
3255 mNormalFrameCount * mChannelCount);
3256 }
3257
Eric Laurent81784c32012-11-19 14:55:58 -08003258 // enable changes in effect chain
3259 unlockEffectChains(effectChains);
3260
Eric Laurentbfb1b832013-01-07 09:53:42 -08003261 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003262 // mSleepTimeUs == 0 means we must write to audio hardware
3263 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003264 ssize_t ret = 0;
Andy Hung69488c42016-05-16 18:43:33 -07003265 // We save lastWriteFinished here, as previousLastWriteFinished,
3266 // for throttling. On thread start, previousLastWriteFinished will be
3267 // set to -1, which properly results in no throttling after the first write.
3268 nsecs_t previousLastWriteFinished = lastWriteFinished;
3269 nsecs_t delta = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003270 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003271 // FIXME rewrite to reduce number of system calls
3272 mLastWriteTime = systemTime(); // also used for dumpsys
Andy Hung08fb1742015-05-31 23:22:10 -07003273 ret = threadLoop_write();
Andy Hung69488c42016-05-16 18:43:33 -07003274 lastWriteFinished = systemTime();
3275 delta = lastWriteFinished - mLastWriteTime;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003276 if (ret < 0) {
3277 mBytesRemaining = 0;
3278 } else {
3279 mBytesWritten += ret;
3280 mBytesRemaining -= ret;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003281 mFramesWritten += ret / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003282 }
3283 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3284 (mMixerStatus == MIXER_DRAIN_ALL)) {
3285 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003286 }
Andy Hung08fb1742015-05-31 23:22:10 -07003287 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003288 // write blocked detection
Andy Hung08fb1742015-05-31 23:22:10 -07003289 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003290 mNumDelayedWrites++;
Andy Hung69488c42016-05-16 18:43:33 -07003291 if ((lastWriteFinished - lastWarning) > kWarningThrottleNs) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003292 ATRACE_NAME("underrun");
3293 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003294 (unsigned long long) ns2ms(delta), mNumDelayedWrites, this);
Andy Hung69488c42016-05-16 18:43:33 -07003295 lastWarning = lastWriteFinished;
Glenn Kasten4944acb2013-08-19 08:39:20 -07003296 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003297 }
Andy Hung08fb1742015-05-31 23:22:10 -07003298
3299 if (mThreadThrottle
3300 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
3301 && ret > 0) { // we wrote something
3302 // Limit MixerThread data processing to no more than twice the
3303 // expected processing rate.
3304 //
3305 // This helps prevent underruns with NuPlayer and other applications
3306 // which may set up buffers that are close to the minimum size, or use
3307 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3308 //
3309 // The throttle smooths out sudden large data drains from the device,
3310 // e.g. when it comes out of standby, which often causes problems with
3311 // (1) mixer threads without a fast mixer (which has its own warm-up)
3312 // (2) minimum buffer sized tracks (even if the track is full,
3313 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07003314 //
3315 // Total time spent in last processing cycle equals time spent in
3316 // 1. threadLoop_write, as well as time spent in
3317 // 2. threadLoop_mix (significant for heavy mixing, especially
3318 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07003319
Andy Hung69488c42016-05-16 18:43:33 -07003320 // it's OK if deltaMs is an overestimate.
3321 const int32_t deltaMs =
3322 (lastWriteFinished - previousLastWriteFinished) / 1000000;
Andy Hung08fb1742015-05-31 23:22:10 -07003323 const int32_t throttleMs = mHalfBufferMs - deltaMs;
3324 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3325 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003326 // notify of throttle start on verbose log
3327 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3328 "mixer(%p) throttle begin:"
3329 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003330 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003331 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07003332 // Throttle must be attributed to the previous mixer loop's write time
3333 // to allow back-to-back throttling.
3334 lastWriteFinished += throttleMs * 1000000;
Andy Hung40eb1a12015-06-18 13:42:02 -07003335 } else {
3336 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3337 if (diff > 0) {
3338 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07003339 // but prevent spamming for bluetooth
3340 ALOGD_IF(!audio_is_a2dp_out_device(outDevice()),
3341 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07003342 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3343 }
Andy Hung08fb1742015-05-31 23:22:10 -07003344 }
3345 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003346 }
Eric Laurent81784c32012-11-19 14:55:58 -08003347
Eric Laurentbfb1b832013-01-07 09:53:42 -08003348 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003349 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07003350 Mutex::Autolock _l(mLock);
3351 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
3352 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08003353 }
Glenn Kastene7754022014-10-31 12:11:26 -07003354 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003355 }
Eric Laurent81784c32012-11-19 14:55:58 -08003356 }
3357
3358 // Finally let go of removed track(s), without the lock held
3359 // since we can't guarantee the destructors won't acquire that
3360 // same lock. This will also mutate and push a new fast mixer state.
3361 threadLoop_removeTracks(tracksToRemove);
3362 tracksToRemove.clear();
3363
3364 // FIXME I don't understand the need for this here;
3365 // it was in the original code but maybe the
3366 // assignment in saveOutputTracks() makes this unnecessary?
3367 clearOutputTracks();
3368
3369 // Effect chains will be actually deleted here if they were removed from
3370 // mEffectChains list during mixing or effects processing
3371 effectChains.clear();
3372
3373 // FIXME Note that the above .clear() is no longer necessary since effectChains
3374 // is now local to this block, but will keep it for now (at least until merge done).
3375 }
3376
Eric Laurentbfb1b832013-01-07 09:53:42 -08003377 threadLoop_exit();
3378
Eric Laurentcf817a22014-08-04 20:36:31 -07003379 if (!mStandby) {
3380 threadLoop_standby();
3381 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003382 }
3383
3384 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003385 mWakeLockUids.clear();
3386 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08003387
3388 ALOGV("Thread %p type %d exiting", this, mType);
3389 return false;
3390}
3391
Eric Laurentbfb1b832013-01-07 09:53:42 -08003392// removeTracks_l() must be called with ThreadBase::mLock held
3393void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3394{
3395 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003396 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003397 for (size_t i=0 ; i<count ; i++) {
3398 const sp<Track>& track = tracksToRemove.itemAt(i);
3399 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003400 mWakeLockUids.remove(track->uid());
3401 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003402 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3403 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3404 if (chain != 0) {
3405 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3406 track->sessionId());
3407 chain->decActiveTrackCnt();
3408 }
3409 if (track->isTerminated()) {
3410 removeTrack_l(track);
3411 }
3412 }
3413 }
3414
3415}
Eric Laurent81784c32012-11-19 14:55:58 -08003416
Eric Laurentaccc1472013-09-20 09:36:34 -07003417status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3418{
3419 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08003420 ExtendedTimestamp ets;
3421 status_t status = mNormalSink->getTimestamp(ets);
3422 if (status == NO_ERROR) {
3423 status = ets.getBestTimestamp(&timestamp);
3424 }
3425 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07003426 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003427 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003428 uint64_t position64;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003429 if (mOutput->getPresentationPosition(&position64, &timestamp.mTime) == OK) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003430 timestamp.mPosition = (uint32_t)position64;
3431 return NO_ERROR;
3432 }
3433 }
3434 return INVALID_OPERATION;
3435}
Eric Laurent1c333e22014-05-20 10:48:17 -07003436
Eric Laurent054d9d32015-04-24 08:48:48 -07003437status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3438 audio_patch_handle_t *handle)
3439{
Andy Hungf60abce2016-08-26 11:37:54 -07003440 status_t status;
3441 if (property_get_bool("af.patch_park", false /* default_value */)) {
3442 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3443 // or if HAL does not properly lock against access.
3444 AutoPark<FastMixer> park(mFastMixer);
3445 status = PlaybackThread::createAudioPatch_l(patch, handle);
3446 } else {
3447 status = PlaybackThread::createAudioPatch_l(patch, handle);
3448 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003449 return status;
3450}
3451
Eric Laurent1c333e22014-05-20 10:48:17 -07003452status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3453 audio_patch_handle_t *handle)
3454{
3455 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003456
3457 // store new device and send to effects
3458 audio_devices_t type = AUDIO_DEVICE_NONE;
3459 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3460 type |= patch->sinks[i].ext.device.type;
3461 }
3462
3463#ifdef ADD_BATTERY_DATA
3464 // when changing the audio output device, call addBatteryData to notify
3465 // the change
3466 if (mOutDevice != type) {
3467 uint32_t params = 0;
3468 // check whether speaker is on
3469 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3470 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003471 }
3472
Eric Laurent054d9d32015-04-24 08:48:48 -07003473 audio_devices_t deviceWithoutSpeaker
3474 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3475 // check if any other device (except speaker) is on
3476 if (type & deviceWithoutSpeaker) {
3477 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3478 }
3479
3480 if (params != 0) {
3481 addBatteryData(params);
3482 }
3483 }
3484#endif
3485
3486 for (size_t i = 0; i < mEffectChains.size(); i++) {
3487 mEffectChains[i]->setDevice_l(type);
3488 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003489
3490 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3491 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3492 bool configChanged = mPrevOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003493 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003494 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003495
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003496 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003497 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3498 status = hwDevice->createAudioPatch(patch->num_sources,
3499 patch->sources,
3500 patch->num_sinks,
3501 patch->sinks,
3502 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003503 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003504 char *address;
3505 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3506 //FIXME: we only support address on first sink with HAL version < 3.0
3507 address = audio_device_address_to_parameter(
3508 patch->sinks[0].ext.device.type,
3509 patch->sinks[0].ext.device.address);
3510 } else {
3511 address = (char *)calloc(1, 1);
3512 }
3513 AudioParameter param = AudioParameter(String8(address));
3514 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07003515 param.addInt(String8(AudioParameter::keyRouting), (int)type);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003516 status = mOutput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07003517 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003518 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003519 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003520 mPrevOutDevice = type;
Eric Laurente8726fe2015-06-26 09:39:24 -07003521 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3522 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003523 return status;
3524}
3525
Eric Laurent054d9d32015-04-24 08:48:48 -07003526status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3527{
Andy Hungf60abce2016-08-26 11:37:54 -07003528 status_t status;
3529 if (property_get_bool("af.patch_park", false /* default_value */)) {
3530 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3531 // or if HAL does not properly lock against access.
3532 AutoPark<FastMixer> park(mFastMixer);
3533 status = PlaybackThread::releaseAudioPatch_l(handle);
3534 } else {
3535 status = PlaybackThread::releaseAudioPatch_l(handle);
3536 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003537 return status;
3538}
3539
Eric Laurent1c333e22014-05-20 10:48:17 -07003540status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3541{
3542 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003543
3544 mOutDevice = AUDIO_DEVICE_NONE;
3545
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003546 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003547 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3548 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003549 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003550 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07003551 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003552 status = mOutput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07003553 }
3554 return status;
3555}
3556
Eric Laurent83b88082014-06-20 18:31:16 -07003557void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3558{
3559 Mutex::Autolock _l(mLock);
3560 mTracks.add(track);
3561}
3562
3563void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3564{
3565 Mutex::Autolock _l(mLock);
3566 destroyTrack_l(track);
3567}
3568
3569void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3570{
3571 ThreadBase::getAudioPortConfig(config);
3572 config->role = AUDIO_PORT_ROLE_SOURCE;
3573 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3574 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3575}
3576
Eric Laurent81784c32012-11-19 14:55:58 -08003577// ----------------------------------------------------------------------------
3578
3579AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003580 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3581 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003582 // mAudioMixer below
3583 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08003584 mFastMixerFutex(0),
3585 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08003586 // mOutputSink below
3587 // mPipeSink below
3588 // mNormalSink below
3589{
3590 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003591 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%zu, "
3592 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003593 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3594 mNormalFrameCount);
3595 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3596
Andy Hungfbfc3952015-01-15 13:33:51 -08003597 if (type == DUPLICATING) {
3598 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3599 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3600 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3601 return;
3602 }
Eric Laurent81784c32012-11-19 14:55:58 -08003603 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07003604 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08003605 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003606 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003607#if !LOG_NDEBUG
3608 ssize_t index =
3609#else
3610 (void)
3611#endif
3612 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003613 ALOG_ASSERT(index == 0);
3614
3615 // initialize fast mixer depending on configuration
3616 bool initFastMixer;
3617 switch (kUseFastMixer) {
3618 case FastMixer_Never:
3619 initFastMixer = false;
3620 break;
3621 case FastMixer_Always:
3622 initFastMixer = true;
3623 break;
3624 case FastMixer_Static:
3625 case FastMixer_Dynamic:
3626 initFastMixer = mFrameCount < mNormalFrameCount;
3627 break;
3628 }
3629 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003630 audio_format_t fastMixerFormat;
3631 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3632 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3633 } else {
3634 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3635 }
3636 if (mFormat != fastMixerFormat) {
3637 // change our Sink format to accept our intermediate precision
3638 mFormat = fastMixerFormat;
3639 free(mSinkBuffer);
3640 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3641 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3642 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3643 }
Eric Laurent81784c32012-11-19 14:55:58 -08003644
3645 // create a MonoPipe to connect our submix to FastMixer
3646 NBAIO_Format format = mOutputSink->format();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003647#ifdef TEE_SINK
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003648 NBAIO_Format origformat = format;
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003649#endif
Andy Hung1258c1a2014-05-23 21:22:17 -07003650 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07003651 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003652 format.mFormat = fastMixerFormat;
3653 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3654
Eric Laurent81784c32012-11-19 14:55:58 -08003655 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3656 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3657 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3658 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3659 const NBAIO_Format offers[1] = {format};
3660 size_t numCounterOffers = 0;
Glenn Kastenfc302fd2016-04-11 14:11:26 -07003661#if !LOG_NDEBUG || defined(TEE_SINK)
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003662 ssize_t index =
3663#else
3664 (void)
3665#endif
3666 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003667 ALOG_ASSERT(index == 0);
3668 monoPipe->setAvgFrames((mScreenState & 1) ?
3669 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3670 mPipeSink = monoPipe;
3671
Glenn Kasten46909e72013-02-26 09:20:22 -08003672#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003673 if (mTeeSinkOutputEnabled) {
3674 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003675 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3676 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003677 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003678 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003679 ALOG_ASSERT(index == 0);
3680 mTeeSink = teeSink;
3681 PipeReader *teeSource = new PipeReader(*teeSink);
3682 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003683 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003684 ALOG_ASSERT(index == 0);
3685 mTeeSource = teeSource;
3686 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003687#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003688
3689 // create fast mixer and configure it initially with just one fast track for our submix
3690 mFastMixer = new FastMixer();
3691 FastMixerStateQueue *sq = mFastMixer->sq();
3692#ifdef STATE_QUEUE_DUMP
3693 sq->setObserverDump(&mStateQueueObserverDump);
3694 sq->setMutatorDump(&mStateQueueMutatorDump);
3695#endif
3696 FastMixerState *state = sq->begin();
3697 FastTrack *fastTrack = &state->mFastTracks[0];
3698 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3699 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3700 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003701 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3702 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003703 fastTrack->mGeneration++;
3704 state->mFastTracksGen++;
3705 state->mTrackMask = 1;
3706 // fast mixer will use the HAL output sink
3707 state->mOutputSink = mOutputSink.get();
3708 state->mOutputSinkGen++;
3709 state->mFrameCount = mFrameCount;
3710 state->mCommand = FastMixerState::COLD_IDLE;
3711 // already done in constructor initialization list
3712 //mFastMixerFutex = 0;
3713 state->mColdFutexAddr = &mFastMixerFutex;
3714 state->mColdGen++;
3715 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003716#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003717 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003718#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003719 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3720 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003721 sq->end();
3722 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3723
3724 // start the fast mixer
3725 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3726 pid_t tid = mFastMixer->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003727 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003728
3729#ifdef AUDIO_WATCHDOG
3730 // create and start the watchdog
3731 mAudioWatchdog = new AudioWatchdog();
3732 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3733 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3734 tid = mAudioWatchdog->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003735 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003736#endif
3737
Eric Laurent81784c32012-11-19 14:55:58 -08003738 }
3739
3740 switch (kUseFastMixer) {
3741 case FastMixer_Never:
3742 case FastMixer_Dynamic:
3743 mNormalSink = mOutputSink;
3744 break;
3745 case FastMixer_Always:
3746 mNormalSink = mPipeSink;
3747 break;
3748 case FastMixer_Static:
3749 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3750 break;
3751 }
3752}
3753
3754AudioFlinger::MixerThread::~MixerThread()
3755{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003756 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003757 FastMixerStateQueue *sq = mFastMixer->sq();
3758 FastMixerState *state = sq->begin();
3759 if (state->mCommand == FastMixerState::COLD_IDLE) {
3760 int32_t old = android_atomic_inc(&mFastMixerFutex);
3761 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003762 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003763 }
3764 }
3765 state->mCommand = FastMixerState::EXIT;
3766 sq->end();
3767 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3768 mFastMixer->join();
3769 // Though the fast mixer thread has exited, it's state queue is still valid.
3770 // We'll use that extract the final state which contains one remaining fast track
3771 // corresponding to our sub-mix.
3772 state = sq->begin();
3773 ALOG_ASSERT(state->mTrackMask == 1);
3774 FastTrack *fastTrack = &state->mFastTracks[0];
3775 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3776 delete fastTrack->mBufferProvider;
3777 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003778 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003779#ifdef AUDIO_WATCHDOG
3780 if (mAudioWatchdog != 0) {
3781 mAudioWatchdog->requestExit();
3782 mAudioWatchdog->requestExitAndWait();
3783 mAudioWatchdog.clear();
3784 }
3785#endif
3786 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003787 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003788 delete mAudioMixer;
3789}
3790
3791
3792uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3793{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003794 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003795 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3796 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3797 }
3798 return latency;
3799}
3800
3801
3802void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3803{
3804 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3805}
3806
Eric Laurentbfb1b832013-01-07 09:53:42 -08003807ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003808{
3809 // FIXME we should only do one push per cycle; confirm this is true
3810 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003811 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003812 FastMixerStateQueue *sq = mFastMixer->sq();
3813 FastMixerState *state = sq->begin();
3814 if (state->mCommand != FastMixerState::MIX_WRITE &&
3815 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3816 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07003817
3818 // FIXME workaround for first HAL write being CPU bound on some devices
3819 ATRACE_BEGIN("write");
3820 mOutput->write((char *)mSinkBuffer, 0);
3821 ATRACE_END();
3822
Eric Laurent81784c32012-11-19 14:55:58 -08003823 int32_t old = android_atomic_inc(&mFastMixerFutex);
3824 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003825 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003826 }
3827#ifdef AUDIO_WATCHDOG
3828 if (mAudioWatchdog != 0) {
3829 mAudioWatchdog->resume();
3830 }
3831#endif
3832 }
3833 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003834#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003835 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003836 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003837#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003838 sq->end();
3839 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3840 if (kUseFastMixer == FastMixer_Dynamic) {
3841 mNormalSink = mPipeSink;
3842 }
3843 } else {
3844 sq->end(false /*didModify*/);
3845 }
3846 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003847 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003848}
3849
3850void AudioFlinger::MixerThread::threadLoop_standby()
3851{
3852 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003853 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003854 FastMixerStateQueue *sq = mFastMixer->sq();
3855 FastMixerState *state = sq->begin();
3856 if (!(state->mCommand & FastMixerState::IDLE)) {
3857 state->mCommand = FastMixerState::COLD_IDLE;
3858 state->mColdFutexAddr = &mFastMixerFutex;
3859 state->mColdGen++;
3860 mFastMixerFutex = 0;
3861 sq->end();
3862 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3863 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3864 if (kUseFastMixer == FastMixer_Dynamic) {
3865 mNormalSink = mOutputSink;
3866 }
3867#ifdef AUDIO_WATCHDOG
3868 if (mAudioWatchdog != 0) {
3869 mAudioWatchdog->pause();
3870 }
3871#endif
3872 } else {
3873 sq->end(false /*didModify*/);
3874 }
3875 }
3876 PlaybackThread::threadLoop_standby();
3877}
3878
Eric Laurentbfb1b832013-01-07 09:53:42 -08003879bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3880{
3881 return false;
3882}
3883
3884bool AudioFlinger::PlaybackThread::shouldStandby_l()
3885{
3886 return !mStandby;
3887}
3888
3889bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3890{
3891 Mutex::Autolock _l(mLock);
3892 return waitingAsyncCallback_l();
3893}
3894
Eric Laurent81784c32012-11-19 14:55:58 -08003895// shared by MIXER and DIRECT, overridden by DUPLICATING
3896void AudioFlinger::PlaybackThread::threadLoop_standby()
3897{
3898 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08003899 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003900 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003901 // discard any pending drain or write ack by incrementing sequence
3902 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3903 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003904 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003905 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3906 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003907 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003908 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003909}
3910
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003911void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3912{
3913 ALOGV("signal playback thread");
3914 broadcast_l();
3915}
3916
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003917void AudioFlinger::PlaybackThread::onAsyncError()
3918{
3919 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
3920 invalidateTracks((audio_stream_type_t)i);
3921 }
3922}
3923
Eric Laurent81784c32012-11-19 14:55:58 -08003924void AudioFlinger::MixerThread::threadLoop_mix()
3925{
Eric Laurent81784c32012-11-19 14:55:58 -08003926 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08003927 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08003928 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003929 // increase sleep time progressively when application underrun condition clears.
3930 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3931 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3932 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003933 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003934 sleepTimeShift--;
3935 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003936 mSleepTimeUs = 0;
3937 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08003938 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003939
Eric Laurent81784c32012-11-19 14:55:58 -08003940}
3941
3942void AudioFlinger::MixerThread::threadLoop_sleepTime()
3943{
3944 // If no tracks are ready, sleep once for the duration of an output
3945 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003946 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003947 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003948 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
3949 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
3950 mSleepTimeUs = kMinThreadSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003951 }
3952 // reduce sleep time in case of consecutive application underruns to avoid
3953 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3954 // duration we would end up writing less data than needed by the audio HAL if
3955 // the condition persists.
3956 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3957 sleepTimeShift++;
3958 }
3959 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003960 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003961 }
3962 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003963 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3964 // before effects processing or output.
3965 if (mMixerBufferValid) {
3966 memset(mMixerBuffer, 0, mMixerBufferSize);
3967 } else {
3968 memset(mSinkBuffer, 0, mSinkBufferSize);
3969 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003970 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003971 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3972 "anticipated start");
3973 }
3974 // TODO add standby time extension fct of effect tail
3975}
3976
3977// prepareTracks_l() must be called with ThreadBase::mLock held
3978AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3979 Vector< sp<Track> > *tracksToRemove)
3980{
3981
3982 mixer_state mixerStatus = MIXER_IDLE;
3983 // find out which tracks need to be processed
3984 size_t count = mActiveTracks.size();
3985 size_t mixedTracks = 0;
3986 size_t tracksWithEffect = 0;
3987 // counts only _active_ fast tracks
3988 size_t fastTracks = 0;
3989 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3990
3991 float masterVolume = mMasterVolume;
3992 bool masterMute = mMasterMute;
3993
3994 if (masterMute) {
3995 masterVolume = 0;
3996 }
3997 // Delegate master volume control to effect in output mix effect chain if needed
3998 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3999 if (chain != 0) {
4000 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
4001 chain->setVolume_l(&v, &v);
4002 masterVolume = (float)((v + (1 << 23)) >> 24);
4003 chain.clear();
4004 }
4005
4006 // prepare a new state to push
4007 FastMixerStateQueue *sq = NULL;
4008 FastMixerState *state = NULL;
4009 bool didModify = false;
4010 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004011 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004012 sq = mFastMixer->sq();
4013 state = sq->begin();
4014 }
4015
Andy Hung69aed5f2014-02-25 17:24:40 -08004016 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08004017 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08004018
Eric Laurent81784c32012-11-19 14:55:58 -08004019 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07004020 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08004021 if (t == 0) {
4022 continue;
4023 }
4024
4025 // this const just means the local variable doesn't change
4026 Track* const track = t.get();
4027
4028 // process fast tracks
4029 if (track->isFastTrack()) {
4030
4031 // It's theoretically possible (though unlikely) for a fast track to be created
4032 // and then removed within the same normal mix cycle. This is not a problem, as
4033 // the track never becomes active so it's fast mixer slot is never touched.
4034 // The converse, of removing an (active) track and then creating a new track
4035 // at the identical fast mixer slot within the same normal mix cycle,
4036 // is impossible because the slot isn't marked available until the end of each cycle.
4037 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07004038 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08004039 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
4040 FastTrack *fastTrack = &state->mFastTracks[j];
4041
4042 // Determine whether the track is currently in underrun condition,
4043 // and whether it had a recent underrun.
4044 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
4045 FastTrackUnderruns underruns = ftDump->mUnderruns;
4046 uint32_t recentFull = (underruns.mBitFields.mFull -
4047 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
4048 uint32_t recentPartial = (underruns.mBitFields.mPartial -
4049 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
4050 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
4051 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
4052 uint32_t recentUnderruns = recentPartial + recentEmpty;
4053 track->mObservedUnderruns = underruns;
4054 // don't count underruns that occur while stopping or pausing
4055 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07004056 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
4057 recentUnderruns > 0) {
4058 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
4059 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Phil Burk2812d9e2016-01-04 10:34:30 -08004060 } else {
4061 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Eric Laurent81784c32012-11-19 14:55:58 -08004062 }
4063
4064 // This is similar to the state machine for normal tracks,
4065 // with a few modifications for fast tracks.
4066 bool isActive = true;
4067 switch (track->mState) {
4068 case TrackBase::STOPPING_1:
4069 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08004070 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004071 track->mState = TrackBase::STOPPING_2;
4072 }
4073 break;
4074 case TrackBase::PAUSING:
4075 // ramp down is not yet implemented
4076 track->setPaused();
4077 break;
4078 case TrackBase::RESUMING:
4079 // ramp up is not yet implemented
4080 track->mState = TrackBase::ACTIVE;
4081 break;
4082 case TrackBase::ACTIVE:
4083 if (recentFull > 0 || recentPartial > 0) {
4084 // track has provided at least some frames recently: reset retry count
4085 track->mRetryCount = kMaxTrackRetries;
4086 }
4087 if (recentUnderruns == 0) {
4088 // no recent underruns: stay active
4089 break;
4090 }
4091 // there has recently been an underrun of some kind
4092 if (track->sharedBuffer() == 0) {
4093 // were any of the recent underruns "empty" (no frames available)?
4094 if (recentEmpty == 0) {
4095 // no, then ignore the partial underruns as they are allowed indefinitely
4096 break;
4097 }
4098 // there has recently been an "empty" underrun: decrement the retry counter
4099 if (--(track->mRetryCount) > 0) {
4100 break;
4101 }
4102 // indicate to client process that the track was disabled because of underrun;
4103 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004104 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004105 // remove from active list, but state remains ACTIVE [confusing but true]
4106 isActive = false;
4107 break;
4108 }
4109 // fall through
4110 case TrackBase::STOPPING_2:
4111 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08004112 case TrackBase::STOPPED:
4113 case TrackBase::FLUSHED: // flush() while active
4114 // Check for presentation complete if track is inactive
4115 // We have consumed all the buffers of this track.
4116 // This would be incomplete if we auto-paused on underrun
4117 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004118 uint32_t latency = 0;
4119 status_t result = mOutput->stream->getLatency(&latency);
4120 ALOGE_IF(result != OK,
4121 "Error when retrieving output stream latency: %d", result);
4122 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004123 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004124 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
4125 // track stays in active list until presentation is complete
4126 break;
4127 }
4128 }
4129 if (track->isStopping_2()) {
4130 track->mState = TrackBase::STOPPED;
4131 }
4132 if (track->isStopped()) {
4133 // Can't reset directly, as fast mixer is still polling this track
4134 // track->reset();
4135 // So instead mark this track as needing to be reset after push with ack
4136 resetMask |= 1 << i;
4137 }
4138 isActive = false;
4139 break;
4140 case TrackBase::IDLE:
4141 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08004142 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08004143 }
4144
4145 if (isActive) {
4146 // was it previously inactive?
4147 if (!(state->mTrackMask & (1 << j))) {
4148 ExtendedAudioBufferProvider *eabp = track;
4149 VolumeProvider *vp = track;
4150 fastTrack->mBufferProvider = eabp;
4151 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08004152 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07004153 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08004154 fastTrack->mGeneration++;
4155 state->mTrackMask |= 1 << j;
4156 didModify = true;
4157 // no acknowledgement required for newly active tracks
4158 }
4159 // cache the combined master volume and stream type volume for fast mixer; this
4160 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08004161 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08004162 ++fastTracks;
4163 } else {
4164 // was it previously active?
4165 if (state->mTrackMask & (1 << j)) {
4166 fastTrack->mBufferProvider = NULL;
4167 fastTrack->mGeneration++;
4168 state->mTrackMask &= ~(1 << j);
4169 didModify = true;
4170 // If any fast tracks were removed, we must wait for acknowledgement
4171 // because we're about to decrement the last sp<> on those tracks.
4172 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4173 } else {
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08004174 LOG_ALWAYS_FATAL("fast track %d should have been active; "
4175 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
4176 j, track->mState, state->mTrackMask, recentUnderruns,
4177 track->sharedBuffer() != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004178 }
4179 tracksToRemove->add(track);
4180 // Avoids a misleading display in dumpsys
4181 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
4182 }
4183 continue;
4184 }
4185
4186 { // local variable scope to avoid goto warning
4187
4188 audio_track_cblk_t* cblk = track->cblk();
4189
4190 // The first time a track is added we wait
4191 // for all its buffers to be filled before processing it
4192 int name = track->name();
4193 // make sure that we have enough frames to mix one full buffer.
4194 // enforce this condition only once to enable draining the buffer in case the client
4195 // app does not call stop() and relies on underrun to stop:
4196 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
4197 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004198 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07004199 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004200 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004201
4202 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004203 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004204 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
4205 // add frames already consumed but not yet released by the resampler
4206 // because mAudioTrackServerProxy->framesReady() will include these frames
4207 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
4208
Eric Laurent81784c32012-11-19 14:55:58 -08004209 uint32_t minFrames = 1;
4210 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
4211 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004212 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08004213 }
Eric Laurent13e4c962013-12-20 17:36:01 -08004214
4215 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07004216 if (ATRACE_ENABLED()) {
4217 // I wish we had formatted trace names
4218 char traceName[16];
4219 strcpy(traceName, "nRdy");
4220 int name = track->name();
4221 if (AudioMixer::TRACK0 <= name &&
4222 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
4223 name -= AudioMixer::TRACK0;
4224 traceName[4] = (name / 10) + '0';
4225 traceName[5] = (name % 10) + '0';
4226 } else {
4227 traceName[4] = '?';
4228 traceName[5] = '?';
4229 }
4230 traceName[6] = '\0';
4231 ATRACE_INT(traceName, framesReady);
4232 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004233 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08004234 !track->isPaused() && !track->isTerminated())
4235 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004236 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004237
4238 mixedTracks++;
4239
Andy Hung69aed5f2014-02-25 17:24:40 -08004240 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
4241 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08004242 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08004243 if (track->mainBuffer() != mSinkBuffer &&
4244 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004245 if (mEffectBufferEnabled) {
4246 mEffectBufferValid = true; // Later can set directly.
4247 }
Eric Laurent81784c32012-11-19 14:55:58 -08004248 chain = getEffectChain_l(track->sessionId());
4249 // Delegate volume control to effect in track effect chain if needed
4250 if (chain != 0) {
4251 tracksWithEffect++;
4252 } else {
4253 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
4254 "session %d",
4255 name, track->sessionId());
4256 }
4257 }
4258
4259
4260 int param = AudioMixer::VOLUME;
4261 if (track->mFillingUpStatus == Track::FS_FILLED) {
4262 // no ramp for the first volume setting
4263 track->mFillingUpStatus = Track::FS_ACTIVE;
4264 if (track->mState == TrackBase::RESUMING) {
4265 track->mState = TrackBase::ACTIVE;
4266 param = AudioMixer::RAMP_VOLUME;
4267 }
4268 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004269 // FIXME should not make a decision based on mServer
4270 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004271 // If the track is stopped before the first frame was mixed,
4272 // do not apply ramp
4273 param = AudioMixer::RAMP_VOLUME;
4274 }
4275
4276 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07004277 uint32_t vl, vr; // in U8.24 integer format
4278 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08004279 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07004280 vl = vr = 0;
4281 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08004282 if (track->isPausing()) {
4283 track->setPaused();
4284 }
4285 } else {
4286
4287 // read original volumes with volume control
4288 float typeVolume = mStreamTypes[track->streamType()].volume;
4289 float v = masterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07004290 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004291 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07004292 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
4293 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08004294 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07004295 if (vlf > GAIN_FLOAT_UNITY) {
4296 ALOGV("Track left volume out of range: %.3g", vlf);
4297 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004298 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07004299 if (vrf > GAIN_FLOAT_UNITY) {
4300 ALOGV("Track right volume out of range: %.3g", vrf);
4301 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004302 }
4303 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07004304 vlf *= v;
4305 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08004306 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07004307 // then derive vl and vr as U8.24 versions for the effect chain
4308 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
4309 vl = (uint32_t) (scaleto8_24 * vlf);
4310 vr = (uint32_t) (scaleto8_24 * vrf);
4311 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08004312 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08004313 // send level comes from shared memory and so may be corrupt
4314 if (sendLevel > MAX_GAIN_INT) {
4315 ALOGV("Track send level out of range: %04X", sendLevel);
4316 sendLevel = MAX_GAIN_INT;
4317 }
Andy Hung6be49402014-05-30 10:42:03 -07004318 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4319 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08004320 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004321
Eric Laurent81784c32012-11-19 14:55:58 -08004322 // Delegate volume control to effect in track effect chain if needed
4323 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4324 // Do not ramp volume if volume is controlled by effect
4325 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08004326 // Update remaining floating point volume levels
4327 vlf = (float)vl / (1 << 24);
4328 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004329 track->mHasVolumeController = true;
4330 } else {
4331 // force no volume ramp when volume controller was just disabled or removed
4332 // from effect chain to avoid volume spike
4333 if (track->mHasVolumeController) {
4334 param = AudioMixer::VOLUME;
4335 }
4336 track->mHasVolumeController = false;
4337 }
4338
Eric Laurent81784c32012-11-19 14:55:58 -08004339 // XXX: these things DON'T need to be done each time
4340 mAudioMixer->setBufferProvider(name, track);
4341 mAudioMixer->enable(name);
4342
Andy Hung6be49402014-05-30 10:42:03 -07004343 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
4344 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
4345 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004346 mAudioMixer->setParameter(
4347 name,
4348 AudioMixer::TRACK,
4349 AudioMixer::FORMAT, (void *)track->format());
4350 mAudioMixer->setParameter(
4351 name,
4352 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004353 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004354 mAudioMixer->setParameter(
4355 name,
4356 AudioMixer::TRACK,
4357 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004358 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004359 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004360 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004361 if (reqSampleRate == 0) {
4362 reqSampleRate = mSampleRate;
4363 } else if (reqSampleRate > maxSampleRate) {
4364 reqSampleRate = maxSampleRate;
4365 }
Eric Laurent81784c32012-11-19 14:55:58 -08004366 mAudioMixer->setParameter(
4367 name,
4368 AudioMixer::RESAMPLE,
4369 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004370 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004371
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004372 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004373 mAudioMixer->setParameter(
4374 name,
4375 AudioMixer::TIMESTRETCH,
4376 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004377 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004378
Andy Hung69aed5f2014-02-25 17:24:40 -08004379 /*
4380 * Select the appropriate output buffer for the track.
4381 *
Andy Hung98ef9782014-03-04 14:46:50 -08004382 * Tracks with effects go into their own effects chain buffer
4383 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004384 *
4385 * Other tracks can use mMixerBuffer for higher precision
4386 * channel accumulation. If this buffer is enabled
4387 * (mMixerBufferEnabled true), then selected tracks will accumulate
4388 * into it.
4389 *
4390 */
4391 if (mMixerBufferEnabled
4392 && (track->mainBuffer() == mSinkBuffer
4393 || track->mainBuffer() == mMixerBuffer)) {
4394 mAudioMixer->setParameter(
4395 name,
4396 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004397 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004398 mAudioMixer->setParameter(
4399 name,
4400 AudioMixer::TRACK,
4401 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4402 // TODO: override track->mainBuffer()?
4403 mMixerBufferValid = true;
4404 } else {
4405 mAudioMixer->setParameter(
4406 name,
4407 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004408 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004409 mAudioMixer->setParameter(
4410 name,
4411 AudioMixer::TRACK,
4412 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4413 }
Eric Laurent81784c32012-11-19 14:55:58 -08004414 mAudioMixer->setParameter(
4415 name,
4416 AudioMixer::TRACK,
4417 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4418
4419 // reset retry count
4420 track->mRetryCount = kMaxTrackRetries;
4421
4422 // If one track is ready, set the mixer ready if:
4423 // - the mixer was not ready during previous round OR
4424 // - no other track is not ready
4425 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4426 mixerStatus != MIXER_TRACKS_ENABLED) {
4427 mixerStatus = MIXER_TRACKS_READY;
4428 }
4429 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004430 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hung08fb1742015-05-31 23:22:10 -07004431 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)",
4432 track, framesReady, desiredFrames);
Glenn Kasten82aaf942013-07-17 16:05:07 -07004433 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08004434 } else {
4435 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004436 }
Phil Burk2812d9e2016-01-04 10:34:30 -08004437
Eric Laurent81784c32012-11-19 14:55:58 -08004438 // clear effect chain input buffer if an active track underruns to avoid sending
4439 // previous audio buffer again to effects
4440 chain = getEffectChain_l(track->sessionId());
4441 if (chain != 0) {
4442 chain->clearInputBuffer();
4443 }
4444
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004445 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004446 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4447 track->isStopped() || track->isPaused()) {
4448 // We have consumed all the buffers of this track.
4449 // Remove it from the list of active tracks.
4450 // TODO: use actual buffer filling status instead of latency when available from
4451 // audio HAL
4452 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004453 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004454 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4455 if (track->isStopped()) {
4456 track->reset();
4457 }
4458 tracksToRemove->add(track);
4459 }
4460 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004461 // No buffers for this track. Give it a few chances to
4462 // fill a buffer, then remove it from active list.
4463 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004464 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004465 tracksToRemove->add(track);
4466 // indicate to client process that the track was disabled because of underrun;
4467 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004468 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004469 // If one track is not ready, mark the mixer also not ready if:
4470 // - the mixer was ready during previous round OR
4471 // - no other track is ready
4472 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4473 mixerStatus != MIXER_TRACKS_READY) {
4474 mixerStatus = MIXER_TRACKS_ENABLED;
4475 }
4476 }
4477 mAudioMixer->disable(name);
4478 }
4479
4480 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08004481
4482 }
4483
4484 // Push the new FastMixer state if necessary
4485 bool pauseAudioWatchdog = false;
4486 if (didModify) {
4487 state->mFastTracksGen++;
4488 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4489 if (kUseFastMixer == FastMixer_Dynamic &&
4490 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4491 state->mCommand = FastMixerState::COLD_IDLE;
4492 state->mColdFutexAddr = &mFastMixerFutex;
4493 state->mColdGen++;
4494 mFastMixerFutex = 0;
4495 if (kUseFastMixer == FastMixer_Dynamic) {
4496 mNormalSink = mOutputSink;
4497 }
4498 // If we go into cold idle, need to wait for acknowledgement
4499 // so that fast mixer stops doing I/O.
4500 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4501 pauseAudioWatchdog = true;
4502 }
Eric Laurent81784c32012-11-19 14:55:58 -08004503 }
4504 if (sq != NULL) {
4505 sq->end(didModify);
4506 sq->push(block);
4507 }
4508#ifdef AUDIO_WATCHDOG
4509 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4510 mAudioWatchdog->pause();
4511 }
4512#endif
4513
4514 // Now perform the deferred reset on fast tracks that have stopped
4515 while (resetMask != 0) {
4516 size_t i = __builtin_ctz(resetMask);
4517 ALOG_ASSERT(i < count);
4518 resetMask &= ~(1 << i);
4519 sp<Track> t = mActiveTracks[i].promote();
4520 if (t == 0) {
4521 continue;
4522 }
4523 Track* track = t.get();
4524 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4525 track->reset();
4526 }
4527
4528 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004529 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004530
Eric Laurent97d547d2014-09-02 14:45:53 -07004531 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4532 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004533 }
4534
4535 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004536 // as long as there are effects we should clear the effects buffer, to avoid
4537 // passing a non-clean buffer to the effect chain
4538 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004539 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004540 // sink or mix buffer must be cleared if all tracks are connected to an
4541 // effect chain as in this case the mixer will not write to the sink or mix buffer
4542 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004543 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4544 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004545 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004546 if (mMixerBufferValid) {
4547 memset(mMixerBuffer, 0, mMixerBufferSize);
4548 // TODO: In testing, mSinkBuffer below need not be cleared because
4549 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4550 // after mixing.
4551 //
4552 // To enforce this guarantee:
4553 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4554 // (mixedTracks == 0 && fastTracks > 0))
4555 // must imply MIXER_TRACKS_READY.
4556 // Later, we may clear buffers regardless, and skip much of this logic.
4557 }
Andy Hung98ef9782014-03-04 14:46:50 -08004558 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004559 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004560 }
4561
4562 // if any fast tracks, then status is ready
4563 mMixerStatusIgnoringFastTracks = mixerStatus;
4564 if (fastTracks > 0) {
4565 mixerStatus = MIXER_TRACKS_READY;
4566 }
4567 return mixerStatus;
4568}
4569
Eric Laurentad7dd962016-09-22 12:38:37 -07004570// trackCountForUid_l() must be called with ThreadBase::mLock held
4571uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid)
4572{
4573 uint32_t trackCount = 0;
4574 for (size_t i = 0; i < mTracks.size() ; i++) {
4575 if (mTracks[i]->uid() == (int)uid) {
4576 trackCount++;
4577 }
4578 }
4579 return trackCount;
4580}
4581
Eric Laurent81784c32012-11-19 14:55:58 -08004582// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07004583int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
Eric Laurentad7dd962016-09-22 12:38:37 -07004584 audio_format_t format, audio_session_t sessionId, uid_t uid)
Eric Laurent81784c32012-11-19 14:55:58 -08004585{
Eric Laurentad7dd962016-09-22 12:38:37 -07004586 if (trackCountForUid_l(uid) > (PlaybackThread::kMaxTracksPerUid - 1)) {
4587 return -1;
4588 }
Andy Hunge8a1ced2014-05-09 15:02:21 -07004589 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08004590}
4591
4592// deleteTrackName_l() must be called with ThreadBase::mLock held
4593void AudioFlinger::MixerThread::deleteTrackName_l(int name)
4594{
4595 ALOGV("remove track (%d) and delete from mixer", name);
4596 mAudioMixer->deleteTrackName(name);
4597}
4598
Eric Laurent10351942014-05-08 18:49:52 -07004599// checkForNewParameter_l() must be called with ThreadBase::mLock held
4600bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4601 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004602{
Eric Laurent81784c32012-11-19 14:55:58 -08004603 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08004604 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004605
Eric Laurent10351942014-05-08 18:49:52 -07004606 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004607
Glenn Kastenc05b8d72016-03-24 09:48:17 -07004608 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004609
Eric Laurent10351942014-05-08 18:49:52 -07004610 AudioParameter param = AudioParameter(keyValuePair);
4611 int value;
4612 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4613 reconfig = true;
4614 }
4615 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004616 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004617 status = BAD_VALUE;
4618 } else {
4619 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004620 reconfig = true;
4621 }
Eric Laurent10351942014-05-08 18:49:52 -07004622 }
4623 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004624 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004625 status = BAD_VALUE;
4626 } else {
4627 // no need to save value, since it's constant
4628 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004629 }
Eric Laurent10351942014-05-08 18:49:52 -07004630 }
4631 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4632 // do not accept frame count changes if tracks are open as the track buffer
4633 // size depends on frame count and correct behavior would not be guaranteed
4634 // if frame count is changed after track creation
4635 if (!mTracks.isEmpty()) {
4636 status = INVALID_OPERATION;
4637 } else {
4638 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004639 }
Eric Laurent10351942014-05-08 18:49:52 -07004640 }
4641 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004642#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004643 // when changing the audio output device, call addBatteryData to notify
4644 // the change
4645 if (mOutDevice != value) {
4646 uint32_t params = 0;
4647 // check whether speaker is on
4648 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4649 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004650 }
Eric Laurent10351942014-05-08 18:49:52 -07004651
4652 audio_devices_t deviceWithoutSpeaker
4653 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4654 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07004655 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07004656 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4657 }
4658
4659 if (params != 0) {
4660 addBatteryData(params);
4661 }
4662 }
Eric Laurent81784c32012-11-19 14:55:58 -08004663#endif
4664
Eric Laurent10351942014-05-08 18:49:52 -07004665 // forward device change to effects that have requested to be
4666 // aware of attached audio device.
4667 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08004668 a2dpDeviceChanged =
4669 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07004670 mOutDevice = value;
4671 for (size_t i = 0; i < mEffectChains.size(); i++) {
4672 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004673 }
4674 }
Eric Laurent10351942014-05-08 18:49:52 -07004675 }
Eric Laurent81784c32012-11-19 14:55:58 -08004676
Eric Laurent10351942014-05-08 18:49:52 -07004677 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004678 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07004679 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004680 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004681 mStandby = true;
4682 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004683 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08004684 }
Eric Laurent10351942014-05-08 18:49:52 -07004685 if (status == NO_ERROR && reconfig) {
4686 readOutputParameters_l();
4687 delete mAudioMixer;
4688 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4689 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004690 int name = getTrackName_l(mTracks[i]->mChannelMask,
Eric Laurentad7dd962016-09-22 12:38:37 -07004691 mTracks[i]->mFormat, mTracks[i]->mSessionId, mTracks[i]->uid());
Eric Laurent10351942014-05-08 18:49:52 -07004692 if (name < 0) {
4693 break;
4694 }
4695 mTracks[i]->mName = name;
4696 }
Eric Laurent73e26b62015-04-27 16:55:58 -07004697 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004698 }
Eric Laurent81784c32012-11-19 14:55:58 -08004699 }
4700
Eric Laurent42537be2016-01-08 17:16:42 -08004701 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08004702}
4703
4704
4705void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4706{
Eric Laurent81784c32012-11-19 14:55:58 -08004707 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07004708 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Elliott Hughes87cebad2014-05-22 10:14:43 -07004709 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Andy Hung2ddee192015-12-18 17:34:44 -08004710 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent81784c32012-11-19 14:55:58 -08004711
4712 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten2f90c512015-12-02 11:40:09 -08004713 // while we are dumping it. It may be inconsistent, but it won't mutate!
4714 // This is a large object so we place it on the heap.
4715 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
4716 const FastMixerDumpState *copy = new FastMixerDumpState(mFastMixerDumpState);
4717 copy->dump(fd);
4718 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08004719
4720#ifdef STATE_QUEUE_DUMP
4721 // Similar for state queue
4722 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4723 observerCopy.dump(fd);
4724 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4725 mutatorCopy.dump(fd);
4726#endif
4727
Glenn Kasten46909e72013-02-26 09:20:22 -08004728#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004729 // Write the tee output to a .wav file
4730 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08004731#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004732
4733#ifdef AUDIO_WATCHDOG
4734 if (mAudioWatchdog != 0) {
4735 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4736 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4737 wdCopy.dump(fd);
4738 }
4739#endif
4740}
4741
4742uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4743{
4744 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4745}
4746
4747uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4748{
4749 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4750}
4751
4752void AudioFlinger::MixerThread::cacheParameters_l()
4753{
4754 PlaybackThread::cacheParameters_l();
4755
4756 // FIXME: Relaxed timing because of a certain device that can't meet latency
4757 // Should be reduced to 2x after the vendor fixes the driver issue
4758 // increase threshold again due to low power audio mode. The way this warning
4759 // threshold is calculated and its usefulness should be reconsidered anyway.
4760 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4761}
4762
4763// ----------------------------------------------------------------------------
4764
4765AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07004766 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady)
4767 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08004768 // mLeftVolFloat, mRightVolFloat
4769{
4770}
4771
Eric Laurentbfb1b832013-01-07 09:53:42 -08004772AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4773 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurente93cc032016-05-05 10:15:10 -07004774 ThreadBase::type_t type, bool systemReady)
4775 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004776 // mLeftVolFloat, mRightVolFloat
4777{
4778}
4779
Eric Laurent81784c32012-11-19 14:55:58 -08004780AudioFlinger::DirectOutputThread::~DirectOutputThread()
4781{
4782}
4783
Eric Laurentbfb1b832013-01-07 09:53:42 -08004784void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
4785{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004786 float left, right;
4787
4788 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4789 left = right = 0;
4790 } else {
4791 float typeVolume = mStreamTypes[track->streamType()].volume;
4792 float v = mMasterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07004793 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004794 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4795 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4796 if (left > GAIN_FLOAT_UNITY) {
4797 left = GAIN_FLOAT_UNITY;
4798 }
4799 left *= v;
4800 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4801 if (right > GAIN_FLOAT_UNITY) {
4802 right = GAIN_FLOAT_UNITY;
4803 }
4804 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004805 }
4806
4807 if (lastTrack) {
4808 if (left != mLeftVolFloat || right != mRightVolFloat) {
4809 mLeftVolFloat = left;
4810 mRightVolFloat = right;
4811
4812 // Convert volumes from float to 8.24
4813 uint32_t vl = (uint32_t)(left * (1 << 24));
4814 uint32_t vr = (uint32_t)(right * (1 << 24));
4815
4816 // Delegate volume control to effect in track effect chain if needed
4817 // only one effect chain can be present on DirectOutputThread, so if
4818 // there is one, the track is connected to it
4819 if (!mEffectChains.isEmpty()) {
4820 mEffectChains[0]->setVolume_l(&vl, &vr);
4821 left = (float)vl / (1 << 24);
4822 right = (float)vr / (1 << 24);
4823 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004824 status_t result = mOutput->stream->setVolume(left, right);
4825 ALOGE_IF(result != OK, "Error when setting output stream volume: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004826 }
4827 }
4828}
4829
Phil Burk43b4dcc2015-06-09 16:53:44 -07004830void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
4831{
4832 sp<Track> previousTrack = mPreviousTrack.promote();
4833 sp<Track> latestTrack = mLatestActiveTrack.promote();
4834
Eric Laurent0f0631e2015-07-06 18:01:25 -07004835 if (previousTrack != 0 && latestTrack != 0) {
4836 if (mType == DIRECT) {
4837 if (previousTrack.get() != latestTrack.get()) {
4838 mFlushPending = true;
4839 }
4840 } else /* mType == OFFLOAD */ {
4841 if (previousTrack->sessionId() != latestTrack->sessionId()) {
4842 mFlushPending = true;
4843 }
4844 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004845 }
4846 PlaybackThread::onAddNewTrack_l();
4847}
Eric Laurentbfb1b832013-01-07 09:53:42 -08004848
Eric Laurent81784c32012-11-19 14:55:58 -08004849AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4850 Vector< sp<Track> > *tracksToRemove
4851)
4852{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004853 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004854 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004855 bool doHwPause = false;
4856 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004857
4858 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07004859 for (size_t i = 0; i < count; i++) {
4860 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08004861 // The track died recently
4862 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004863 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08004864 }
4865
Phil Burk43b4dcc2015-06-09 16:53:44 -07004866 if (t->isInvalid()) {
4867 ALOGW("An invalidated track shouldn't be in active list");
4868 tracksToRemove->add(t);
4869 continue;
4870 }
4871
Eric Laurent81784c32012-11-19 14:55:58 -08004872 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004873#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08004874 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004875#endif
Eric Laurentfd477972013-10-25 18:10:40 -07004876 // Only consider last track started for volume and mixer state control.
4877 // In theory an older track could underrun and restart after the new one starts
4878 // but as we only care about the transition phase between two tracks on a
4879 // direct output, it is not a problem to ignore the underrun case.
4880 sp<Track> l = mLatestActiveTrack.promote();
4881 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004882
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004883 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004884 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004885 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004886 doHwPause = true;
4887 mHwPaused = true;
4888 }
4889 tracksToRemove->add(track);
4890 } else if (track->isFlushPending()) {
4891 track->flushAck();
4892 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004893 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004894 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004895 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004896 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07004897 if (last) {
4898 mLeftVolFloat = mRightVolFloat = -1.0;
4899 if (mHwPaused) {
4900 doHwResume = true;
4901 mHwPaused = false;
4902 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004903 }
4904 }
4905
Eric Laurent81784c32012-11-19 14:55:58 -08004906 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004907 // for all its buffers to be filled before processing it.
4908 // Allow draining the buffer in case the client
4909 // app does not call stop() and relies on underrun to stop:
4910 // hence the test on (track->mRetryCount > 1).
4911 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07004912 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08004913 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004914 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08004915 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004916 minFrames = mNormalFrameCount;
4917 } else {
4918 minFrames = 1;
4919 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004920
Eric Laurentab5cdba2014-06-09 17:22:27 -07004921 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4922 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004923 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004924 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004925
4926 if (track->mFillingUpStatus == Track::FS_FILLED) {
4927 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07004928 if (last) {
4929 // make sure processVolume_l() will apply new volume even if 0
4930 mLeftVolFloat = mRightVolFloat = -1.0;
4931 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004932 if (!mHwSupportsPause) {
4933 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004934 }
4935 }
4936
4937 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004938 processVolume_l(track, last);
4939 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004940 sp<Track> previousTrack = mPreviousTrack.promote();
4941 if (previousTrack != 0) {
4942 if (track != previousTrack.get()) {
4943 // Flush any data still being written from last track
4944 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07004945 // Invalidate previous track to force a seek when resuming.
4946 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004947 }
4948 }
4949 mPreviousTrack = track;
4950
Eric Laurentd595b7c2013-04-03 17:27:56 -07004951 // reset retry count
4952 track->mRetryCount = kMaxTrackRetriesDirect;
4953 mActiveTrack = t;
4954 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07004955 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004956 doHwResume = true;
4957 mHwPaused = false;
4958 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004959 }
Eric Laurent81784c32012-11-19 14:55:58 -08004960 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004961 // clear effect chain input buffer if the last active track started underruns
4962 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004963 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004964 mEffectChains[0]->clearInputBuffer();
4965 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004966 if (track->isStopping_1()) {
4967 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07004968 if (last && mHwPaused) {
4969 doHwResume = true;
4970 mHwPaused = false;
4971 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004972 }
4973 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4974 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004975 // We have consumed all the buffers of this track.
4976 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004977 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08004978 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004979 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4980 } else {
4981 audioHALFrames = 0;
4982 }
4983
Andy Hung818e7a32016-02-16 18:08:07 -08004984 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004985 if (mStandby || !last ||
4986 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004987 if (track->isStopping_2()) {
4988 track->mState = TrackBase::STOPPED;
4989 }
Eric Laurent81784c32012-11-19 14:55:58 -08004990 if (track->isStopped()) {
4991 track->reset();
4992 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004993 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004994 }
4995 } else {
4996 // No buffers for this track. Give it a few chances to
4997 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004998 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004999 if (--(track->mRetryCount) <= 0) {
5000 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07005001 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005002 // indicate to client process that the track was disabled because of underrun;
5003 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005004 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005005 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07005006 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
5007 "minFrames = %u, mFormat = %#x",
5008 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08005009 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07005010 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005011 doHwPause = true;
5012 mHwPaused = true;
5013 }
Eric Laurent81784c32012-11-19 14:55:58 -08005014 }
5015 }
5016 }
5017 }
5018
Eric Laurentd1f69b02014-12-15 14:33:13 -08005019 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07005020 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005021 for (size_t i = 0; i < mTracks.size(); i++) {
5022 if (mTracks[i]->isFlushPending()) {
5023 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005024 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005025 }
5026 }
5027 }
5028
5029 // make sure the pause/flush/resume sequence is executed in the right order.
5030 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5031 // before flush and then resume HW. This can happen in case of pause/flush/resume
5032 // if resume is received before pause is executed.
5033 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07005034 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005035 status_t result = mOutput->stream->pause();
5036 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005037 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005038 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005039 flushHw_l();
5040 }
5041 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005042 status_t result = mOutput->stream->resume();
5043 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005044 }
Eric Laurent81784c32012-11-19 14:55:58 -08005045 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005046 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005047
5048 return mixerStatus;
5049}
5050
5051void AudioFlinger::DirectOutputThread::threadLoop_mix()
5052{
Eric Laurent81784c32012-11-19 14:55:58 -08005053 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08005054 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005055 // output audio to hardware
5056 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07005057 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005058 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08005059 status_t status = mActiveTrack->getNextBuffer(&buffer);
5060 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08005061 // no need to pad with 0 for compressed audio
5062 if (audio_has_proportional_frames(mFormat)) {
5063 memset(curBuf, 0, frameCount * mFrameSize);
5064 }
Eric Laurent81784c32012-11-19 14:55:58 -08005065 break;
5066 }
5067 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
5068 frameCount -= buffer.frameCount;
5069 curBuf += buffer.frameCount * mFrameSize;
5070 mActiveTrack->releaseBuffer(&buffer);
5071 }
Andy Hung2098f272014-02-27 14:00:06 -08005072 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005073 mSleepTimeUs = 0;
5074 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005075 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005076}
5077
5078void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
5079{
Eric Laurentd1f69b02014-12-15 14:33:13 -08005080 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005081 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005082 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005083 return;
5084 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005085 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005086 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurente93cc032016-05-05 10:15:10 -07005087 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005088 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005089 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005090 }
Phil Burkfdb3c072016-02-09 10:47:02 -08005091 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08005092 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005093 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005094 }
5095}
5096
Eric Laurentd1f69b02014-12-15 14:33:13 -08005097void AudioFlinger::DirectOutputThread::threadLoop_exit()
5098{
5099 {
5100 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005101 for (size_t i = 0; i < mTracks.size(); i++) {
5102 if (mTracks[i]->isFlushPending()) {
5103 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005104 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005105 }
5106 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005107 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005108 flushHw_l();
5109 }
5110 }
5111 PlaybackThread::threadLoop_exit();
5112}
5113
5114// must be called with thread mutex locked
5115bool AudioFlinger::DirectOutputThread::shouldStandby_l()
5116{
5117 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07005118 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005119
vivek mehta9cd7ad12016-03-17 00:18:29 -07005120 if ((mType == DIRECT) && audio_is_linear_pcm(mFormat) && !usesHwAvSync()) {
5121 return !mStandby;
5122 }
5123
Eric Laurentd1f69b02014-12-15 14:33:13 -08005124 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
5125 // after a timeout and we will enter standby then.
5126 if (mTracks.size() > 0) {
5127 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07005128 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
5129 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005130 }
5131
Eric Laurent5cff4032015-05-26 13:49:58 -07005132 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08005133}
5134
Eric Laurent81784c32012-11-19 14:55:58 -08005135// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005136int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Eric Laurentad7dd962016-09-22 12:38:37 -07005137 audio_format_t format __unused, audio_session_t sessionId __unused, uid_t uid)
Eric Laurent81784c32012-11-19 14:55:58 -08005138{
Eric Laurentad7dd962016-09-22 12:38:37 -07005139 if (trackCountForUid_l(uid) > (PlaybackThread::kMaxTracksPerUid - 1)) {
5140 return -1;
5141 }
Eric Laurent81784c32012-11-19 14:55:58 -08005142 return 0;
5143}
5144
5145// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005146void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005147{
5148}
5149
Eric Laurent10351942014-05-08 18:49:52 -07005150// checkForNewParameter_l() must be called with ThreadBase::mLock held
5151bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
5152 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005153{
5154 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005155 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005156
Eric Laurent10351942014-05-08 18:49:52 -07005157 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005158
Eric Laurent10351942014-05-08 18:49:52 -07005159 AudioParameter param = AudioParameter(keyValuePair);
5160 int value;
5161 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5162 // forward device change to effects that have requested to be
5163 // aware of attached audio device.
5164 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005165 a2dpDeviceChanged =
5166 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005167 mOutDevice = value;
5168 for (size_t i = 0; i < mEffectChains.size(); i++) {
5169 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07005170 }
5171 }
Eric Laurent81784c32012-11-19 14:55:58 -08005172 }
Eric Laurent10351942014-05-08 18:49:52 -07005173 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5174 // do not accept frame count changes if tracks are open as the track buffer
5175 // size depends on frame count and correct behavior would not be garantied
5176 // if frame count is changed after track creation
5177 if (!mTracks.isEmpty()) {
5178 status = INVALID_OPERATION;
5179 } else {
5180 reconfig = true;
5181 }
5182 }
5183 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005184 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005185 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005186 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005187 mStandby = true;
5188 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005189 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005190 }
5191 if (status == NO_ERROR && reconfig) {
5192 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07005193 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005194 }
5195 }
5196
Eric Laurent42537be2016-01-08 17:16:42 -08005197 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005198}
5199
5200uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
5201{
5202 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005203 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005204 time = PlaybackThread::activeSleepTimeUs();
5205 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005206 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005207 }
5208 return time;
5209}
5210
5211uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
5212{
5213 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005214 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005215 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
5216 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005217 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005218 }
5219 return time;
5220}
5221
5222uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
5223{
5224 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005225 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005226 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
5227 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005228 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005229 }
5230 return time;
5231}
5232
5233void AudioFlinger::DirectOutputThread::cacheParameters_l()
5234{
5235 PlaybackThread::cacheParameters_l();
5236
5237 // use shorter standby delay as on normal output to release
5238 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07005239 // no delay on outputs with HW A/V sync
5240 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005241 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08005242 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005243 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07005244 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005245 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07005246 }
Eric Laurent81784c32012-11-19 14:55:58 -08005247}
5248
Eric Laurente659ef42014-09-29 13:06:46 -07005249void AudioFlinger::DirectOutputThread::flushHw_l()
5250{
Phil Burk062e67a2015-02-11 13:40:50 -08005251 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08005252 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005253 mFlushPending = false;
Eric Laurente659ef42014-09-29 13:06:46 -07005254}
5255
Eric Laurent81784c32012-11-19 14:55:58 -08005256// ----------------------------------------------------------------------------
5257
Eric Laurentbfb1b832013-01-07 09:53:42 -08005258AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07005259 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005260 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07005261 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07005262 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005263 mDrainSequence(0),
5264 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005265{
5266}
5267
5268AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
5269{
5270}
5271
5272void AudioFlinger::AsyncCallbackThread::onFirstRef()
5273{
5274 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
5275}
5276
5277bool AudioFlinger::AsyncCallbackThread::threadLoop()
5278{
5279 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005280 uint32_t writeAckSequence;
5281 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005282 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005283
5284 {
5285 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005286 while (!((mWriteAckSequence & 1) ||
5287 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005288 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005289 exitPending())) {
5290 mWaitWorkCV.wait(mLock);
5291 }
5292
Eric Laurentbfb1b832013-01-07 09:53:42 -08005293 if (exitPending()) {
5294 break;
5295 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005296 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
5297 mWriteAckSequence, mDrainSequence);
5298 writeAckSequence = mWriteAckSequence;
5299 mWriteAckSequence &= ~1;
5300 drainSequence = mDrainSequence;
5301 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005302 asyncError = mAsyncError;
5303 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005304 }
5305 {
Eric Laurent4de95592013-09-26 15:28:21 -07005306 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
5307 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005308 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005309 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005310 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005311 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005312 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005313 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005314 if (asyncError) {
5315 playbackThread->onAsyncError();
5316 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005317 }
5318 }
5319 }
5320 return false;
5321}
5322
5323void AudioFlinger::AsyncCallbackThread::exit()
5324{
5325 ALOGV("AsyncCallbackThread::exit");
5326 Mutex::Autolock _l(mLock);
5327 requestExit();
5328 mWaitWorkCV.broadcast();
5329}
5330
Eric Laurent3b4529e2013-09-05 18:09:19 -07005331void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005332{
5333 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005334 // bit 0 is cleared
5335 mWriteAckSequence = sequence << 1;
5336}
5337
5338void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5339{
5340 Mutex::Autolock _l(mLock);
5341 // ignore unexpected callbacks
5342 if (mWriteAckSequence & 2) {
5343 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005344 mWaitWorkCV.signal();
5345 }
5346}
5347
Eric Laurent3b4529e2013-09-05 18:09:19 -07005348void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005349{
5350 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005351 // bit 0 is cleared
5352 mDrainSequence = sequence << 1;
5353}
5354
5355void AudioFlinger::AsyncCallbackThread::resetDraining()
5356{
5357 Mutex::Autolock _l(mLock);
5358 // ignore unexpected callbacks
5359 if (mDrainSequence & 2) {
5360 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005361 mWaitWorkCV.signal();
5362 }
5363}
5364
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005365void AudioFlinger::AsyncCallbackThread::setAsyncError()
5366{
5367 Mutex::Autolock _l(mLock);
5368 mAsyncError = true;
5369 mWaitWorkCV.signal();
5370}
5371
Eric Laurentbfb1b832013-01-07 09:53:42 -08005372
5373// ----------------------------------------------------------------------------
5374AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07005375 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
5376 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07005377 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
5378 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005379{
Eric Laurentfd477972013-10-25 18:10:40 -07005380 //FIXME: mStandby should be set to true by ThreadBase constructor
5381 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07005382 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005383}
5384
Eric Laurentbfb1b832013-01-07 09:53:42 -08005385void AudioFlinger::OffloadThread::threadLoop_exit()
5386{
5387 if (mFlushPending || mHwPaused) {
5388 // If a flush is pending or track was paused, just discard buffered data
5389 flushHw_l();
5390 } else {
5391 mMixerStatus = MIXER_DRAIN_ALL;
5392 threadLoop_drain();
5393 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005394 if (mUseAsyncWrite) {
5395 ALOG_ASSERT(mCallbackThread != 0);
5396 mCallbackThread->exit();
5397 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005398 PlaybackThread::threadLoop_exit();
5399}
5400
5401AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5402 Vector< sp<Track> > *tracksToRemove
5403)
5404{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005405 size_t count = mActiveTracks.size();
5406
5407 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005408 bool doHwPause = false;
5409 bool doHwResume = false;
5410
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005411 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07005412
Eric Laurentbfb1b832013-01-07 09:53:42 -08005413 // find out which tracks need to be processed
5414 for (size_t i = 0; i < count; i++) {
5415 sp<Track> t = mActiveTracks[i].promote();
5416 // The track died recently
5417 if (t == 0) {
5418 continue;
5419 }
5420 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005421#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08005422 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005423#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005424 // Only consider last track started for volume and mixer state control.
5425 // In theory an older track could underrun and restart after the new one starts
5426 // but as we only care about the transition phase between two tracks on a
5427 // direct output, it is not a problem to ignore the underrun case.
5428 sp<Track> l = mLatestActiveTrack.promote();
5429 bool last = l.get() == track;
5430
Haynes Mathew George7844f672014-01-15 12:32:55 -08005431 if (track->isInvalid()) {
5432 ALOGW("An invalidated track shouldn't be in active list");
5433 tracksToRemove->add(track);
5434 continue;
5435 }
5436
5437 if (track->mState == TrackBase::IDLE) {
5438 ALOGW("An idle track shouldn't be in active list");
5439 continue;
5440 }
5441
Eric Laurentbfb1b832013-01-07 09:53:42 -08005442 if (track->isPausing()) {
5443 track->setPaused();
5444 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005445 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005446 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005447 mHwPaused = true;
5448 }
5449 // If we were part way through writing the mixbuffer to
5450 // the HAL we must save this until we resume
5451 // BUG - this will be wrong if a different track is made active,
5452 // in that case we want to discard the pending data in the
5453 // mixbuffer and tell the client to present it again when the
5454 // track is resumed
5455 mPausedWriteLength = mCurrentWriteLength;
5456 mPausedBytesRemaining = mBytesRemaining;
5457 mBytesRemaining = 0; // stop writing
5458 }
5459 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005460 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005461 if (track->isStopping_1()) {
5462 track->mRetryCount = kMaxTrackStopRetriesOffload;
5463 } else {
5464 track->mRetryCount = kMaxTrackRetriesOffload;
5465 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08005466 track->flushAck();
5467 if (last) {
5468 mFlushPending = true;
5469 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005470 } else if (track->isResumePending()){
5471 track->resumeAck();
5472 if (last) {
5473 if (mPausedBytesRemaining) {
5474 // Need to continue write that was interrupted
5475 mCurrentWriteLength = mPausedWriteLength;
5476 mBytesRemaining = mPausedBytesRemaining;
5477 mPausedBytesRemaining = 0;
5478 }
5479 if (mHwPaused) {
5480 doHwResume = true;
5481 mHwPaused = false;
5482 // threadLoop_mix() will handle the case that we need to
5483 // resume an interrupted write
5484 }
5485 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005486 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005487
Eric Laurent3df841a2016-07-15 15:15:40 -07005488 mLeftVolFloat = mRightVolFloat = -1.0;
5489
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005490 // Do not handle new data in this iteration even if track->framesReady()
5491 mixerStatus = MIXER_TRACKS_ENABLED;
5492 }
5493 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005494 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005495 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005496 if (track->mFillingUpStatus == Track::FS_FILLED) {
5497 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005498 if (last) {
5499 // make sure processVolume_l() will apply new volume even if 0
5500 mLeftVolFloat = mRightVolFloat = -1.0;
5501 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005502 }
5503
5504 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005505 sp<Track> previousTrack = mPreviousTrack.promote();
5506 if (previousTrack != 0) {
5507 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005508 // Flush any data still being written from last track
5509 mBytesRemaining = 0;
5510 if (mPausedBytesRemaining) {
5511 // Last track was paused so we also need to flush saved
5512 // mixbuffer state and invalidate track so that it will
5513 // re-submit that unwritten data when it is next resumed
5514 mPausedBytesRemaining = 0;
5515 // Invalidate is a bit drastic - would be more efficient
5516 // to have a flag to tell client that some of the
5517 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005518 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005519 }
5520 // flush data already sent to the DSP if changing audio session as audio
5521 // comes from a different source. Also invalidate previous track to force a
5522 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005523 if (previousTrack->sessionId() != track->sessionId()) {
5524 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005525 }
5526 }
5527 }
5528 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005529 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07005530 if (track->isStopping_1()) {
5531 track->mRetryCount = kMaxTrackStopRetriesOffload;
5532 } else {
5533 track->mRetryCount = kMaxTrackRetriesOffload;
5534 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005535 mActiveTrack = t;
5536 mixerStatus = MIXER_TRACKS_READY;
5537 }
5538 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005539 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005540 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005541 if (--(track->mRetryCount) <= 0) {
5542 // Hardware buffer can hold a large amount of audio so we must
5543 // wait for all current track's data to drain before we say
5544 // that the track is stopped.
5545 if (mBytesRemaining == 0) {
5546 // Only start draining when all data in mixbuffer
5547 // has been written
5548 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5549 track->mState = TrackBase::STOPPING_2; // so presentation completes after
5550 // drain do not drain if no data was ever sent to HAL (mStandby == true)
5551 if (last && !mStandby) {
5552 // do not modify drain sequence if we are already draining. This happens
5553 // when resuming from pause after drain.
5554 if ((mDrainSequence & 1) == 0) {
5555 mSleepTimeUs = 0;
5556 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
5557 mixerStatus = MIXER_DRAIN_TRACK;
5558 mDrainSequence += 2;
5559 }
5560 if (mHwPaused) {
5561 // It is possible to move from PAUSED to STOPPING_1 without
5562 // a resume so we must ensure hardware is running
5563 doHwResume = true;
5564 mHwPaused = false;
5565 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005566 }
5567 }
Eric Laurente93cc032016-05-05 10:15:10 -07005568 } else if (last) {
5569 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
5570 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005571 }
5572 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005573 // Drain has completed or we are in standby, signal presentation complete
5574 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005575 track->mState = TrackBase::STOPPED;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005576 uint32_t latency = 0;
5577 status_t result = mOutput->stream->getLatency(&latency);
5578 ALOGE_IF(result != OK,
5579 "Error when retrieving output stream latency: %d", result);
5580 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005581 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005582 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005583 track->presentationComplete(framesWritten, audioHALFrames);
5584 track->reset();
5585 tracksToRemove->add(track);
5586 }
5587 } else {
5588 // No buffers for this track. Give it a few chances to
5589 // fill a buffer, then remove it from active list.
5590 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07005591 bool running = false;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005592 uint64_t position = 0;
5593 struct timespec unused;
5594 // The running check restarts the retry counter at least once.
5595 status_t ret = mOutput->stream->getPresentationPosition(&position, &unused);
5596 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
5597 running = true;
5598 mOffloadUnderrunPosition = position;
5599 }
5600 if (ret == NO_ERROR) {
Andy Hungf8044752016-07-27 14:58:11 -07005601 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
5602 (long long)position, (long long)mOffloadUnderrunPosition);
5603 }
5604 if (running) { // still running, give us more time.
5605 track->mRetryCount = kMaxTrackRetriesOffload;
5606 } else {
5607 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5608 track->name());
5609 tracksToRemove->add(track);
5610 // indicate to client process that the track was disabled because of underrun;
5611 // it will then automatically call start() when data is available
5612 track->disable();
5613 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005614 } else if (last){
5615 mixerStatus = MIXER_TRACKS_ENABLED;
5616 }
5617 }
5618 }
5619 // compute volume for this track
5620 processVolume_l(track, last);
5621 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005622
Eric Laurentea0fade2013-10-04 16:23:48 -07005623 // make sure the pause/flush/resume sequence is executed in the right order.
5624 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5625 // before flush and then resume HW. This can happen in case of pause/flush/resume
5626 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07005627 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005628 status_t result = mOutput->stream->pause();
5629 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07005630 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005631 if (mFlushPending) {
5632 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005633 }
Eric Laurentfd477972013-10-25 18:10:40 -07005634 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005635 status_t result = mOutput->stream->resume();
5636 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07005637 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005638
Eric Laurentbfb1b832013-01-07 09:53:42 -08005639 // remove all the tracks that need to be...
5640 removeTracks_l(*tracksToRemove);
5641
5642 return mixerStatus;
5643}
5644
Eric Laurentbfb1b832013-01-07 09:53:42 -08005645// must be called with thread mutex locked
5646bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5647{
Eric Laurent3b4529e2013-09-05 18:09:19 -07005648 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5649 mWriteAckSequence, mDrainSequence);
5650 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005651 return true;
5652 }
5653 return false;
5654}
5655
Eric Laurentbfb1b832013-01-07 09:53:42 -08005656bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5657{
5658 Mutex::Autolock _l(mLock);
5659 return waitingAsyncCallback_l();
5660}
5661
5662void AudioFlinger::OffloadThread::flushHw_l()
5663{
Eric Laurente659ef42014-09-29 13:06:46 -07005664 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005665 // Flush anything still waiting in the mixbuffer
5666 mCurrentWriteLength = 0;
5667 mBytesRemaining = 0;
5668 mPausedWriteLength = 0;
5669 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07005670 // reset bytes written count to reflect that DSP buffers are empty after flush.
5671 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07005672 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08005673
Eric Laurentbfb1b832013-01-07 09:53:42 -08005674 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005675 // discard any pending drain or write ack by incrementing sequence
5676 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5677 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005678 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005679 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5680 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005681 }
5682}
5683
Haynes Mathew George05317d22016-05-03 16:34:26 -07005684void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
5685{
5686 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07005687 if (PlaybackThread::invalidateTracks_l(streamType)) {
5688 mFlushPending = true;
5689 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07005690}
5691
Eric Laurentbfb1b832013-01-07 09:53:42 -08005692// ----------------------------------------------------------------------------
5693
Eric Laurent81784c32012-11-19 14:55:58 -08005694AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005695 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005696 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07005697 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08005698 mWaitTimeMs(UINT_MAX)
5699{
5700 addOutputTrack(mainThread);
5701}
5702
5703AudioFlinger::DuplicatingThread::~DuplicatingThread()
5704{
5705 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5706 mOutputTracks[i]->destroy();
5707 }
5708}
5709
5710void AudioFlinger::DuplicatingThread::threadLoop_mix()
5711{
5712 // mix buffers...
5713 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08005714 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08005715 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005716 if (mMixerBufferValid) {
5717 memset(mMixerBuffer, 0, mMixerBufferSize);
5718 } else {
5719 memset(mSinkBuffer, 0, mSinkBufferSize);
5720 }
Eric Laurent81784c32012-11-19 14:55:58 -08005721 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005722 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005723 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005724 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005725 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005726}
5727
5728void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5729{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005730 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005731 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005732 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005733 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005734 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005735 }
5736 } else if (mBytesWritten != 0) {
5737 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5738 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005739 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005740 } else {
5741 // flush remaining overflow buffers in output tracks
5742 writeFrames = 0;
5743 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005744 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005745 }
5746}
5747
Eric Laurentbfb1b832013-01-07 09:53:42 -08005748ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005749{
5750 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005751 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005752 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005753 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005754 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005755}
5756
5757void AudioFlinger::DuplicatingThread::threadLoop_standby()
5758{
5759 // DuplicatingThread implements standby by stopping all tracks
5760 for (size_t i = 0; i < outputTracks.size(); i++) {
5761 outputTracks[i]->stop();
5762 }
5763}
5764
5765void AudioFlinger::DuplicatingThread::saveOutputTracks()
5766{
5767 outputTracks = mOutputTracks;
5768}
5769
5770void AudioFlinger::DuplicatingThread::clearOutputTracks()
5771{
5772 outputTracks.clear();
5773}
5774
5775void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5776{
5777 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005778 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5779 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5780 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5781 const size_t frameCount =
5782 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5783 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5784 // from different OutputTracks and their associated MixerThreads (e.g. one may
5785 // nearly empty and the other may be dropping data).
5786
5787 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005788 this,
5789 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005790 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005791 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005792 frameCount,
5793 IPCThreadState::self()->getCallingUid());
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07005794 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
5795 if (status != NO_ERROR) {
5796 ALOGE("addOutputTrack() initCheck failed %d", status);
5797 return;
Eric Laurent81784c32012-11-19 14:55:58 -08005798 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07005799 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
5800 mOutputTracks.add(outputTrack);
5801 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
5802 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005803}
5804
5805void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5806{
5807 Mutex::Autolock _l(mLock);
5808 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5809 if (mOutputTracks[i]->thread() == thread) {
5810 mOutputTracks[i]->destroy();
5811 mOutputTracks.removeAt(i);
5812 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07005813 if (thread->getOutput() == mOutput) {
5814 mOutput = NULL;
5815 }
Eric Laurent81784c32012-11-19 14:55:58 -08005816 return;
5817 }
5818 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07005819 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005820}
5821
5822// caller must hold mLock
5823void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5824{
5825 mWaitTimeMs = UINT_MAX;
5826 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5827 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5828 if (strong != 0) {
5829 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5830 if (waitTimeMs < mWaitTimeMs) {
5831 mWaitTimeMs = waitTimeMs;
5832 }
5833 }
5834 }
5835}
5836
5837
5838bool AudioFlinger::DuplicatingThread::outputsReady(
5839 const SortedVector< sp<OutputTrack> > &outputTracks)
5840{
5841 for (size_t i = 0; i < outputTracks.size(); i++) {
5842 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5843 if (thread == 0) {
5844 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5845 outputTracks[i].get());
5846 return false;
5847 }
5848 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5849 // see note at standby() declaration
5850 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5851 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5852 thread.get());
5853 return false;
5854 }
5855 }
5856 return true;
5857}
5858
5859uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5860{
5861 return (mWaitTimeMs * 1000) / 2;
5862}
5863
5864void AudioFlinger::DuplicatingThread::cacheParameters_l()
5865{
5866 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5867 updateWaitTime_l();
5868
5869 MixerThread::cacheParameters_l();
5870}
5871
5872// ----------------------------------------------------------------------------
5873// Record
5874// ----------------------------------------------------------------------------
5875
5876AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5877 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005878 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005879 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07005880 audio_devices_t inDevice,
5881 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08005882#ifdef TEE_SINK
5883 , const sp<NBAIO_Sink>& teeSink
5884#endif
5885 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07005886 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005887 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07005888 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005889 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005890#ifdef TEE_SINK
5891 , mTeeSink(teeSink)
5892#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005893 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5894 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005895 // mFastCapture below
5896 , mFastCaptureFutex(0)
5897 // mInputSource
5898 // mPipeSink
5899 // mPipeSource
5900 , mPipeFramesP2(0)
5901 // mPipeMemory
5902 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005903 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005904{
Glenn Kastend7dca052015-03-05 16:05:54 -08005905 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5906 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08005907
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005908 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005909
5910 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07005911 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005912 size_t numCounterOffers = 0;
5913 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005914#if !LOG_NDEBUG
5915 ssize_t index =
5916#else
5917 (void)
5918#endif
5919 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005920 ALOG_ASSERT(index == 0);
5921
5922 // initialize fast capture depending on configuration
5923 bool initFastCapture;
5924 switch (kUseFastCapture) {
5925 case FastCapture_Never:
5926 initFastCapture = false;
5927 break;
5928 case FastCapture_Always:
5929 initFastCapture = true;
5930 break;
5931 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07005932 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005933 break;
5934 // case FastCapture_Dynamic:
5935 }
5936
5937 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07005938 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005939 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07005940 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
5941 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005942 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5943 void *pipeBuffer;
5944 const sp<MemoryDealer> roHeap(readOnlyHeap());
5945 sp<IMemory> pipeMemory;
5946 if ((roHeap == 0) ||
5947 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5948 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5949 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5950 goto failed;
5951 }
5952 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5953 memset(pipeBuffer, 0, pipeSize);
5954 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5955 const NBAIO_Format offers[1] = {format};
5956 size_t numCounterOffers = 0;
5957 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5958 ALOG_ASSERT(index == 0);
5959 mPipeSink = pipe;
5960 PipeReader *pipeReader = new PipeReader(*pipe);
5961 numCounterOffers = 0;
5962 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5963 ALOG_ASSERT(index == 0);
5964 mPipeSource = pipeReader;
5965 mPipeFramesP2 = pipeFramesP2;
5966 mPipeMemory = pipeMemory;
5967
5968 // create fast capture
5969 mFastCapture = new FastCapture();
5970 FastCaptureStateQueue *sq = mFastCapture->sq();
5971#ifdef STATE_QUEUE_DUMP
5972 // FIXME
5973#endif
5974 FastCaptureState *state = sq->begin();
5975 state->mCblk = NULL;
5976 state->mInputSource = mInputSource.get();
5977 state->mInputSourceGen++;
5978 state->mPipeSink = pipe;
5979 state->mPipeSinkGen++;
5980 state->mFrameCount = mFrameCount;
5981 state->mCommand = FastCaptureState::COLD_IDLE;
5982 // already done in constructor initialization list
5983 //mFastCaptureFutex = 0;
5984 state->mColdFutexAddr = &mFastCaptureFutex;
5985 state->mColdGen++;
5986 state->mDumpState = &mFastCaptureDumpState;
5987#ifdef TEE_SINK
5988 // FIXME
5989#endif
5990 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
5991 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
5992 sq->end();
5993 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5994
5995 // start the fast capture
5996 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
5997 pid_t tid = mFastCapture->getTid();
Glenn Kasten8379b722016-03-18 14:54:17 -07005998 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005999#ifdef AUDIO_WATCHDOG
6000 // FIXME
6001#endif
6002
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006003 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006004 }
6005failed: ;
6006
6007 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08006008}
6009
Eric Laurent81784c32012-11-19 14:55:58 -08006010AudioFlinger::RecordThread::~RecordThread()
6011{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006012 if (mFastCapture != 0) {
6013 FastCaptureStateQueue *sq = mFastCapture->sq();
6014 FastCaptureState *state = sq->begin();
6015 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6016 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6017 if (old == -1) {
6018 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6019 }
6020 }
6021 state->mCommand = FastCaptureState::EXIT;
6022 sq->end();
6023 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6024 mFastCapture->join();
6025 mFastCapture.clear();
6026 }
6027 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07006028 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07006029 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08006030}
6031
6032void AudioFlinger::RecordThread::onFirstRef()
6033{
Glenn Kastend7dca052015-03-05 16:05:54 -08006034 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08006035}
6036
Eric Laurent81784c32012-11-19 14:55:58 -08006037bool AudioFlinger::RecordThread::threadLoop()
6038{
Eric Laurent81784c32012-11-19 14:55:58 -08006039 nsecs_t lastWarning = 0;
6040
6041 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006042
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006043reacquire_wakelock:
6044 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08006045 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006046 {
6047 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006048 size_t size = mActiveTracks.size();
6049 activeTracksGen = mActiveTracksGen;
6050 if (size > 0) {
6051 // FIXME an arbitrary choice
6052 activeTrack = mActiveTracks[0];
6053 acquireWakeLock_l(activeTrack->uid());
6054 if (size > 1) {
6055 SortedVector<int> tmp;
6056 for (size_t i = 0; i < size; i++) {
6057 tmp.add(mActiveTracks[i]->uid());
6058 }
6059 updateWakeLockUids_l(tmp);
6060 }
6061 } else {
6062 acquireWakeLock_l(-1);
6063 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006064 }
6065
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006066 // used to request a deferred sleep, to be executed later while mutex is unlocked
6067 uint32_t sleepUs = 0;
6068
6069 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006070 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006071 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07006072
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006073 // activeTracks accumulates a copy of a subset of mActiveTracks
6074 Vector< sp<RecordTrack> > activeTracks;
6075
Glenn Kasten735f45f2014-08-18 15:51:59 -07006076 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006077 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07006078
Glenn Kasten735f45f2014-08-18 15:51:59 -07006079 // reference to a fast track which is about to be removed
6080 sp<RecordTrack> fastTrackToRemove;
6081
Eric Laurent81784c32012-11-19 14:55:58 -08006082 { // scope for mLock
6083 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08006084
Eric Laurent021cf962014-05-13 10:18:14 -07006085 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006086
Eric Laurent000a4192014-01-29 15:17:32 -08006087 // check exitPending here because checkForNewParameters_l() and
6088 // checkForNewParameters_l() can temporarily release mLock
6089 if (exitPending()) {
6090 break;
6091 }
6092
Eric Laurent5c25d562016-07-13 17:17:45 -07006093 // sleep with mutex unlocked
6094 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07006095 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07006096 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
6097 ATRACE_END();
6098 sleepUs = 0;
6099 continue;
6100 }
6101
Glenn Kasten2b806402013-11-20 16:37:38 -08006102 // if no active track(s), then standby and release wakelock
6103 size_t size = mActiveTracks.size();
6104 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07006105 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006106 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08006107 releaseWakeLock_l();
6108 ALOGV("RecordThread: loop stopping");
6109 // go to sleep
6110 mWaitWorkCV.wait(mLock);
6111 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006112 goto reacquire_wakelock;
6113 }
6114
Glenn Kasten2b806402013-11-20 16:37:38 -08006115 if (mActiveTracksGen != activeTracksGen) {
6116 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006117 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08006118 for (size_t i = 0; i < size; i++) {
6119 tmp.add(mActiveTracks[i]->uid());
6120 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006121 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08006122 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006123
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006124 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07006125 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006126 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07006127
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006128 activeTrack = mActiveTracks[i];
6129 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07006130 if (activeTrack->isFastTrack()) {
6131 ALOG_ASSERT(fastTrackToRemove == 0);
6132 fastTrackToRemove = activeTrack;
6133 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006134 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08006135 mActiveTracks.remove(activeTrack);
6136 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006137 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07006138 continue;
6139 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006140
6141 TrackBase::track_state activeTrackState = activeTrack->mState;
6142 switch (activeTrackState) {
6143
6144 case TrackBase::PAUSING:
6145 mActiveTracks.remove(activeTrack);
6146 mActiveTracksGen++;
6147 doBroadcast = true;
6148 size--;
6149 continue;
6150
6151 case TrackBase::STARTING_1:
6152 sleepUs = 10000;
6153 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07006154 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006155 continue;
6156
6157 case TrackBase::STARTING_2:
6158 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006159 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07006160 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07006161 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006162 break;
6163
6164 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07006165 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006166 break;
6167
6168 case TrackBase::IDLE:
6169 i++;
6170 continue;
6171
6172 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08006173 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07006174 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006175
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006176 activeTracks.add(activeTrack);
6177 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07006178
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006179 if (activeTrack->isFastTrack()) {
6180 ALOG_ASSERT(!mFastTrackAvail);
6181 ALOG_ASSERT(fastTrack == 0);
6182 fastTrack = activeTrack;
6183 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006184 }
Eric Laurent5c25d562016-07-13 17:17:45 -07006185
6186 if (allStopped) {
6187 standbyIfNotAlreadyInStandby();
6188 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006189 if (doBroadcast) {
6190 mStartStopCond.broadcast();
6191 }
6192
6193 // sleep if there are no active tracks to process
6194 if (activeTracks.size() == 0) {
6195 if (sleepUs == 0) {
6196 sleepUs = kRecordThreadSleepUs;
6197 }
6198 continue;
6199 }
6200 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07006201
Eric Laurent81784c32012-11-19 14:55:58 -08006202 lockEffectChains_l(effectChains);
6203 }
6204
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006205 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07006206
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006207 size_t size = effectChains.size();
6208 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006209 // thread mutex is not locked, but effect chain is locked
6210 effectChains[i]->process_l();
6211 }
6212
Glenn Kasten735f45f2014-08-18 15:51:59 -07006213 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006214 if (mFastCapture != 0) {
6215 FastCaptureStateQueue *sq = mFastCapture->sq();
6216 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07006217 bool didModify = false;
6218 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006219 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
6220 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
6221 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6222 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6223 if (old == -1) {
6224 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6225 }
6226 }
6227 state->mCommand = FastCaptureState::READ_WRITE;
6228#if 0 // FIXME
6229 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08006230 FastThreadDumpState::kSamplingNforLowRamDevice :
6231 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006232#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07006233 didModify = true;
6234 }
6235 audio_track_cblk_t *cblkOld = state->mCblk;
6236 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
6237 if (cblkNew != cblkOld) {
6238 state->mCblk = cblkNew;
6239 // block until acked if removing a fast track
6240 if (cblkOld != NULL) {
6241 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
6242 }
6243 didModify = true;
6244 }
6245 sq->end(didModify);
6246 if (didModify) {
6247 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006248#if 0
6249 if (kUseFastCapture == FastCapture_Dynamic) {
6250 mNormalSource = mPipeSource;
6251 }
6252#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006253 }
6254 }
6255
Glenn Kasten735f45f2014-08-18 15:51:59 -07006256 // now run the fast track destructor with thread mutex unlocked
6257 fastTrackToRemove.clear();
6258
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006259 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
6260 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
6261 // slow, then this RecordThread will overrun by not calling HAL read often enough.
6262 // If destination is non-contiguous, first read past the nominal end of buffer, then
6263 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006264
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006265 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006266 ssize_t framesRead;
6267
6268 // If an NBAIO source is present, use it to read the normal capture's data
6269 if (mPipeSource != 0) {
6270 size_t framesToRead = mBufferSize / mFrameSize;
Glenn Kasten1b291842016-07-18 14:55:21 -07006271 framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hung57446612015-04-19 23:56:46 -07006272 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
Glenn Kastend79072e2016-01-06 08:41:20 -08006273 framesToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07006274 // since pipe is non-blocking, simulate blocking input by waiting for 1/2 of
6275 // buffer size or at least for 20ms.
6276 size_t sleepFrames = max(
6277 min(mPipeFramesP2, mRsmpInFramesP2) / 2, FMS_20 * mSampleRate / 1000);
6278 if (framesRead <= (ssize_t) sleepFrames) {
6279 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
6280 }
6281 if (framesRead < 0) {
6282 status_t status = (status_t) framesRead;
6283 switch (status) {
6284 case OVERRUN:
6285 ALOGW("overrun on read from pipe");
6286 framesRead = 0;
6287 break;
6288 case NEGOTIATE:
6289 ALOGE("re-negotiation is needed");
6290 framesRead = -1; // Will cause an attempt to recover.
6291 break;
6292 default:
6293 ALOGE("unknown error %d on read from pipe", status);
6294 break;
6295 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006296 }
6297 // otherwise use the HAL / AudioStreamIn directly
6298 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07006299 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006300 size_t bytesRead;
6301 status_t result = mInput->stream->read(
6302 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07006303 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006304 if (result < 0) {
6305 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006306 } else {
6307 framesRead = bytesRead / mFrameSize;
6308 }
6309 }
6310
Andy Hung3f0c9022016-01-15 17:49:46 -08006311 // Update server timestamp with server stats
6312 // systemTime() is optional if the hardware supports timestamps.
6313 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
6314 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6315
6316 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006317 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08006318 int64_t position, time;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006319 int ret = mInput->stream->getCapturePosition(&position, &time);
Andy Hung3f0c9022016-01-15 17:49:46 -08006320 if (ret == NO_ERROR) {
6321 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
6322 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
6323 // Note: In general record buffers should tend to be empty in
6324 // a properly running pipeline.
6325 //
6326 // Also, it is not advantageous to call get_presentation_position during the read
6327 // as the read obtains a lock, preventing the timestamp call from executing.
6328 }
6329 }
6330 // Use this to track timestamp information
6331 // ALOGD("%s", mTimestamp.toString().c_str());
6332
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006333 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006334 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006335 // Force input into standby so that it tries to recover at next read attempt
6336 inputStandBy();
6337 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006338 }
6339 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006340 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006341 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006342 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006343
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006344 if (mTeeSink != 0) {
Andy Hung57446612015-04-19 23:56:46 -07006345 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006346 }
6347 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006348 {
6349 size_t part1 = mRsmpInFramesP2 - rear;
6350 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07006351 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006352 (framesRead - part1) * mFrameSize);
6353 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006354 }
6355 rear = mRsmpInRear += framesRead;
6356
6357 size = activeTracks.size();
6358 // loop over each active track
6359 for (size_t i = 0; i < size; i++) {
6360 activeTrack = activeTracks[i];
6361
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006362 // skip fast tracks, as those are handled directly by FastCapture
6363 if (activeTrack->isFastTrack()) {
6364 continue;
6365 }
6366
Andy Hung73c02e42015-03-29 01:13:58 -07006367 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07006368 // TODO: Update the activeTrack buffer converter in case of reconfigure.
6369
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006370 enum {
6371 OVERRUN_UNKNOWN,
6372 OVERRUN_TRUE,
6373 OVERRUN_FALSE
6374 } overrun = OVERRUN_UNKNOWN;
6375
6376 // loop over getNextBuffer to handle circular sink
6377 for (;;) {
6378
6379 activeTrack->mSink.frameCount = ~0;
6380 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
6381 size_t framesOut = activeTrack->mSink.frameCount;
6382 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
6383
Andy Hung73c02e42015-03-29 01:13:58 -07006384 // check available frames and handle overrun conditions
6385 // if the record track isn't draining fast enough.
6386 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006387 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07006388 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
6389 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006390 overrun = OVERRUN_TRUE;
6391 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006392 if (framesOut == 0 || framesIn == 0) {
6393 break;
6394 }
6395
Andy Hung6770c6f2015-04-07 13:43:36 -07006396 // Don't allow framesOut to be larger than what is possible with resampling
6397 // from framesIn.
6398 // This isn't strictly necessary but helps limit buffer resizing in
6399 // RecordBufferConverter. TODO: remove when no longer needed.
6400 framesOut = min(framesOut,
6401 destinationFramesPossible(
6402 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07006403 // process frames from the RecordThread buffer provider to the RecordTrack buffer
6404 framesOut = activeTrack->mRecordBufferConverter->convert(
6405 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006406
6407 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
6408 overrun = OVERRUN_FALSE;
6409 }
6410
6411 if (activeTrack->mFramesToDrop == 0) {
6412 if (framesOut > 0) {
6413 activeTrack->mSink.frameCount = framesOut;
6414 activeTrack->releaseBuffer(&activeTrack->mSink);
6415 }
6416 } else {
6417 // FIXME could do a partial drop of framesOut
6418 if (activeTrack->mFramesToDrop > 0) {
6419 activeTrack->mFramesToDrop -= framesOut;
6420 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006421 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006422 }
6423 } else {
6424 activeTrack->mFramesToDrop += framesOut;
6425 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
6426 activeTrack->mSyncStartEvent->isCancelled()) {
6427 ALOGW("Synced record %s, session %d, trigger session %d",
6428 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
6429 activeTrack->sessionId(),
6430 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08006431 activeTrack->mSyncStartEvent->triggerSession() :
6432 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006433 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006434 }
6435 }
6436 }
6437
6438 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006439 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006440 }
6441 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006442
6443 switch (overrun) {
6444 case OVERRUN_TRUE:
6445 // client isn't retrieving buffers fast enough
6446 if (!activeTrack->setOverflow()) {
6447 nsecs_t now = systemTime();
6448 // FIXME should lastWarning per track?
6449 if ((now - lastWarning) > kWarningThrottleNs) {
6450 ALOGW("RecordThread: buffer overflow");
6451 lastWarning = now;
6452 }
6453 }
6454 break;
6455 case OVERRUN_FALSE:
6456 activeTrack->clearOverflow();
6457 break;
6458 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006459 break;
6460 }
6461
Andy Hung3f0c9022016-01-15 17:49:46 -08006462 // update frame information and push timestamp out
6463 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08006464 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08006465 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
6466 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006467 }
6468
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006469unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08006470 // enable changes in effect chain
6471 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006472 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08006473 }
6474
Glenn Kasten93e471f2013-08-19 08:40:07 -07006475 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08006476
6477 {
6478 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07006479 for (size_t i = 0; i < mTracks.size(); i++) {
6480 sp<RecordTrack> track = mTracks[i];
6481 track->invalidate();
6482 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006483 mActiveTracks.clear();
6484 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08006485 mStartStopCond.broadcast();
6486 }
6487
6488 releaseWakeLock();
6489
6490 ALOGV("RecordThread %p exiting", this);
6491 return false;
6492}
6493
Glenn Kasten93e471f2013-08-19 08:40:07 -07006494void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08006495{
6496 if (!mStandby) {
6497 inputStandBy();
6498 mStandby = true;
6499 }
6500}
6501
6502void AudioFlinger::RecordThread::inputStandBy()
6503{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006504 // Idle the fast capture if it's currently running
6505 if (mFastCapture != 0) {
6506 FastCaptureStateQueue *sq = mFastCapture->sq();
6507 FastCaptureState *state = sq->begin();
6508 if (!(state->mCommand & FastCaptureState::IDLE)) {
6509 state->mCommand = FastCaptureState::COLD_IDLE;
6510 state->mColdFutexAddr = &mFastCaptureFutex;
6511 state->mColdGen++;
6512 mFastCaptureFutex = 0;
6513 sq->end();
6514 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
6515 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
6516#if 0
6517 if (kUseFastCapture == FastCapture_Dynamic) {
6518 // FIXME
6519 }
6520#endif
6521#ifdef AUDIO_WATCHDOG
6522 // FIXME
6523#endif
6524 } else {
6525 sq->end(false /*didModify*/);
6526 }
6527 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006528 status_t result = mInput->stream->standby();
6529 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07006530
6531 // If going into standby, flush the pipe source.
6532 if (mPipeSource.get() != nullptr) {
6533 const ssize_t flushed = mPipeSource->flush();
6534 if (flushed > 0) {
6535 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
6536 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
6537 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6538 }
6539 }
Eric Laurent81784c32012-11-19 14:55:58 -08006540}
6541
Glenn Kasten05997e22014-03-13 15:08:33 -07006542// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07006543sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08006544 const sp<AudioFlinger::Client>& client,
6545 uint32_t sampleRate,
6546 audio_format_t format,
6547 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08006548 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08006549 audio_session_t sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07006550 size_t *notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006551 int uid,
Eric Laurent05067782016-06-01 18:27:28 -07006552 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08006553 pid_t tid,
6554 status_t *status)
6555{
Glenn Kasten74935e42013-12-19 08:56:45 -08006556 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08006557 sp<RecordTrack> track;
6558 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07006559 audio_input_flags_t inputFlags = mInput->flags;
6560
6561 // special case for FAST flag considered OK if fast capture is present
6562 if (hasFastCapture()) {
6563 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
6564 }
6565
6566 // Check if requested flags are compatible with output stream flags
6567 if ((*flags & inputFlags) != *flags) {
6568 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
6569 " input flags (%08x)",
6570 *flags, inputFlags);
6571 *flags = (audio_input_flags_t)(*flags & inputFlags);
6572 }
Eric Laurent81784c32012-11-19 14:55:58 -08006573
Glenn Kasten90e58b12013-07-31 16:16:02 -07006574 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07006575 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006576 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07006577 // we formerly checked for a callback handler (non-0 tid),
6578 // but that is no longer required for TRANSFER_OBTAIN mode
6579 //
Glenn Kasten74105912014-07-03 12:28:53 -07006580 // frame count is not specified, or is exactly the pipe depth
6581 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006582 // PCM data
6583 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006584 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006585 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006586 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006587 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006588 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07006589 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006590 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006591 hasFastCapture() &&
6592 // there are sufficient fast track slots available
6593 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07006594 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07006595 // check compatibility with audio effects.
6596 Mutex::Autolock _l(mLock);
6597 // Do not accept FAST flag if the session has software effects
6598 sp<EffectChain> chain = getEffectChain_l(sessionId);
6599 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07006600 audio_input_flags_t old = *flags;
6601 chain->checkInputFlagCompatibility(flags);
6602 if (old != *flags) {
6603 ALOGV("AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
6604 (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07006605 }
6606 }
Eric Laurent122f7e72016-06-29 11:53:29 -07006607 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07006608 "AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
6609 frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006610 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006611 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
Glenn Kasten74105912014-07-03 12:28:53 -07006612 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006613 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07006614 frameCount, mFrameCount, mPipeFramesP2,
6615 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
6616 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07006617 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07006618 }
6619 }
6620
6621 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07006622 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07006623 // fast track: frame count is exactly the pipe depth
6624 frameCount = mPipeFramesP2;
6625 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
6626 *notificationFrames = mFrameCount;
6627 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006628 // not fast track: max notification period is resampled equivalent of one HAL buffer time
6629 // or 20 ms if there is a fast capture
6630 // TODO This could be a roundupRatio inline, and const
6631 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
6632 * sampleRate + mSampleRate - 1) / mSampleRate;
6633 // minimum number of notification periods is at least kMinNotifications,
6634 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
6635 static const size_t kMinNotifications = 3;
6636 static const uint32_t kMinMs = 30;
6637 // TODO This could be a roundupRatio inline
6638 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
6639 // TODO This could be a roundupRatio inline
6640 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
6641 maxNotificationFrames;
6642 const size_t minFrameCount = maxNotificationFrames *
6643 max(kMinNotifications, minNotificationsByMs);
6644 frameCount = max(frameCount, minFrameCount);
6645 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
6646 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07006647 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07006648 }
Glenn Kasten74935e42013-12-19 08:56:45 -08006649 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07006650
Glenn Kasten15e57982013-09-24 11:52:37 -07006651 lStatus = initCheck();
6652 if (lStatus != NO_ERROR) {
6653 ALOGE("createRecordTrack_l() audio driver not initialized");
6654 goto Exit;
6655 }
Eric Laurent81784c32012-11-19 14:55:58 -08006656
6657 { // scope for mLock
6658 Mutex::Autolock _l(mLock);
6659
6660 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07006661 format, channelMask, frameCount, NULL, sessionId, uid,
6662 *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08006663
Glenn Kasten03003332013-08-06 15:40:54 -07006664 lStatus = track->initCheck();
6665 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07006666 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08006667 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08006668 goto Exit;
6669 }
6670 mTracks.add(track);
6671
6672 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6673 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6674 mAudioFlinger->btNrecIsOff();
6675 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6676 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006677
Eric Laurent05067782016-06-01 18:27:28 -07006678 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006679 pid_t callingPid = IPCThreadState::self()->getCallingPid();
6680 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
6681 // so ask activity manager to do this on our behalf
6682 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
6683 }
Eric Laurent81784c32012-11-19 14:55:58 -08006684 }
Glenn Kasten05997e22014-03-13 15:08:33 -07006685
Eric Laurent81784c32012-11-19 14:55:58 -08006686 lStatus = NO_ERROR;
6687
6688Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07006689 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08006690 return track;
6691}
6692
6693status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6694 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08006695 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08006696{
6697 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6698 sp<ThreadBase> strongMe = this;
6699 status_t status = NO_ERROR;
6700
6701 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006702 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006703 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006704 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08006705 triggerSession,
6706 recordTrack->sessionId(),
6707 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006708 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08006709 // Sync event can be cancelled by the trigger session if the track is not in a
6710 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006711 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006712 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006713 } else {
6714 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006715 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006716 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08006717 }
6718 }
6719
6720 {
Glenn Kasten47c20702013-08-13 15:37:35 -07006721 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08006722 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006723 if (mActiveTracks.indexOf(recordTrack) >= 0) {
6724 if (recordTrack->mState == TrackBase::PAUSING) {
6725 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006726 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006727 } else {
6728 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08006729 }
6730 return status;
6731 }
6732
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006733 // TODO consider other ways of handling this, such as changing the state to :STARTING and
6734 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6735 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006736 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08006737 mActiveTracks.add(recordTrack);
6738 mActiveTracksGen++;
Eric Laurent83b88082014-06-20 18:31:16 -07006739 status_t status = NO_ERROR;
6740 if (recordTrack->isExternalTrack()) {
6741 mLock.unlock();
Glenn Kastend848eb42016-03-08 13:42:11 -08006742 status = AudioSystem::startInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006743 mLock.lock();
6744 // FIXME should verify that recordTrack is still in mActiveTracks
6745 if (status != NO_ERROR) {
6746 mActiveTracks.remove(recordTrack);
6747 mActiveTracksGen++;
6748 recordTrack->clearSyncStartEvent();
6749 ALOGV("RecordThread::start error %d", status);
6750 return status;
6751 }
Eric Laurent81784c32012-11-19 14:55:58 -08006752 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006753 // Catch up with current buffer indices if thread is already running.
6754 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
6755 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6756 // see previously buffered data before it called start(), but with greater risk of overrun.
6757
Andy Hung73c02e42015-03-29 01:13:58 -07006758 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07006759 // clear any converter state as new data will be discontinuous
6760 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006761 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08006762 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08006763 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08006764 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006765 ALOGV("Record failed to start");
6766 status = BAD_VALUE;
6767 goto startError;
6768 }
Eric Laurent81784c32012-11-19 14:55:58 -08006769 return status;
6770 }
Glenn Kasten7c027242012-12-26 14:43:16 -08006771
Eric Laurent81784c32012-11-19 14:55:58 -08006772startError:
Eric Laurent83b88082014-06-20 18:31:16 -07006773 if (recordTrack->isExternalTrack()) {
Glenn Kastend848eb42016-03-08 13:42:11 -08006774 AudioSystem::stopInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006775 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006776 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006777 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08006778 return status;
6779}
6780
Eric Laurent81784c32012-11-19 14:55:58 -08006781void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6782{
6783 sp<SyncEvent> strongEvent = event.promote();
6784
6785 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08006786 sp<RefBase> ptr = strongEvent->cookie().promote();
6787 if (ptr != 0) {
6788 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6789 recordTrack->handleSyncStartEvent(strongEvent);
6790 }
Eric Laurent81784c32012-11-19 14:55:58 -08006791 }
6792}
6793
Glenn Kastena8356f62013-07-25 14:37:52 -07006794bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08006795 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07006796 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006797 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08006798 return false;
6799 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006800 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006801 recordTrack->mState = TrackBase::PAUSING;
Eric Laurent5c25d562016-07-13 17:17:45 -07006802 // signal thread to stop
6803 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08006804 // do not wait for mStartStopCond if exiting
6805 if (exitPending()) {
6806 return true;
6807 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006808 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08006809 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006810 // if we have been restarted, recordTrack is in mActiveTracks here
6811 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006812 ALOGV("Record stopped OK");
6813 return true;
6814 }
6815 return false;
6816}
6817
Glenn Kasten0f11b512014-01-31 16:18:54 -08006818bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08006819{
6820 return false;
6821}
6822
Glenn Kasten0f11b512014-01-31 16:18:54 -08006823status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006824{
6825#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6826 if (!isValidSyncEvent(event)) {
6827 return BAD_VALUE;
6828 }
6829
Glenn Kastend848eb42016-03-08 13:42:11 -08006830 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08006831 status_t ret = NAME_NOT_FOUND;
6832
6833 Mutex::Autolock _l(mLock);
6834
6835 for (size_t i = 0; i < mTracks.size(); i++) {
6836 sp<RecordTrack> track = mTracks[i];
6837 if (eventSession == track->sessionId()) {
6838 (void) track->setSyncEvent(event);
6839 ret = NO_ERROR;
6840 }
6841 }
6842 return ret;
6843#else
6844 return BAD_VALUE;
6845#endif
6846}
6847
6848// destroyTrack_l() must be called with ThreadBase::mLock held
6849void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6850{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006851 track->terminate();
6852 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006853 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006854 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006855 removeTrack_l(track);
6856 }
6857}
6858
6859void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6860{
6861 mTracks.remove(track);
6862 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006863 if (track->isFastTrack()) {
6864 ALOG_ASSERT(!mFastTrackAvail);
6865 mFastTrackAvail = true;
6866 }
Eric Laurent81784c32012-11-19 14:55:58 -08006867}
6868
6869void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6870{
6871 dumpInternals(fd, args);
6872 dumpTracks(fd, args);
6873 dumpEffectChains(fd, args);
6874}
6875
6876void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6877{
Elliott Hughes87cebad2014-05-22 10:14:43 -07006878 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08006879
Glenn Kasten44182c22015-03-05 17:12:23 -08006880 dumpBase(fd, args);
6881
6882 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006883 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006884 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006885 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006886 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08006887
Glenn Kasten2f90c512015-12-02 11:40:09 -08006888 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
6889 // while we are dumping it. It may be inconsistent, but it won't mutate!
6890 // This is a large object so we place it on the heap.
6891 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
6892 const FastCaptureDumpState *copy = new FastCaptureDumpState(mFastCaptureDumpState);
6893 copy->dump(fd);
6894 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08006895}
6896
Glenn Kasten0f11b512014-01-31 16:18:54 -08006897void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006898{
6899 const size_t SIZE = 256;
6900 char buffer[SIZE];
6901 String8 result;
6902
Marco Nelissenb2208842014-02-07 14:00:50 -08006903 size_t numtracks = mTracks.size();
6904 size_t numactive = mActiveTracks.size();
6905 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006906 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006907 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006908 dprintf(fd, " of which %zu are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006909 RecordTrack::appendDumpHeader(result);
6910 for (size_t i = 0; i < numtracks ; ++i) {
6911 sp<RecordTrack> track = mTracks[i];
6912 if (track != 0) {
6913 bool active = mActiveTracks.indexOf(track) >= 0;
6914 if (active) {
6915 numactiveseen++;
6916 }
6917 track->dump(buffer, SIZE, active);
6918 result.append(buffer);
6919 }
Eric Laurent81784c32012-11-19 14:55:58 -08006920 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006921 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006922 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006923 }
6924
Marco Nelissenb2208842014-02-07 14:00:50 -08006925 if (numactiveseen != numactive) {
6926 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6927 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006928 result.append(buffer);
6929 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006930 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006931 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006932 if (mTracks.indexOf(track) < 0) {
6933 track->dump(buffer, SIZE, true);
6934 result.append(buffer);
6935 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006936 }
Eric Laurent81784c32012-11-19 14:55:58 -08006937
6938 }
6939 write(fd, result.string(), result.size());
6940}
6941
Andy Hung73c02e42015-03-29 01:13:58 -07006942
6943void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
6944{
6945 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6946 RecordThread *recordThread = (RecordThread *) threadBase.get();
6947 mRsmpInFront = recordThread->mRsmpInRear;
6948 mRsmpInUnrel = 0;
6949}
6950
6951void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
6952 size_t *framesAvailable, bool *hasOverrun)
6953{
6954 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6955 RecordThread *recordThread = (RecordThread *) threadBase.get();
6956 const int32_t rear = recordThread->mRsmpInRear;
6957 const int32_t front = mRsmpInFront;
6958 const ssize_t filled = rear - front;
6959
6960 size_t framesIn;
6961 bool overrun = false;
6962 if (filled < 0) {
6963 // should not happen, but treat like a massive overrun and re-sync
6964 framesIn = 0;
6965 mRsmpInFront = rear;
6966 overrun = true;
6967 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
6968 framesIn = (size_t) filled;
6969 } else {
6970 // client is not keeping up with server, but give it latest data
6971 framesIn = recordThread->mRsmpInFrames;
6972 mRsmpInFront = /* front = */ rear - framesIn;
6973 overrun = true;
6974 }
6975 if (framesAvailable != NULL) {
6976 *framesAvailable = framesIn;
6977 }
6978 if (hasOverrun != NULL) {
6979 *hasOverrun = overrun;
6980 }
6981}
6982
Eric Laurent81784c32012-11-19 14:55:58 -08006983// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006984status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08006985 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006986{
Andy Hung73c02e42015-03-29 01:13:58 -07006987 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006988 if (threadBase == 0) {
6989 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006990 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006991 return NOT_ENOUGH_DATA;
6992 }
6993 RecordThread *recordThread = (RecordThread *) threadBase.get();
6994 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07006995 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07006996 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006997 // FIXME should not be P2 (don't want to increase latency)
6998 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006999 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07007000 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007001 front &= recordThread->mRsmpInFramesP2 - 1;
7002 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07007003 if (part1 > (size_t) filled) {
7004 part1 = filled;
7005 }
7006 size_t ask = buffer->frameCount;
7007 ALOG_ASSERT(ask > 0);
7008 if (part1 > ask) {
7009 part1 = ask;
7010 }
7011 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07007012 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07007013 buffer->raw = NULL;
7014 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07007015 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07007016 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08007017 }
7018
Andy Hung57446612015-04-19 23:56:46 -07007019 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07007020 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07007021 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08007022 return NO_ERROR;
7023}
7024
7025// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007026void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
7027 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08007028{
Glenn Kasten85948432013-08-19 12:09:05 -07007029 size_t stepCount = buffer->frameCount;
7030 if (stepCount == 0) {
7031 return;
7032 }
Andy Hung73c02e42015-03-29 01:13:58 -07007033 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
7034 mRsmpInUnrel -= stepCount;
7035 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07007036 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08007037 buffer->frameCount = 0;
7038}
7039
Andy Hung97a893e2015-03-29 01:03:07 -07007040AudioFlinger::RecordThread::RecordBufferConverter::RecordBufferConverter(
7041 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
7042 uint32_t srcSampleRate,
7043 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
7044 uint32_t dstSampleRate) :
7045 mSrcChannelMask(AUDIO_CHANNEL_INVALID), // updateParameters will set following vars
7046 // mSrcFormat
7047 // mSrcSampleRate
7048 // mDstChannelMask
7049 // mDstFormat
7050 // mDstSampleRate
7051 // mSrcChannelCount
7052 // mDstChannelCount
7053 // mDstFrameSize
7054 mBuf(NULL), mBufFrames(0), mBufFrameSize(0),
Andy Hungd330ee42015-04-20 13:23:41 -07007055 mResampler(NULL),
7056 mIsLegacyDownmix(false),
7057 mIsLegacyUpmix(false),
7058 mRequiresFloat(false),
7059 mInputConverterProvider(NULL)
Andy Hung97a893e2015-03-29 01:03:07 -07007060{
7061 (void)updateParameters(srcChannelMask, srcFormat, srcSampleRate,
7062 dstChannelMask, dstFormat, dstSampleRate);
7063}
7064
7065AudioFlinger::RecordThread::RecordBufferConverter::~RecordBufferConverter() {
7066 free(mBuf);
7067 delete mResampler;
Andy Hungd330ee42015-04-20 13:23:41 -07007068 delete mInputConverterProvider;
Andy Hung97a893e2015-03-29 01:03:07 -07007069}
7070
7071size_t AudioFlinger::RecordThread::RecordBufferConverter::convert(void *dst,
7072 AudioBufferProvider *provider, size_t frames)
7073{
Andy Hungd330ee42015-04-20 13:23:41 -07007074 if (mInputConverterProvider != NULL) {
7075 mInputConverterProvider->setBufferProvider(provider);
7076 provider = mInputConverterProvider;
7077 }
7078
7079 if (mResampler == NULL) {
Andy Hung97a893e2015-03-29 01:03:07 -07007080 ALOGVV("NO RESAMPLING sampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
7081 mSrcSampleRate, mSrcFormat, mDstFormat);
7082
7083 AudioBufferProvider::Buffer buffer;
7084 for (size_t i = frames; i > 0; ) {
7085 buffer.frameCount = i;
Glenn Kastend79072e2016-01-06 08:41:20 -08007086 status_t status = provider->getNextBuffer(&buffer);
Andy Hung97a893e2015-03-29 01:03:07 -07007087 if (status != OK || buffer.frameCount == 0) {
7088 frames -= i; // cannot fill request.
7089 break;
7090 }
Andy Hungd330ee42015-04-20 13:23:41 -07007091 // format convert to destination buffer
7092 convertNoResampler(dst, buffer.raw, buffer.frameCount);
Andy Hung97a893e2015-03-29 01:03:07 -07007093
7094 dst = (int8_t*)dst + buffer.frameCount * mDstFrameSize;
7095 i -= buffer.frameCount;
7096 provider->releaseBuffer(&buffer);
7097 }
7098 } else {
7099 ALOGVV("RESAMPLING mSrcSampleRate:%u mDstSampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
7100 mSrcSampleRate, mDstSampleRate, mSrcFormat, mDstFormat);
7101
Andy Hungd330ee42015-04-20 13:23:41 -07007102 // reallocate buffer if needed
7103 if (mBufFrameSize != 0 && mBufFrames < frames) {
7104 free(mBuf);
7105 mBufFrames = frames;
7106 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
7107 }
Andy Hung97a893e2015-03-29 01:03:07 -07007108 // resampler accumulates, but we only have one source track
Andy Hungd330ee42015-04-20 13:23:41 -07007109 memset(mBuf, 0, frames * mBufFrameSize);
7110 frames = mResampler->resample((int32_t*)mBuf, frames, provider);
7111 // format convert to destination buffer
7112 convertResampler(dst, mBuf, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07007113 }
7114 return frames;
7115}
7116
7117status_t AudioFlinger::RecordThread::RecordBufferConverter::updateParameters(
7118 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
7119 uint32_t srcSampleRate,
7120 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
7121 uint32_t dstSampleRate)
7122{
7123 // quick evaluation if there is any change.
7124 if (mSrcFormat == srcFormat
7125 && mSrcChannelMask == srcChannelMask
7126 && mSrcSampleRate == srcSampleRate
7127 && mDstFormat == dstFormat
7128 && mDstChannelMask == dstChannelMask
7129 && mDstSampleRate == dstSampleRate) {
7130 return NO_ERROR;
7131 }
7132
Andy Hungdb4c0312015-05-06 08:46:52 -07007133 ALOGV("RecordBufferConverter updateParameters srcMask:%#x dstMask:%#x"
7134 " srcFormat:%#x dstFormat:%#x srcRate:%u dstRate:%u",
7135 srcChannelMask, dstChannelMask, srcFormat, dstFormat, srcSampleRate, dstSampleRate);
Andy Hung97a893e2015-03-29 01:03:07 -07007136 const bool valid =
7137 audio_is_input_channel(srcChannelMask)
7138 && audio_is_input_channel(dstChannelMask)
7139 && audio_is_valid_format(srcFormat) && audio_is_linear_pcm(srcFormat)
7140 && audio_is_valid_format(dstFormat) && audio_is_linear_pcm(dstFormat)
7141 && (srcSampleRate <= dstSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX)
7142 ; // no upsampling checks for now
7143 if (!valid) {
7144 return BAD_VALUE;
7145 }
7146
7147 mSrcFormat = srcFormat;
7148 mSrcChannelMask = srcChannelMask;
7149 mSrcSampleRate = srcSampleRate;
7150 mDstFormat = dstFormat;
7151 mDstChannelMask = dstChannelMask;
7152 mDstSampleRate = dstSampleRate;
7153
7154 // compute derived parameters
7155 mSrcChannelCount = audio_channel_count_from_in_mask(srcChannelMask);
7156 mDstChannelCount = audio_channel_count_from_in_mask(dstChannelMask);
7157 mDstFrameSize = mDstChannelCount * audio_bytes_per_sample(mDstFormat);
7158
Andy Hungd330ee42015-04-20 13:23:41 -07007159 // do we need to resample?
7160 delete mResampler;
7161 mResampler = NULL;
7162 if (mSrcSampleRate != mDstSampleRate) {
7163 mResampler = AudioResampler::create(AUDIO_FORMAT_PCM_FLOAT,
7164 mSrcChannelCount, mDstSampleRate);
7165 mResampler->setSampleRate(mSrcSampleRate);
7166 mResampler->setVolume(AudioMixer::UNITY_GAIN_FLOAT, AudioMixer::UNITY_GAIN_FLOAT);
7167 }
7168
7169 // are we running legacy channel conversion modes?
7170 mIsLegacyDownmix = (mSrcChannelMask == AUDIO_CHANNEL_IN_STEREO
7171 || mSrcChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK)
7172 && mDstChannelMask == AUDIO_CHANNEL_IN_MONO;
7173 mIsLegacyUpmix = mSrcChannelMask == AUDIO_CHANNEL_IN_MONO
7174 && (mDstChannelMask == AUDIO_CHANNEL_IN_STEREO
7175 || mDstChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK);
7176
7177 // do we need to process in float?
7178 mRequiresFloat = mResampler != NULL || mIsLegacyDownmix || mIsLegacyUpmix;
7179
7180 // do we need a staging buffer to convert for destination (we can still optimize this)?
7181 // we use mBufFrameSize > 0 to indicate both frame size as well as buffer necessity
7182 if (mResampler != NULL) {
7183 mBufFrameSize = max(mSrcChannelCount, FCC_2)
7184 * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
Andy Hunga97630b2015-07-22 23:27:24 -07007185 } else if (mIsLegacyUpmix || mIsLegacyDownmix) { // legacy modes always float
Andy Hungd330ee42015-04-20 13:23:41 -07007186 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
7187 } else if (mSrcChannelMask != mDstChannelMask && mDstFormat != mSrcFormat) {
Andy Hung97a893e2015-03-29 01:03:07 -07007188 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(mSrcFormat);
7189 } else {
7190 mBufFrameSize = 0;
7191 }
7192 mBufFrames = 0; // force the buffer to be resized.
7193
Andy Hungd330ee42015-04-20 13:23:41 -07007194 // do we need an input converter buffer provider to give us float?
7195 delete mInputConverterProvider;
7196 mInputConverterProvider = NULL;
7197 if (mRequiresFloat && mSrcFormat != AUDIO_FORMAT_PCM_FLOAT) {
7198 mInputConverterProvider = new ReformatBufferProvider(
7199 audio_channel_count_from_in_mask(mSrcChannelMask),
7200 mSrcFormat,
7201 AUDIO_FORMAT_PCM_FLOAT,
7202 256 /* provider buffer frame count */);
7203 }
7204
7205 // do we need a remixer to do channel mask conversion
7206 if (!mIsLegacyDownmix && !mIsLegacyUpmix && mSrcChannelMask != mDstChannelMask) {
7207 (void) memcpy_by_index_array_initialization_from_channel_mask(
7208 mIdxAry, ARRAY_SIZE(mIdxAry), mDstChannelMask, mSrcChannelMask);
Andy Hung97a893e2015-03-29 01:03:07 -07007209 }
7210 return NO_ERROR;
7211}
7212
Andy Hungd330ee42015-04-20 13:23:41 -07007213void AudioFlinger::RecordThread::RecordBufferConverter::convertNoResampler(
7214 void *dst, const void *src, size_t frames)
Andy Hung97a893e2015-03-29 01:03:07 -07007215{
Andy Hungd330ee42015-04-20 13:23:41 -07007216 // src is native type unless there is legacy upmix or downmix, whereupon it is float.
Andy Hung97a893e2015-03-29 01:03:07 -07007217 if (mBufFrameSize != 0 && mBufFrames < frames) {
7218 free(mBuf);
7219 mBufFrames = frames;
7220 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
7221 }
Andy Hungd330ee42015-04-20 13:23:41 -07007222 // do we need to do legacy upmix and downmix?
7223 if (mIsLegacyUpmix || mIsLegacyDownmix) {
Andy Hung97a893e2015-03-29 01:03:07 -07007224 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07007225 if (mIsLegacyUpmix) {
7226 upmix_to_stereo_float_from_mono_float((float *)dstBuf,
7227 (const float *)src, frames);
7228 } else /*mIsLegacyDownmix */ {
7229 downmix_to_mono_float_from_stereo_float((float *)dstBuf,
7230 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07007231 }
Andy Hungd330ee42015-04-20 13:23:41 -07007232 if (mBuf != NULL) {
7233 memcpy_by_audio_format(dst, mDstFormat, mBuf, AUDIO_FORMAT_PCM_FLOAT,
7234 frames * mDstChannelCount);
7235 }
7236 return;
7237 }
7238 // do we need to do channel mask conversion?
7239 if (mSrcChannelMask != mDstChannelMask) {
Andy Hung97a893e2015-03-29 01:03:07 -07007240 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07007241 memcpy_by_index_array(dstBuf, mDstChannelCount,
7242 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mSrcFormat), frames);
7243 if (dstBuf == dst) {
7244 return; // format is the same
7245 }
7246 }
7247 // convert to destination buffer
7248 const void *convertBuf = mBuf != NULL ? mBuf : src;
7249 memcpy_by_audio_format(dst, mDstFormat, convertBuf, mSrcFormat,
7250 frames * mDstChannelCount);
7251}
7252
7253void AudioFlinger::RecordThread::RecordBufferConverter::convertResampler(
7254 void *dst, /*not-a-const*/ void *src, size_t frames)
7255{
7256 // src buffer format is ALWAYS float when entering this routine
7257 if (mIsLegacyUpmix) {
7258 ; // mono to stereo already handled by resampler
7259 } else if (mIsLegacyDownmix
7260 || (mSrcChannelMask == mDstChannelMask && mSrcChannelCount == 1)) {
7261 // the resampler outputs stereo for mono input channel (a feature?)
7262 // must convert to mono
7263 downmix_to_mono_float_from_stereo_float((float *)src,
7264 (const float *)src, frames);
7265 } else if (mSrcChannelMask != mDstChannelMask) {
7266 // convert to mono channel again for channel mask conversion (could be skipped
7267 // with further optimization).
Andy Hung97a893e2015-03-29 01:03:07 -07007268 if (mSrcChannelCount == 1) {
Andy Hungd330ee42015-04-20 13:23:41 -07007269 downmix_to_mono_float_from_stereo_float((float *)src,
7270 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07007271 }
Andy Hungd330ee42015-04-20 13:23:41 -07007272 // convert to destination format (in place, OK as float is larger than other types)
7273 if (mDstFormat != AUDIO_FORMAT_PCM_FLOAT) {
7274 memcpy_by_audio_format(src, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
7275 frames * mSrcChannelCount);
7276 }
7277 // channel convert and save to dst
7278 memcpy_by_index_array(dst, mDstChannelCount,
7279 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mDstFormat), frames);
7280 return;
Andy Hung97a893e2015-03-29 01:03:07 -07007281 }
Andy Hungd330ee42015-04-20 13:23:41 -07007282 // convert to destination format and save to dst
7283 memcpy_by_audio_format(dst, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
7284 frames * mDstChannelCount);
Andy Hung97a893e2015-03-29 01:03:07 -07007285}
7286
Eric Laurent10351942014-05-08 18:49:52 -07007287bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
7288 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007289{
7290 bool reconfig = false;
7291
Eric Laurent10351942014-05-08 18:49:52 -07007292 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007293
Eric Laurent10351942014-05-08 18:49:52 -07007294 audio_format_t reqFormat = mFormat;
7295 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07007296 // 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 -07007297 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
7298
7299 AudioParameter param = AudioParameter(keyValuePair);
7300 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07007301
7302 // scope for AutoPark extends to end of method
7303 AutoPark<FastCapture> park(mFastCapture);
7304
Eric Laurent10351942014-05-08 18:49:52 -07007305 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
7306 // channel count change can be requested. Do we mandate the first client defines the
7307 // HAL sampling rate and channel count or do we allow changes on the fly?
7308 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
7309 samplingRate = value;
7310 reconfig = true;
7311 }
7312 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07007313 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07007314 status = BAD_VALUE;
7315 } else {
7316 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08007317 reconfig = true;
7318 }
Eric Laurent10351942014-05-08 18:49:52 -07007319 }
7320 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
7321 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07007322 if (!audio_is_input_channel(mask) ||
7323 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007324 status = BAD_VALUE;
7325 } else {
7326 channelMask = mask;
7327 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007328 }
Eric Laurent10351942014-05-08 18:49:52 -07007329 }
7330 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7331 // do not accept frame count changes if tracks are open as the track buffer
7332 // size depends on frame count and correct behavior would not be guaranteed
7333 // if frame count is changed after track creation
7334 if (mActiveTracks.size() > 0) {
7335 status = INVALID_OPERATION;
7336 } else {
7337 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007338 }
Eric Laurent10351942014-05-08 18:49:52 -07007339 }
7340 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7341 // forward device change to effects that have requested to be
7342 // aware of attached audio device.
7343 for (size_t i = 0; i < mEffectChains.size(); i++) {
7344 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08007345 }
Eric Laurent81784c32012-11-19 14:55:58 -08007346
Eric Laurent10351942014-05-08 18:49:52 -07007347 // store input device and output device but do not forward output device to audio HAL.
7348 // Note that status is ignored by the caller for output device
7349 // (see AudioFlinger::setParameters()
7350 if (audio_is_output_devices(value)) {
7351 mOutDevice = value;
7352 status = BAD_VALUE;
7353 } else {
7354 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07007355 if (value != AUDIO_DEVICE_NONE) {
7356 mPrevInDevice = value;
7357 }
Eric Laurent10351942014-05-08 18:49:52 -07007358 // disable AEC and NS if the device is a BT SCO headset supporting those
7359 // pre processings
7360 if (mTracks.size() > 0) {
7361 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7362 mAudioFlinger->btNrecIsOff();
7363 for (size_t i = 0; i < mTracks.size(); i++) {
7364 sp<RecordTrack> track = mTracks[i];
7365 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7366 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08007367 }
7368 }
7369 }
Eric Laurent10351942014-05-08 18:49:52 -07007370 }
7371 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
7372 mAudioSource != (audio_source_t)value) {
7373 // forward device change to effects that have requested to be
7374 // aware of attached audio device.
7375 for (size_t i = 0; i < mEffectChains.size(); i++) {
7376 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08007377 }
Eric Laurent10351942014-05-08 18:49:52 -07007378 mAudioSource = (audio_source_t)value;
7379 }
Glenn Kastene198c362013-08-13 09:13:36 -07007380
Eric Laurent10351942014-05-08 18:49:52 -07007381 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007382 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007383 if (status == INVALID_OPERATION) {
7384 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007385 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007386 }
7387 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007388 if (status == BAD_VALUE) {
7389 uint32_t sRate;
7390 audio_channel_mask_t channelMask;
7391 audio_format_t format;
7392 if (mInput->stream->getAudioProperties(&sRate, &channelMask, &format) == OK &&
7393 audio_is_linear_pcm(format) && audio_is_linear_pcm(reqFormat) &&
7394 sRate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
7395 audio_channel_count_from_in_mask(channelMask) <= FCC_8) {
7396 status = NO_ERROR;
7397 }
Eric Laurent81784c32012-11-19 14:55:58 -08007398 }
Eric Laurent10351942014-05-08 18:49:52 -07007399 if (status == NO_ERROR) {
7400 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007401 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08007402 }
7403 }
Eric Laurent81784c32012-11-19 14:55:58 -08007404 }
Eric Laurent10351942014-05-08 18:49:52 -07007405
Eric Laurent81784c32012-11-19 14:55:58 -08007406 return reconfig;
7407}
7408
7409String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
7410{
Eric Laurent81784c32012-11-19 14:55:58 -08007411 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007412 if (initCheck() == NO_ERROR) {
7413 String8 out_s8;
7414 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
7415 return out_s8;
7416 }
Eric Laurent81784c32012-11-19 14:55:58 -08007417 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007418 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08007419}
7420
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007421void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007422 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7423
7424 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08007425
7426 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007427 case AUDIO_INPUT_OPENED:
7428 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07007429 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07007430 desc->mChannelMask = mChannelMask;
7431 desc->mSamplingRate = mSampleRate;
7432 desc->mFormat = mFormat;
7433 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07007434 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07007435 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007436 break;
7437
Eric Laurent73e26b62015-04-27 16:55:58 -07007438 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08007439 default:
7440 break;
7441 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007442 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08007443}
7444
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007445void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007446{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007447 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
7448 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hunge5412692014-05-16 11:25:07 -07007449 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007450 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_8, "HAL channel count %d > %d", mChannelCount, FCC_8);
Andy Hung463be252014-07-10 16:56:07 -07007451 mFormat = mHALFormat;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007452 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
7453 result = mInput->stream->getFrameSize(&mFrameSize);
7454 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
7455 result = mInput->stream->getBufferSize(&mBufferSize);
7456 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08007457 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007458 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08007459 // 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 -07007460 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08007461 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007462 // A larger value should allow more old data to be read after a track calls start(),
7463 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07007464 //
7465 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08007466 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07007467 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07007468 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07007469 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007470
7471 // TODO optimize audio capture buffer sizes ...
7472 // Here we calculate the size of the sliding buffer used as a source
7473 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
7474 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
7475 // be better to have it derived from the pipe depth in the long term.
7476 // The current value is higher than necessary. However it should not add to latency.
7477
Glenn Kasten85948432013-08-19 12:09:05 -07007478 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Glenn Kasten1b291842016-07-18 14:55:21 -07007479 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
7480 (void)posix_memalign(&mRsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
7481 memset(mRsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize); // if posix_memalign fails, will segv here.
Eric Laurent81784c32012-11-19 14:55:58 -08007482
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007483 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
7484 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08007485}
7486
Glenn Kasten5f972c02014-01-13 09:59:31 -08007487uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08007488{
7489 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007490 uint32_t result;
7491 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
7492 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08007493 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007494 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007495}
7496
Eric Laurent4c415062016-06-17 16:14:16 -07007497// hasAudioSession_l() must be called with ThreadBase::mLock held
7498uint32_t AudioFlinger::RecordThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08007499{
Eric Laurent81784c32012-11-19 14:55:58 -08007500 uint32_t result = 0;
7501 if (getEffectChain_l(sessionId) != 0) {
7502 result = EFFECT_SESSION;
7503 }
7504
7505 for (size_t i = 0; i < mTracks.size(); ++i) {
7506 if (sessionId == mTracks[i]->sessionId()) {
7507 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07007508 if (mTracks[i]->isFastTrack()) {
7509 result |= FAST_SESSION;
7510 }
Eric Laurent81784c32012-11-19 14:55:58 -08007511 break;
7512 }
7513 }
7514
7515 return result;
7516}
7517
Glenn Kastend848eb42016-03-08 13:42:11 -08007518KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08007519{
Glenn Kastend848eb42016-03-08 13:42:11 -08007520 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08007521 Mutex::Autolock _l(mLock);
7522 for (size_t j = 0; j < mTracks.size(); ++j) {
7523 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08007524 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08007525 if (ids.indexOfKey(sessionId) < 0) {
7526 ids.add(sessionId, true);
7527 }
7528 }
7529 return ids;
7530}
7531
7532AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7533{
7534 Mutex::Autolock _l(mLock);
7535 AudioStreamIn *input = mInput;
7536 mInput = NULL;
7537 return input;
7538}
7539
7540// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007541sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08007542{
7543 if (mInput == NULL) {
7544 return NULL;
7545 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007546 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08007547}
7548
7549status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7550{
7551 // only one chain per input thread
7552 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07007553 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08007554 return INVALID_OPERATION;
7555 }
7556 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07007557 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08007558 chain->setInBuffer(NULL);
7559 chain->setOutBuffer(NULL);
7560
7561 checkSuspendOnAddEffectChain_l(chain);
7562
Eric Laurent1b928682014-10-02 19:41:47 -07007563 // make sure enabled pre processing effects state is communicated to the HAL as we
7564 // just moved them to a new input stream.
7565 chain->syncHalEffectsState();
7566
Eric Laurent81784c32012-11-19 14:55:58 -08007567 mEffectChains.add(chain);
7568
7569 return NO_ERROR;
7570}
7571
7572size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7573{
7574 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7575 ALOGW_IF(mEffectChains.size() != 1,
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007576 "removeEffectChain_l() %p invalid chain size %zu on thread %p",
Eric Laurent81784c32012-11-19 14:55:58 -08007577 chain.get(), mEffectChains.size(), this);
7578 if (mEffectChains.size() == 1) {
7579 mEffectChains.removeAt(0);
7580 }
7581 return 0;
7582}
7583
Eric Laurent1c333e22014-05-20 10:48:17 -07007584status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7585 audio_patch_handle_t *handle)
7586{
7587 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007588
7589 // store new device and send to effects
7590 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07007591 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07007592 for (size_t i = 0; i < mEffectChains.size(); i++) {
7593 mEffectChains[i]->setDevice_l(mInDevice);
7594 }
7595
7596 // disable AEC and NS if the device is a BT SCO headset supporting those
7597 // pre processings
7598 if (mTracks.size() > 0) {
7599 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7600 mAudioFlinger->btNrecIsOff();
7601 for (size_t i = 0; i < mTracks.size(); i++) {
7602 sp<RecordTrack> track = mTracks[i];
7603 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7604 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
7605 }
7606 }
7607
7608 // store new source and send to effects
7609 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7610 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07007611 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07007612 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07007613 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007614 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007615
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007616 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007617 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7618 status = hwDevice->createAudioPatch(patch->num_sources,
7619 patch->sources,
7620 patch->num_sinks,
7621 patch->sinks,
7622 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007623 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007624 char *address;
7625 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7626 address = audio_device_address_to_parameter(
7627 patch->sources[0].ext.device.type,
7628 patch->sources[0].ext.device.address);
7629 } else {
7630 address = (char *)calloc(1, 1);
7631 }
7632 AudioParameter param = AudioParameter(String8(address));
7633 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007634 param.addInt(String8(AudioParameter::keyRouting),
Eric Laurent054d9d32015-04-24 08:48:48 -07007635 (int)patch->sources[0].ext.device.type);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007636 param.addInt(String8(AudioParameter::keyInputSource),
Eric Laurent054d9d32015-04-24 08:48:48 -07007637 (int)patch->sinks[0].ext.mix.usecase.source);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007638 status = mInput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07007639 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07007640 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007641
Eric Laurente8726fe2015-06-26 09:39:24 -07007642 if (mInDevice != mPrevInDevice) {
7643 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7644 mPrevInDevice = mInDevice;
7645 }
Eric Laurent296fb132015-05-01 11:38:42 -07007646
Eric Laurent1c333e22014-05-20 10:48:17 -07007647 return status;
7648}
7649
7650status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7651{
7652 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007653
7654 mInDevice = AUDIO_DEVICE_NONE;
7655
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007656 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007657 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7658 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007659 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007660 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07007661 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007662 status = mInput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07007663 }
7664 return status;
7665}
7666
Eric Laurent83b88082014-06-20 18:31:16 -07007667void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
7668{
7669 Mutex::Autolock _l(mLock);
7670 mTracks.add(record);
7671}
7672
7673void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
7674{
7675 Mutex::Autolock _l(mLock);
7676 destroyTrack_l(record);
7677}
7678
7679void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
7680{
7681 ThreadBase::getAudioPortConfig(config);
7682 config->role = AUDIO_PORT_ROLE_SINK;
7683 config->ext.mix.hw_module = mInput->audioHwDev->handle();
7684 config->ext.mix.usecase.source = mAudioSource;
7685}
Eric Laurent1c333e22014-05-20 10:48:17 -07007686
Glenn Kasten63238ef2015-03-02 15:50:29 -08007687} // namespace android