blob: 737d21ee873671b053ae6faa52d6bd8ba94e54c5 [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)),
Andy Hung2f366df2016-10-31 14:01:16 -0700650 mSystemReady(systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -0800651{
Eric Laurent296fb132015-05-01 11:38:42 -0700652 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800653}
654
655AudioFlinger::ThreadBase::~ThreadBase()
656{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700657 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700658 mConfigEvents.clear();
659
Eric Laurent81784c32012-11-19 14:55:58 -0800660 // do not lock the mutex in destructor
661 releaseWakeLock_l();
662 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800663 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800664 binder->unlinkToDeath(mDeathRecipient);
665 }
666}
667
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700668status_t AudioFlinger::ThreadBase::readyToRun()
669{
670 status_t status = initCheck();
671 if (status == NO_ERROR) {
672 ALOGI("AudioFlinger's thread %p ready to run", this);
673 } else {
674 ALOGE("No working audio driver found.");
675 }
676 return status;
677}
678
Eric Laurent81784c32012-11-19 14:55:58 -0800679void AudioFlinger::ThreadBase::exit()
680{
681 ALOGV("ThreadBase::exit");
682 // do any cleanup required for exit to succeed
683 preExit();
684 {
685 // This lock prevents the following race in thread (uniprocessor for illustration):
686 // if (!exitPending()) {
687 // // context switch from here to exit()
688 // // exit() calls requestExit(), what exitPending() observes
689 // // exit() calls signal(), which is dropped since no waiters
690 // // context switch back from exit() to here
691 // mWaitWorkCV.wait(...);
692 // // now thread is hung
693 // }
694 AutoMutex lock(mLock);
695 requestExit();
696 mWaitWorkCV.broadcast();
697 }
698 // When Thread::requestExitAndWait is made virtual and this method is renamed to
699 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
700 requestExitAndWait();
701}
702
703status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
704{
Eric Laurent81784c32012-11-19 14:55:58 -0800705 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
706 Mutex::Autolock _l(mLock);
707
Eric Laurent10351942014-05-08 18:49:52 -0700708 return sendSetParameterConfigEvent_l(keyValuePairs);
709}
710
711// sendConfigEvent_l() must be called with ThreadBase::mLock held
712// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
713status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
714{
715 status_t status = NO_ERROR;
716
Eric Laurent72e3f392015-05-20 14:43:50 -0700717 if (event->mRequiresSystemReady && !mSystemReady) {
718 event->mWaitStatus = false;
719 mPendingConfigEvents.add(event);
720 return status;
721 }
Eric Laurent10351942014-05-08 18:49:52 -0700722 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700723 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800724 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700725 mLock.unlock();
726 {
727 Mutex::Autolock _l(event->mLock);
728 while (event->mWaitStatus) {
729 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
730 event->mStatus = TIMED_OUT;
731 event->mWaitStatus = false;
732 }
733 }
734 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800735 }
Eric Laurent10351942014-05-08 18:49:52 -0700736 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800737 return status;
738}
739
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700740void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800741{
742 Mutex::Autolock _l(mLock);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700743 sendIoConfigEvent_l(event, pid);
Eric Laurent81784c32012-11-19 14:55:58 -0800744}
745
746// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700747void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800748{
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700749 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid);
Eric Laurent10351942014-05-08 18:49:52 -0700750 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800751}
752
Eric Laurent72e3f392015-05-20 14:43:50 -0700753void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio)
754{
755 Mutex::Autolock _l(mLock);
756 sendPrioConfigEvent_l(pid, tid, prio);
757}
758
Eric Laurent81784c32012-11-19 14:55:58 -0800759// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
760void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
761{
Eric Laurent10351942014-05-08 18:49:52 -0700762 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio);
763 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800764}
765
Eric Laurent10351942014-05-08 18:49:52 -0700766// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
767status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800768{
Andy Hung2ddee192015-12-18 17:34:44 -0800769 sp<ConfigEvent> configEvent;
770 AudioParameter param(keyValuePair);
771 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700772 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800773 setMasterMono_l(value != 0);
774 if (param.size() == 1) {
775 return NO_ERROR; // should be a solo parameter - we don't pass down
776 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700777 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800778 configEvent = new SetParameterConfigEvent(param.toString());
779 } else {
780 configEvent = new SetParameterConfigEvent(keyValuePair);
781 }
Eric Laurent10351942014-05-08 18:49:52 -0700782 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700783}
784
Eric Laurent1c333e22014-05-20 10:48:17 -0700785status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
786 const struct audio_patch *patch,
787 audio_patch_handle_t *handle)
788{
789 Mutex::Autolock _l(mLock);
790 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
791 status_t status = sendConfigEvent_l(configEvent);
792 if (status == NO_ERROR) {
793 CreateAudioPatchConfigEventData *data =
794 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
795 *handle = data->mHandle;
796 }
797 return status;
798}
799
800status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
801 const audio_patch_handle_t handle)
802{
803 Mutex::Autolock _l(mLock);
804 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
805 return sendConfigEvent_l(configEvent);
806}
807
808
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700809// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700810void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700811{
Eric Laurent10351942014-05-08 18:49:52 -0700812 bool configChanged = false;
813
Eric Laurent81784c32012-11-19 14:55:58 -0800814 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700815 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700816 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800817 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700818 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700819 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700820 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
821 // FIXME Need to understand why this has to be done asynchronously
822 int err = requestPriority(data->mPid, data->mTid, data->mPrio,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700823 true /*asynchronous*/);
824 if (err != 0) {
825 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700826 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700827 }
828 } break;
829 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700830 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700831 ioConfigChanged(data->mEvent, data->mPid);
Eric Laurent10351942014-05-08 18:49:52 -0700832 } break;
833 case CFG_EVENT_SET_PARAMETER: {
834 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
835 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
836 configChanged = true;
Glenn Kastend5418eb2013-08-14 13:11:06 -0700837 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700838 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700839 case CFG_EVENT_CREATE_AUDIO_PATCH: {
840 CreateAudioPatchConfigEventData *data =
841 (CreateAudioPatchConfigEventData *)event->mData.get();
842 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
843 } break;
844 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
845 ReleaseAudioPatchConfigEventData *data =
846 (ReleaseAudioPatchConfigEventData *)event->mData.get();
847 event->mStatus = releaseAudioPatch_l(data->mHandle);
848 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700849 default:
Eric Laurent10351942014-05-08 18:49:52 -0700850 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700851 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800852 }
Eric Laurent10351942014-05-08 18:49:52 -0700853 {
854 Mutex::Autolock _l(event->mLock);
855 if (event->mWaitStatus) {
856 event->mWaitStatus = false;
857 event->mCond.signal();
858 }
859 }
860 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
861 }
862
863 if (configChanged) {
864 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800865 }
Eric Laurent81784c32012-11-19 14:55:58 -0800866}
867
Marco Nelissenb2208842014-02-07 14:00:50 -0800868String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
869 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700870 const audio_channel_representation_t representation =
871 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700872
873 switch (representation) {
874 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
875 if (output) {
876 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
877 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
878 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
879 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
880 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
881 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
882 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
883 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
884 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
885 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
886 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
887 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
888 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
889 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
890 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
891 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
892 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
893 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
894 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
895 } else {
896 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
897 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
898 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
899 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
900 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
901 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
902 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
903 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
904 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
905 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
906 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
907 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
908 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
909 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
910 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
911 }
912 const int len = s.length();
913 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -0700914 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -0700915 s.unlockBuffer(len - 2); // remove trailing ", "
916 }
917 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800918 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700919 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
920 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
921 return s;
922 default:
923 s.appendFormat("unknown mask, representation:%d bits:%#x",
924 representation, audio_channel_mask_get_bits(mask));
925 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800926 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800927}
928
Glenn Kasten0f11b512014-01-31 16:18:54 -0800929void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800930{
931 const size_t SIZE = 256;
932 char buffer[SIZE];
933 String8 result;
934
935 bool locked = AudioFlinger::dumpTryLock(mLock);
936 if (!locked) {
Glenn Kasten97b7b752014-09-28 13:04:24 -0700937 dprintf(fd, "thread %p may be deadlocked\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -0800938 }
939
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800940 dprintf(fd, " Thread name: %s\n", mThreadName);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700941 dprintf(fd, " I/O handle: %d\n", mId);
942 dprintf(fd, " TID: %d\n", getTid());
943 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700944 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700945 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700946 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat));
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700947 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700948 dprintf(fd, " Channel count: %u\n", mChannelCount);
949 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800950 channelMaskToString(mChannelMask, mType != RECORD).string());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700951 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat));
952 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700953 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800954 size_t numConfig = mConfigEvents.size();
955 if (numConfig) {
956 for (size_t i = 0; i < numConfig; i++) {
957 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700958 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800959 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700960 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800961 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700962 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800963 }
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800964 dprintf(fd, " Output device: %#x (%s)\n", mOutDevice, devicesToString(mOutDevice).string());
965 dprintf(fd, " Input device: %#x (%s)\n", mInDevice, devicesToString(mInDevice).string());
966 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, sourceToString(mAudioSource));
Eric Laurent81784c32012-11-19 14:55:58 -0800967
968 if (locked) {
969 mLock.unlock();
970 }
971}
972
973void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
974{
975 const size_t SIZE = 256;
976 char buffer[SIZE];
977 String8 result;
978
Marco Nelissenb2208842014-02-07 14:00:50 -0800979 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000980 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800981 write(fd, buffer, strlen(buffer));
982
Marco Nelissenb2208842014-02-07 14:00:50 -0800983 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800984 sp<EffectChain> chain = mEffectChains[i];
985 if (chain != 0) {
986 chain->dump(fd, args);
987 }
988 }
989}
990
Andy Hung2f366df2016-10-31 14:01:16 -0700991void AudioFlinger::ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -0800992{
993 Mutex::Autolock _l(mLock);
Andy Hung2f366df2016-10-31 14:01:16 -0700994 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800995}
996
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100997String16 AudioFlinger::ThreadBase::getWakeLockTag()
998{
999 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -08001000 case MIXER:
1001 return String16("AudioMix");
1002 case DIRECT:
1003 return String16("AudioDirectOut");
1004 case DUPLICATING:
1005 return String16("AudioDup");
1006 case RECORD:
1007 return String16("AudioIn");
1008 case OFFLOAD:
1009 return String16("AudioOffload");
1010 default:
1011 ALOG_ASSERT(false);
1012 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001013 }
1014}
1015
Andy Hung2f366df2016-10-31 14:01:16 -07001016void AudioFlinger::ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001017{
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001018 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001019 if (mPowerManager != 0) {
1020 sp<IBinder> binder = new BBinder();
Andy Hung2f366df2016-10-31 14:01:16 -07001021 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
1022 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -07001023 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001024 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -07001025 String16("audioserver"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -07001026 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -08001027 if (status == NO_ERROR) {
1028 mWakeLockToken = binder;
1029 }
Glenn Kastend7dca052015-03-05 16:05:54 -08001030 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -08001031 }
Wei Jia3f273d12015-11-24 09:06:49 -08001032
Andy Hung3f0c9022016-01-15 17:49:46 -08001033 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -08001034 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
1035 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -08001036}
1037
1038void AudioFlinger::ThreadBase::releaseWakeLock()
1039{
1040 Mutex::Autolock _l(mLock);
1041 releaseWakeLock_l();
1042}
1043
1044void AudioFlinger::ThreadBase::releaseWakeLock_l()
1045{
Andy Hung3f0c9022016-01-15 17:49:46 -08001046 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -08001047 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001048 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001049 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -07001050 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
1051 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -08001052 }
1053 mWakeLockToken.clear();
1054 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001055}
1056
1057void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -07001058 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001059 // use checkService() to avoid blocking if power service is not up yet
1060 sp<IBinder> binder =
1061 defaultServiceManager()->checkService(String16("power"));
1062 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001063 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001064 } else {
1065 mPowerManager = interface_cast<IPowerManager>(binder);
1066 binder->linkToDeath(mDeathRecipient);
1067 }
1068 }
1069}
1070
1071void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<int> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001072 getPowerManager_l();
Andy Hung2f366df2016-10-31 14:01:16 -07001073
1074#if !LOG_NDEBUG
1075 std::stringstream s;
1076 for (int uid : uids) {
1077 s << uid << " ";
1078 }
1079 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
1080#endif
1081
Andy Hung438e7572015-12-14 15:51:17 -08001082 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
1083 if (mSystemReady) {
1084 ALOGE("no wake lock to update, but system ready!");
1085 } else {
1086 ALOGW("no wake lock to update, system not ready yet");
1087 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001088 return;
1089 }
1090 if (mPowerManager != 0) {
1091 sp<IBinder> binder = new BBinder();
1092 status_t status;
Glenn Kasten3abc2de2014-09-05 16:45:52 -07001093 status = mPowerManager->updateWakeLockUids(mWakeLockToken, uids.size(), uids.array(),
1094 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent4d231dc2016-03-11 18:38:23 -08001095 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001096 }
1097}
1098
Eric Laurent81784c32012-11-19 14:55:58 -08001099void AudioFlinger::ThreadBase::clearPowerManager()
1100{
1101 Mutex::Autolock _l(mLock);
1102 releaseWakeLock_l();
1103 mPowerManager.clear();
1104}
1105
Glenn Kasten0f11b512014-01-31 16:18:54 -08001106void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001107{
1108 sp<ThreadBase> thread = mThread.promote();
1109 if (thread != 0) {
1110 thread->clearPowerManager();
1111 }
1112 ALOGW("power manager service died !!!");
1113}
1114
1115void AudioFlinger::ThreadBase::setEffectSuspended(
Glenn Kastend848eb42016-03-08 13:42:11 -08001116 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001117{
1118 Mutex::Autolock _l(mLock);
1119 setEffectSuspended_l(type, suspend, sessionId);
1120}
1121
1122void AudioFlinger::ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001123 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001124{
1125 sp<EffectChain> chain = getEffectChain_l(sessionId);
1126 if (chain != 0) {
1127 if (type != NULL) {
1128 chain->setEffectSuspended_l(type, suspend);
1129 } else {
1130 chain->setEffectSuspendedAll_l(suspend);
1131 }
1132 }
1133
1134 updateSuspendedSessions_l(type, suspend, sessionId);
1135}
1136
1137void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1138{
1139 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1140 if (index < 0) {
1141 return;
1142 }
1143
1144 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1145 mSuspendedSessions.valueAt(index);
1146
1147 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001148 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001149 for (int j = 0; j < desc->mRefCount; j++) {
1150 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1151 chain->setEffectSuspendedAll_l(true);
1152 } else {
1153 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1154 desc->mType.timeLow);
1155 chain->setEffectSuspended_l(&desc->mType, true);
1156 }
1157 }
1158 }
1159}
1160
1161void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1162 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001163 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001164{
1165 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1166
1167 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1168
1169 if (suspend) {
1170 if (index >= 0) {
1171 sessionEffects = mSuspendedSessions.valueAt(index);
1172 } else {
1173 mSuspendedSessions.add(sessionId, sessionEffects);
1174 }
1175 } else {
1176 if (index < 0) {
1177 return;
1178 }
1179 sessionEffects = mSuspendedSessions.valueAt(index);
1180 }
1181
1182
1183 int key = EffectChain::kKeyForSuspendAll;
1184 if (type != NULL) {
1185 key = type->timeLow;
1186 }
1187 index = sessionEffects.indexOfKey(key);
1188
1189 sp<SuspendedSessionDesc> desc;
1190 if (suspend) {
1191 if (index >= 0) {
1192 desc = sessionEffects.valueAt(index);
1193 } else {
1194 desc = new SuspendedSessionDesc();
1195 if (type != NULL) {
1196 desc->mType = *type;
1197 }
1198 sessionEffects.add(key, desc);
1199 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1200 }
1201 desc->mRefCount++;
1202 } else {
1203 if (index < 0) {
1204 return;
1205 }
1206 desc = sessionEffects.valueAt(index);
1207 if (--desc->mRefCount == 0) {
1208 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1209 sessionEffects.removeItemsAt(index);
1210 if (sessionEffects.isEmpty()) {
1211 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1212 sessionId);
1213 mSuspendedSessions.removeItem(sessionId);
1214 }
1215 }
1216 }
1217 if (!sessionEffects.isEmpty()) {
1218 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1219 }
1220}
1221
1222void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1223 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001224 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001225{
1226 Mutex::Autolock _l(mLock);
1227 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1228}
1229
1230void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1231 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001232 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001233{
1234 if (mType != RECORD) {
1235 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1236 // another session. This gives the priority to well behaved effect control panels
1237 // and applications not using global effects.
1238 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1239 // global effects
1240 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1241 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1242 }
1243 }
1244
1245 sp<EffectChain> chain = getEffectChain_l(sessionId);
1246 if (chain != 0) {
1247 chain->checkSuspendOnEffectEnabled(effect, enabled);
1248 }
1249}
1250
Eric Laurent4c415062016-06-17 16:14:16 -07001251// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1252status_t AudioFlinger::RecordThread::checkEffectCompatibility_l(
1253 const effect_descriptor_t *desc, audio_session_t sessionId)
1254{
1255 // No global effect sessions on record threads
1256 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1257 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1258 desc->name, mThreadName);
1259 return BAD_VALUE;
1260 }
1261 // only pre processing effects on record thread
1262 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1263 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1264 desc->name, mThreadName);
1265 return BAD_VALUE;
1266 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001267
1268 // always allow effects without processing load or latency
1269 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1270 return NO_ERROR;
1271 }
1272
Eric Laurent4c415062016-06-17 16:14:16 -07001273 audio_input_flags_t flags = mInput->flags;
1274 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1275 if (flags & AUDIO_INPUT_FLAG_RAW) {
1276 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1277 desc->name, mThreadName);
1278 return BAD_VALUE;
1279 }
1280 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1281 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1282 desc->name, mThreadName);
1283 return BAD_VALUE;
1284 }
1285 }
1286 return NO_ERROR;
1287}
1288
1289// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1290status_t AudioFlinger::PlaybackThread::checkEffectCompatibility_l(
1291 const effect_descriptor_t *desc, audio_session_t sessionId)
1292{
1293 // no preprocessing on playback threads
1294 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
1295 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback"
1296 " thread %s", desc->name, mThreadName);
1297 return BAD_VALUE;
1298 }
1299
1300 switch (mType) {
1301 case MIXER: {
1302 // Reject any effect on mixer multichannel sinks.
1303 // TODO: fix both format and multichannel issues with effects.
1304 if (mChannelCount != FCC_2) {
1305 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d) on MIXER"
1306 " thread %s", desc->name, mChannelCount, mThreadName);
1307 return BAD_VALUE;
1308 }
1309 audio_output_flags_t flags = mOutput->flags;
1310 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1311 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1312 // global effects are applied only to non fast tracks if they are SW
1313 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1314 break;
1315 }
1316 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1317 // only post processing on output stage session
1318 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1319 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1320 " on output stage session", desc->name);
1321 return BAD_VALUE;
1322 }
1323 } else {
1324 // no restriction on effects applied on non fast tracks
1325 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1326 break;
1327 }
1328 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001329
1330 // always allow effects without processing load or latency
1331 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1332 break;
1333 }
Eric Laurent4c415062016-06-17 16:14:16 -07001334 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
1335 ALOGW("checkEffectCompatibility_l(): effect %s on playback thread in raw mode",
1336 desc->name);
1337 return BAD_VALUE;
1338 }
1339 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1340 ALOGW("checkEffectCompatibility_l(): non HW effect %s on playback thread"
1341 " in fast mode", desc->name);
1342 return BAD_VALUE;
1343 }
1344 }
1345 } break;
1346 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001347 // nothing actionable on offload threads, if the effect:
1348 // - is offloadable: the effect can be created
1349 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1350 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001351 break;
1352 case DIRECT:
1353 // Reject any effect on Direct output threads for now, since the format of
1354 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1355 ALOGW("checkEffectCompatibility_l(): effect %s on DIRECT output thread %s",
1356 desc->name, mThreadName);
1357 return BAD_VALUE;
1358 case DUPLICATING:
1359 // Reject any effect on mixer multichannel sinks.
1360 // TODO: fix both format and multichannel issues with effects.
1361 if (mChannelCount != FCC_2) {
1362 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d)"
1363 " on DUPLICATING thread %s", desc->name, mChannelCount, mThreadName);
1364 return BAD_VALUE;
1365 }
1366 if ((sessionId == AUDIO_SESSION_OUTPUT_STAGE) || (sessionId == AUDIO_SESSION_OUTPUT_MIX)) {
1367 ALOGW("checkEffectCompatibility_l(): global effect %s on DUPLICATING"
1368 " thread %s", desc->name, mThreadName);
1369 return BAD_VALUE;
1370 }
1371 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
1372 ALOGW("checkEffectCompatibility_l(): post processing effect %s on"
1373 " DUPLICATING thread %s", desc->name, mThreadName);
1374 return BAD_VALUE;
1375 }
1376 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1377 ALOGW("checkEffectCompatibility_l(): HW tunneled effect %s on"
1378 " DUPLICATING thread %s", desc->name, mThreadName);
1379 return BAD_VALUE;
1380 }
1381 break;
1382 default:
1383 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1384 }
1385
1386 return NO_ERROR;
1387}
1388
Eric Laurent81784c32012-11-19 14:55:58 -08001389// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1390sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1391 const sp<AudioFlinger::Client>& client,
1392 const sp<IEffectClient>& effectClient,
1393 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001394 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001395 effect_descriptor_t *desc,
1396 int *enabled,
Glenn Kasten9156ef32013-08-06 15:39:08 -07001397 status_t *status)
Eric Laurent81784c32012-11-19 14:55:58 -08001398{
1399 sp<EffectModule> effect;
1400 sp<EffectHandle> handle;
1401 status_t lStatus;
1402 sp<EffectChain> chain;
1403 bool chainCreated = false;
1404 bool effectCreated = false;
1405 bool effectRegistered = false;
1406
1407 lStatus = initCheck();
1408 if (lStatus != NO_ERROR) {
1409 ALOGW("createEffect_l() Audio driver not initialized.");
1410 goto Exit;
1411 }
1412
Eric Laurent81784c32012-11-19 14:55:58 -08001413 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1414
1415 { // scope for mLock
1416 Mutex::Autolock _l(mLock);
1417
Eric Laurent4c415062016-06-17 16:14:16 -07001418 lStatus = checkEffectCompatibility_l(desc, sessionId);
1419 if (lStatus != NO_ERROR) {
1420 goto Exit;
1421 }
1422
Eric Laurent81784c32012-11-19 14:55:58 -08001423 // check for existing effect chain with the requested audio session
1424 chain = getEffectChain_l(sessionId);
1425 if (chain == 0) {
1426 // create a new chain for this session
1427 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1428 chain = new EffectChain(this, sessionId);
1429 addEffectChain_l(chain);
1430 chain->setStrategy(getStrategyForSession_l(sessionId));
1431 chainCreated = true;
1432 } else {
1433 effect = chain->getEffectFromDesc_l(desc);
1434 }
1435
1436 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1437
1438 if (effect == 0) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08001439 audio_unique_id_t id = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001440 // Check CPU and memory usage
1441 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
1442 if (lStatus != NO_ERROR) {
1443 goto Exit;
1444 }
1445 effectRegistered = true;
1446 // create a new effect module if none present in the chain
1447 effect = new EffectModule(this, chain, desc, id, sessionId);
1448 lStatus = effect->status();
1449 if (lStatus != NO_ERROR) {
1450 goto Exit;
1451 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001452 effect->setOffloaded(mType == OFFLOAD, mId);
1453
Eric Laurent81784c32012-11-19 14:55:58 -08001454 lStatus = chain->addEffect_l(effect);
1455 if (lStatus != NO_ERROR) {
1456 goto Exit;
1457 }
1458 effectCreated = true;
1459
1460 effect->setDevice(mOutDevice);
1461 effect->setDevice(mInDevice);
1462 effect->setMode(mAudioFlinger->getMode());
1463 effect->setAudioSource(mAudioSource);
1464 }
1465 // create effect handle and connect it to effect module
1466 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001467 lStatus = handle->initCheck();
1468 if (lStatus == OK) {
1469 lStatus = effect->addHandle(handle.get());
1470 }
Eric Laurent81784c32012-11-19 14:55:58 -08001471 if (enabled != NULL) {
1472 *enabled = (int)effect->isEnabled();
1473 }
1474 }
1475
1476Exit:
1477 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1478 Mutex::Autolock _l(mLock);
1479 if (effectCreated) {
1480 chain->removeEffect_l(effect);
1481 }
1482 if (effectRegistered) {
1483 AudioSystem::unregisterEffect(effect->id());
1484 }
1485 if (chainCreated) {
1486 removeEffectChain_l(chain);
1487 }
1488 handle.clear();
1489 }
1490
Glenn Kasten9156ef32013-08-06 15:39:08 -07001491 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001492 return handle;
1493}
1494
Glenn Kastend848eb42016-03-08 13:42:11 -08001495sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1496 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001497{
1498 Mutex::Autolock _l(mLock);
1499 return getEffect_l(sessionId, effectId);
1500}
1501
Glenn Kastend848eb42016-03-08 13:42:11 -08001502sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1503 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001504{
1505 sp<EffectChain> chain = getEffectChain_l(sessionId);
1506 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1507}
1508
1509// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1510// PlaybackThread::mLock held
1511status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1512{
1513 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001514 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001515 sp<EffectChain> chain = getEffectChain_l(sessionId);
1516 bool chainCreated = false;
1517
Eric Laurent5baf2af2013-09-12 17:37:00 -07001518 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1519 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1520 this, effect->desc().name, effect->desc().flags);
1521
Eric Laurent81784c32012-11-19 14:55:58 -08001522 if (chain == 0) {
1523 // create a new chain for this session
1524 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1525 chain = new EffectChain(this, sessionId);
1526 addEffectChain_l(chain);
1527 chain->setStrategy(getStrategyForSession_l(sessionId));
1528 chainCreated = true;
1529 }
1530 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1531
1532 if (chain->getEffectFromId_l(effect->id()) != 0) {
1533 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1534 this, effect->desc().name, chain.get());
1535 return BAD_VALUE;
1536 }
1537
Eric Laurent5baf2af2013-09-12 17:37:00 -07001538 effect->setOffloaded(mType == OFFLOAD, mId);
1539
Eric Laurent81784c32012-11-19 14:55:58 -08001540 status_t status = chain->addEffect_l(effect);
1541 if (status != NO_ERROR) {
1542 if (chainCreated) {
1543 removeEffectChain_l(chain);
1544 }
1545 return status;
1546 }
1547
1548 effect->setDevice(mOutDevice);
1549 effect->setDevice(mInDevice);
1550 effect->setMode(mAudioFlinger->getMode());
1551 effect->setAudioSource(mAudioSource);
1552 return NO_ERROR;
1553}
1554
1555void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
1556
1557 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
1558 effect_descriptor_t desc = effect->desc();
1559 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1560 detachAuxEffect_l(effect->id());
1561 }
1562
1563 sp<EffectChain> chain = effect->chain().promote();
1564 if (chain != 0) {
1565 // remove effect chain if removing last effect
1566 if (chain->removeEffect_l(effect) == 0) {
1567 removeEffectChain_l(chain);
1568 }
1569 } else {
1570 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1571 }
1572}
1573
1574void AudioFlinger::ThreadBase::lockEffectChains_l(
1575 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1576{
1577 effectChains = mEffectChains;
1578 for (size_t i = 0; i < mEffectChains.size(); i++) {
1579 mEffectChains[i]->lock();
1580 }
1581}
1582
1583void AudioFlinger::ThreadBase::unlockEffectChains(
1584 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1585{
1586 for (size_t i = 0; i < effectChains.size(); i++) {
1587 effectChains[i]->unlock();
1588 }
1589}
1590
Glenn Kastend848eb42016-03-08 13:42:11 -08001591sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001592{
1593 Mutex::Autolock _l(mLock);
1594 return getEffectChain_l(sessionId);
1595}
1596
Glenn Kastend848eb42016-03-08 13:42:11 -08001597sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1598 const
Eric Laurent81784c32012-11-19 14:55:58 -08001599{
1600 size_t size = mEffectChains.size();
1601 for (size_t i = 0; i < size; i++) {
1602 if (mEffectChains[i]->sessionId() == sessionId) {
1603 return mEffectChains[i];
1604 }
1605 }
1606 return 0;
1607}
1608
1609void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1610{
1611 Mutex::Autolock _l(mLock);
1612 size_t size = mEffectChains.size();
1613 for (size_t i = 0; i < size; i++) {
1614 mEffectChains[i]->setMode_l(mode);
1615 }
1616}
1617
Eric Laurent83b88082014-06-20 18:31:16 -07001618void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1619{
1620 config->type = AUDIO_PORT_TYPE_MIX;
1621 config->ext.mix.handle = mId;
1622 config->sample_rate = mSampleRate;
1623 config->format = mFormat;
1624 config->channel_mask = mChannelMask;
1625 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1626 AUDIO_PORT_CONFIG_FORMAT;
1627}
1628
Eric Laurent72e3f392015-05-20 14:43:50 -07001629void AudioFlinger::ThreadBase::systemReady()
1630{
1631 Mutex::Autolock _l(mLock);
1632 if (mSystemReady) {
1633 return;
1634 }
1635 mSystemReady = true;
1636
1637 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1638 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1639 }
1640 mPendingConfigEvents.clear();
1641}
1642
Andy Hung2f366df2016-10-31 14:01:16 -07001643template <typename T>
1644ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::add(const sp<T> &track) {
1645 ssize_t index = mActiveTracks.indexOf(track);
1646 if (index >= 0) {
1647 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1648 return index;
1649 }
1650 mActiveTracksGeneration++;
1651 mLatestActiveTrack = track;
1652 BatteryNotifier::getInstance().noteStartAudio(track->uid());
1653 return mActiveTracks.add(track);
1654}
1655
1656template <typename T>
1657ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::remove(const sp<T> &track) {
1658 ssize_t index = mActiveTracks.remove(track);
1659 if (index < 0) {
1660 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1661 return index;
1662 }
1663 mActiveTracksGeneration++;
1664 BatteryNotifier::getInstance().noteStopAudio(track->uid());
1665 // mLatestActiveTrack is not cleared even if is the same as track.
1666 return index;
1667}
1668
1669template <typename T>
1670void AudioFlinger::ThreadBase::ActiveTracks<T>::clear() {
1671 for (const sp<T> &track : mActiveTracks) {
1672 BatteryNotifier::getInstance().noteStopAudio(track->uid());
1673 }
1674 mLastActiveTracksGeneration = mActiveTracksGeneration;
1675 mActiveTracks.clear();
1676 mLatestActiveTrack.clear();
1677}
Eric Laurent83b88082014-06-20 18:31:16 -07001678
Eric Laurent81784c32012-11-19 14:55:58 -08001679// ----------------------------------------------------------------------------
1680// Playback
1681// ----------------------------------------------------------------------------
1682
1683AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1684 AudioStreamOut* output,
1685 audio_io_handle_t id,
1686 audio_devices_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07001687 type_t type,
Eric Laurente93cc032016-05-05 10:15:10 -07001688 bool systemReady)
Eric Laurent72e3f392015-05-20 14:43:50 -07001689 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001690 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001691 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001692 mMixerBuffer(NULL),
1693 mMixerBufferSize(0),
1694 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1695 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001696 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001697 mEffectBuffer(NULL),
1698 mEffectBufferSize(0),
1699 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1700 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001701 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001702 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07001703 mSuspendedFrames(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001704 // mStreamTypes[] initialized in constructor body
1705 mOutput(output),
Andy Hung69488c42016-05-16 18:43:33 -07001706 mLastWriteTime(-1), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001707 mMixerStatus(MIXER_IDLE),
1708 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001709 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001710 mBytesRemaining(0),
1711 mCurrentWriteLength(0),
1712 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001713 mWriteAckSequence(0),
1714 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001715 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001716 mScreenState(AudioFlinger::mScreenState),
1717 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001718 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Andy Hunge10393e2015-06-12 13:59:33 -07001719 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001720{
Glenn Kastend7dca052015-03-05 16:05:54 -08001721 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1722 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001723
1724 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1725 // it would be safer to explicitly pass initial masterVolume/masterMute as
1726 // parameter.
1727 //
1728 // If the HAL we are using has support for master volume or master mute,
1729 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1730 // and the mute set to false).
1731 mMasterVolume = audioFlinger->masterVolume_l();
1732 mMasterMute = audioFlinger->masterMute_l();
1733 if (mOutput && mOutput->audioHwDev) {
1734 if (mOutput->audioHwDev->canSetMasterVolume()) {
1735 mMasterVolume = 1.0;
1736 }
1737
1738 if (mOutput->audioHwDev->canSetMasterMute()) {
1739 mMasterMute = false;
1740 }
1741 }
1742
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001743 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001744
Eric Laurent223fd5c2014-11-11 13:43:36 -08001745 // ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001746 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001747 stream = (audio_stream_type_t) (stream + 1)) {
1748 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1749 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1750 }
Eric Laurent81784c32012-11-19 14:55:58 -08001751}
1752
1753AudioFlinger::PlaybackThread::~PlaybackThread()
1754{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001755 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001756 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001757 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001758 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001759}
1760
1761void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1762{
1763 dumpInternals(fd, args);
1764 dumpTracks(fd, args);
1765 dumpEffectChains(fd, args);
1766}
1767
Glenn Kasten0f11b512014-01-31 16:18:54 -08001768void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001769{
1770 const size_t SIZE = 256;
1771 char buffer[SIZE];
1772 String8 result;
1773
Marco Nelissenb2208842014-02-07 14:00:50 -08001774 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001775 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1776 const stream_type_t *st = &mStreamTypes[i];
1777 if (i > 0) {
1778 result.appendFormat(", ");
1779 }
1780 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1781 if (st->mute) {
1782 result.append("M");
1783 }
1784 }
1785 result.append("\n");
1786 write(fd, result.string(), result.length());
1787 result.clear();
1788
Eric Laurent81784c32012-11-19 14:55:58 -08001789 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1790 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001791 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001792 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001793
1794 size_t numtracks = mTracks.size();
1795 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001796 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001797 size_t numactiveseen = 0;
1798 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001799 dprintf(fd, " of which %zu are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001800 Track::appendDumpHeader(result);
1801 for (size_t i = 0; i < numtracks; ++i) {
1802 sp<Track> track = mTracks[i];
1803 if (track != 0) {
1804 bool active = mActiveTracks.indexOf(track) >= 0;
1805 if (active) {
1806 numactiveseen++;
1807 }
1808 track->dump(buffer, SIZE, active);
1809 result.append(buffer);
1810 }
1811 }
1812 } else {
1813 result.append("\n");
1814 }
1815 if (numactiveseen != numactive) {
1816 // some tracks in the active list were not in the tracks list
1817 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1818 " not in the track list\n");
1819 result.append(buffer);
1820 Track::appendDumpHeader(result);
1821 for (size_t i = 0; i < numactive; ++i) {
Andy Hung2f366df2016-10-31 14:01:16 -07001822 sp<Track> track = mActiveTracks[i];
1823 if (mTracks.indexOf(track) < 0) {
Marco Nelissenb2208842014-02-07 14:00:50 -08001824 track->dump(buffer, SIZE, true);
1825 result.append(buffer);
1826 }
1827 }
1828 }
1829
1830 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001831}
1832
1833void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1834{
Glenn Kasten97b7b752014-09-28 13:04:24 -07001835 dprintf(fd, "\nOutput thread %p type %d (%s):\n", this, type(), threadTypeToString(type()));
Glenn Kasten44182c22015-03-05 17:12:23 -08001836
1837 dumpBase(fd, args);
1838
Elliott Hughes87cebad2014-05-22 10:14:43 -07001839 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001840 dprintf(fd, " Last write occurred (msecs): %llu\n",
1841 (unsigned long long) ns2ms(systemTime() - mLastWriteTime));
Elliott Hughes87cebad2014-05-22 10:14:43 -07001842 dprintf(fd, " Total writes: %d\n", mNumWrites);
1843 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1844 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1845 dprintf(fd, " Suspend count: %d\n", mSuspended);
1846 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1847 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1848 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1849 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08001850 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001851 AudioStreamOut *output = mOutput;
1852 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
1853 String8 flagsAsString = outputFlagsToString(flags);
1854 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n", output, flags, flagsAsString.string());
Andy Hungb54c8542016-09-21 12:55:15 -07001855 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
1856 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
1857 if (mPipeSink.get() != nullptr) {
1858 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
1859 }
1860 if (output != nullptr) {
1861 dprintf(fd, " Hal stream dump:\n");
1862 (void)output->stream->dump(fd);
1863 }
Eric Laurent81784c32012-11-19 14:55:58 -08001864}
1865
1866// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001867
1868void AudioFlinger::PlaybackThread::onFirstRef()
1869{
Glenn Kastend7dca052015-03-05 16:05:54 -08001870 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001871}
1872
1873// ThreadBase virtuals
1874void AudioFlinger::PlaybackThread::preExit()
1875{
1876 ALOGV(" preExit()");
1877 // FIXME this is using hard-coded strings but in the future, this functionality will be
1878 // converted to use audio HAL extensions required to support tunneling
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001879 status_t result = mOutput->stream->setParameters(String8("exiting=1"));
1880 ALOGE_IF(result != OK, "Error when setting parameters on exit: %d", result);
Eric Laurent81784c32012-11-19 14:55:58 -08001881}
1882
1883// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1884sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1885 const sp<AudioFlinger::Client>& client,
1886 audio_stream_type_t streamType,
1887 uint32_t sampleRate,
1888 audio_format_t format,
1889 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001890 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001891 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08001892 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07001893 audio_output_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08001894 pid_t tid,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001895 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -08001896 status_t *status)
1897{
Glenn Kasten74935e42013-12-19 08:56:45 -08001898 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001899 sp<Track> track;
1900 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07001901 audio_output_flags_t outputFlags = mOutput->flags;
1902
1903 // special case for FAST flag considered OK if fast mixer is present
1904 if (hasFastMixer()) {
1905 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
1906 }
1907
1908 // Check if requested flags are compatible with output stream flags
1909 if ((*flags & outputFlags) != *flags) {
1910 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
1911 *flags, outputFlags);
1912 *flags = (audio_output_flags_t)(*flags & outputFlags);
1913 }
Eric Laurent81784c32012-11-19 14:55:58 -08001914
Eric Laurent81784c32012-11-19 14:55:58 -08001915 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07001916 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08001917 if (
Eric Laurent81784c32012-11-19 14:55:58 -08001918 // PCM data
1919 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001920 // TODO: extract as a data library function that checks that a computationally
1921 // expensive downmixer is not required: isFastOutputChannelConversion()
Andy Hung9a592762014-07-21 21:56:01 -07001922 (channelMask == mChannelMask ||
Andy Hung1f439e12015-05-19 12:57:41 -07001923 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1924 (channelMask == AUDIO_CHANNEL_OUT_MONO
1925 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001926 // hardware sample rate
1927 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001928 // normal mixer has an associated fast mixer
1929 hasFastMixer() &&
1930 // there are sufficient fast track slots available
1931 (mFastTrackAvailMask != 0)
1932 // FIXME test that MixerThread for this fast track has a capable output HAL
1933 // FIXME add a permission test also?
1934 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07001935 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
1936 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001937 // read the fast track multiplier property the first time it is needed
1938 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1939 if (ok != 0) {
1940 ALOGE("%s pthread_once failed: %d", __func__, ok);
1941 }
Andy Hunge0a269a2016-03-23 15:13:42 -07001942 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08001943 }
Eric Laurent4c415062016-06-17 16:14:16 -07001944
1945 // check compatibility with audio effects.
1946 { // scope for mLock
1947 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07001948 for (audio_session_t session : {
1949 AUDIO_SESSION_OUTPUT_STAGE,
1950 AUDIO_SESSION_OUTPUT_MIX,
1951 sessionId,
1952 }) {
1953 sp<EffectChain> chain = getEffectChain_l(session);
1954 if (chain.get() != nullptr) {
1955 audio_output_flags_t old = *flags;
1956 chain->checkOutputFlagCompatibility(flags);
1957 if (old != *flags) {
1958 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
1959 (int)session, (int)old, (int)*flags);
1960 }
Eric Laurent4c415062016-06-17 16:14:16 -07001961 }
1962 }
1963 }
Eric Laurent122f7e72016-06-29 11:53:29 -07001964 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07001965 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
1966 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08001967 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001968 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
1969 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07001970 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001971 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08001972 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001973 audio_is_linear_pcm(format),
1974 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07001975 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08001976 }
1977 }
1978 // For normal PCM streaming tracks, update minimum frame count.
1979 // For compatibility with AudioTrack calculation, buffer depth is forced
1980 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1981 // This is probably too conservative, but legacy application code may depend on it.
1982 // If you change this calculation, also review the start threshold which is related.
Eric Laurent05067782016-06-01 18:27:28 -07001983 if (!(*flags & AUDIO_OUTPUT_FLAG_FAST)
Phil Burkfdb3c072016-02-09 10:47:02 -08001984 && audio_has_proportional_frames(format) && sharedBuffer == 0) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001985 // this must match AudioTrack.cpp calculateMinFrameCount().
1986 // TODO: Move to a common library
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001987 uint32_t latencyMs = 0;
1988 lStatus = mOutput->stream->getLatency(&latencyMs);
1989 if (lStatus != OK) {
1990 ALOGE("Error when retrieving output stream latency: %d", lStatus);
1991 goto Exit;
1992 }
Eric Laurent81784c32012-11-19 14:55:58 -08001993 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1994 if (minBufCount < 2) {
1995 minBufCount = 2;
1996 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07001997 // For normal mixing tracks, if speed is > 1.0f (normal), AudioTrack
1998 // or the client should compute and pass in a larger buffer request.
Andy Hung0e48d252015-01-26 11:43:15 -08001999 size_t minFrameCount =
Andy Hung8edb8dc2015-03-26 19:13:55 -07002000 minBufCount * sourceFramesNeededWithTimestretch(
2001 sampleRate, mNormalFrameCount,
2002 mSampleRate, AUDIO_TIMESTRETCH_SPEED_NORMAL /*speed*/);
Andy Hung0e48d252015-01-26 11:43:15 -08002003 if (frameCount < minFrameCount) { // including frameCount == 0
Eric Laurent81784c32012-11-19 14:55:58 -08002004 frameCount = minFrameCount;
2005 }
Eric Laurent81784c32012-11-19 14:55:58 -08002006 }
Glenn Kasten74935e42013-12-19 08:56:45 -08002007 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002008
Glenn Kastenc3df8382014-03-13 15:05:25 -07002009 switch (mType) {
2010
2011 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002012 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002013 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002014 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2015 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002016 sampleRate, format, channelMask, mOutput, mFormat);
2017 lStatus = BAD_VALUE;
2018 goto Exit;
2019 }
2020 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002021 break;
2022
2023 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002024 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002025 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2026 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002027 sampleRate, format, channelMask, mOutput, mFormat);
2028 lStatus = BAD_VALUE;
2029 goto Exit;
2030 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002031 break;
2032
2033 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002034 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002035 ALOGE("createTrack_l() Bad parameter: format %#x \""
2036 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002037 format, mOutput, mFormat);
2038 lStatus = BAD_VALUE;
2039 goto Exit;
2040 }
Andy Hungcd044842014-08-07 11:04:34 -07002041 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002042 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2043 lStatus = BAD_VALUE;
2044 goto Exit;
2045 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002046 break;
2047
Eric Laurent81784c32012-11-19 14:55:58 -08002048 }
2049
2050 lStatus = initCheck();
2051 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002052 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002053 goto Exit;
2054 }
2055
2056 { // scope for mLock
2057 Mutex::Autolock _l(mLock);
2058
2059 // all tracks in same audio session must share the same routing strategy otherwise
2060 // conflicts will happen when tracks are moved from one output to another by audio policy
2061 // manager
2062 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
2063 for (size_t i = 0; i < mTracks.size(); ++i) {
2064 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002065 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002066 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
2067 if (sessionId == t->sessionId() && strategy != actual) {
2068 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2069 strategy, actual);
2070 lStatus = BAD_VALUE;
2071 goto Exit;
2072 }
2073 }
2074 }
2075
Glenn Kastend79072e2016-01-06 08:41:20 -08002076 track = new Track(this, client, streamType, sampleRate, format,
2077 channelMask, frameCount, NULL, sharedBuffer,
2078 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT);
Glenn Kasten03003332013-08-06 15:40:54 -07002079
Glenn Kasten03003332013-08-06 15:40:54 -07002080 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2081 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002082 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002083 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002084 goto Exit;
2085 }
2086 mTracks.add(track);
2087
2088 sp<EffectChain> chain = getEffectChain_l(sessionId);
2089 if (chain != 0) {
2090 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2091 track->setMainBuffer(chain->inBuffer());
2092 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
2093 chain->incTrackCnt();
2094 }
2095
Eric Laurent05067782016-06-01 18:27:28 -07002096 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002097 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2098 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2099 // so ask activity manager to do this on our behalf
2100 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
2101 }
2102 }
2103
2104 lStatus = NO_ERROR;
2105
2106Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002107 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002108 return track;
2109}
2110
2111uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2112{
2113 return latency;
2114}
2115
2116uint32_t AudioFlinger::PlaybackThread::latency() const
2117{
2118 Mutex::Autolock _l(mLock);
2119 return latency_l();
2120}
2121uint32_t AudioFlinger::PlaybackThread::latency_l() const
2122{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002123 uint32_t latency;
2124 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2125 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002126 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002127 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002128}
2129
2130void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2131{
2132 Mutex::Autolock _l(mLock);
2133 // Don't apply master volume in SW if our HAL can do it for us.
2134 if (mOutput && mOutput->audioHwDev &&
2135 mOutput->audioHwDev->canSetMasterVolume()) {
2136 mMasterVolume = 1.0;
2137 } else {
2138 mMasterVolume = value;
2139 }
2140}
2141
2142void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2143{
2144 Mutex::Autolock _l(mLock);
2145 // Don't apply master mute in SW if our HAL can do it for us.
2146 if (mOutput && mOutput->audioHwDev &&
2147 mOutput->audioHwDev->canSetMasterMute()) {
2148 mMasterMute = false;
2149 } else {
2150 mMasterMute = muted;
2151 }
2152}
2153
2154void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2155{
2156 Mutex::Autolock _l(mLock);
2157 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002158 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002159}
2160
2161void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2162{
2163 Mutex::Autolock _l(mLock);
2164 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002165 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002166}
2167
2168float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2169{
2170 Mutex::Autolock _l(mLock);
2171 return mStreamTypes[stream].volume;
2172}
2173
2174// addTrack_l() must be called with ThreadBase::mLock held
2175status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2176{
2177 status_t status = ALREADY_EXISTS;
2178
Eric Laurent81784c32012-11-19 14:55:58 -08002179 if (mActiveTracks.indexOf(track) < 0) {
2180 // the track is newly added, make sure it fills up all its
2181 // buffers before playing. This is to ensure the client will
2182 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002183 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002184 TrackBase::track_state state = track->mState;
2185 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002186 status = AudioSystem::startOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002187 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002188 mLock.lock();
2189 // abort track was stopped/paused while we released the lock
2190 if (state != track->mState) {
2191 if (status == NO_ERROR) {
2192 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002193 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002194 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002195 mLock.lock();
2196 }
2197 return INVALID_OPERATION;
2198 }
2199 // abort if start is rejected by audio policy manager
2200 if (status != NO_ERROR) {
2201 return PERMISSION_DENIED;
2202 }
2203#ifdef ADD_BATTERY_DATA
2204 // to track the speaker usage
2205 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2206#endif
2207 }
2208
Eric Laurent51716182016-02-29 18:00:56 -08002209 // set retry count for buffer fill
2210 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002211 if (track->isStopping_1()) {
2212 track->mRetryCount = kMaxTrackStopRetriesOffload;
2213 } else {
2214 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2215 }
2216 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002217 } else {
2218 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002219 track->mFillingUpStatus =
2220 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002221 }
2222
Eric Laurent81784c32012-11-19 14:55:58 -08002223 track->mResetDone = false;
2224 track->mPresentationCompleteFrames = 0;
2225 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002226 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2227 if (chain != 0) {
2228 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2229 track->sessionId());
2230 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002231 }
2232
2233 status = NO_ERROR;
2234 }
2235
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002236 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002237 return status;
2238}
2239
Eric Laurentbfb1b832013-01-07 09:53:42 -08002240bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002241{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002242 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002243 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002244 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2245 track->mState = TrackBase::STOPPED;
2246 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002247 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002248 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002249 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002250 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002251
2252 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002253}
2254
2255void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2256{
2257 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
2258 mTracks.remove(track);
2259 deleteTrackName_l(track->name());
2260 // redundant as track is about to be destroyed, for dumpsys only
2261 track->mName = -1;
2262 if (track->isFastTrack()) {
2263 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002264 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002265 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2266 mFastTrackAvailMask |= 1 << index;
2267 // redundant as track is about to be destroyed, for dumpsys only
2268 track->mFastIndex = -1;
2269 }
2270 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2271 if (chain != 0) {
2272 chain->decTrackCnt();
2273 }
2274}
2275
Eric Laurentede6c3b2013-09-19 14:37:46 -07002276void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002277{
2278 // Thread could be blocked waiting for async
2279 // so signal it to handle state changes immediately
2280 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
2281 // be lost so we also flag to prevent it blocking on mWaitWorkCV
2282 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002283 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002284}
2285
Eric Laurent81784c32012-11-19 14:55:58 -08002286String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2287{
Eric Laurent81784c32012-11-19 14:55:58 -08002288 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002289 String8 out_s8;
2290 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2291 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002292 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002293 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002294}
2295
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002296void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002297 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2298 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002299
Eric Laurent73e26b62015-04-27 16:55:58 -07002300 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002301
2302 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002303 case AUDIO_OUTPUT_OPENED:
2304 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002305 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002306 desc->mChannelMask = mChannelMask;
2307 desc->mSamplingRate = mSampleRate;
2308 desc->mFormat = mFormat;
2309 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002310 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002311 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002312 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002313 break;
2314
Eric Laurent73e26b62015-04-27 16:55:58 -07002315 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002316 default:
2317 break;
2318 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002319 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002320}
2321
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002322void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002323{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002324 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002325}
2326
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002327void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002328{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002329 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002330}
2331
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002332void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002333{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002334 mCallbackThread->setAsyncError();
2335}
2336
Eric Laurent3b4529e2013-09-05 18:09:19 -07002337void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002338{
2339 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002340 // reject out of sequence requests
2341 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2342 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002343 mWaitWorkCV.signal();
2344 }
2345}
2346
Eric Laurent3b4529e2013-09-05 18:09:19 -07002347void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002348{
2349 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002350 // reject out of sequence requests
2351 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
2352 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002353 mWaitWorkCV.signal();
2354 }
2355}
2356
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002357void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002358{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002359 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002360 mSampleRate = mOutput->getSampleRate();
2361 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002362 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002363 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002364 }
Andy Hung9a592762014-07-21 21:56:01 -07002365 if ((mType == MIXER || mType == DUPLICATING)
2366 && !isValidPcmSinkChannelMask(mChannelMask)) {
2367 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2368 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002369 }
Andy Hunge5412692014-05-16 11:25:07 -07002370 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002371
2372 // Get actual HAL format.
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002373 status_t result = mOutput->stream->getFormat(&mHALFormat);
2374 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002375 // Get format from the shim, which will be different than the HAL format
2376 // if playing compressed audio over HDMI passthrough.
2377 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002378 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002379 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002380 }
Andy Hung6146c082014-03-18 11:56:15 -07002381 if ((mType == MIXER || mType == DUPLICATING)
2382 && !isValidPcmSinkFormat(mFormat)) {
2383 LOG_FATAL("HAL format %#x not supported for mixed output",
2384 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002385 }
Phil Burk062e67a2015-02-11 13:40:50 -08002386 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002387 result = mOutput->stream->getBufferSize(&mBufferSize);
2388 LOG_ALWAYS_FATAL_IF(result != OK,
2389 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07002390 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002391 if (mFrameCount & 15) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002392 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002393 mFrameCount);
2394 }
2395
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002396 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
2397 if (mOutput->stream->setCallback(this) == OK) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002398 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002399 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002400 }
2401 }
2402
Eric Laurentd1f69b02014-12-15 14:33:13 -08002403 mHwSupportsPause = false;
2404 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002405 bool supportsPause = false, supportsResume = false;
2406 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
2407 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002408 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002409 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002410 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002411 } else if (supportsResume) {
2412 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08002413 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002414 }
2415 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002416 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2417 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2418 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002419
Andy Hungfbfc3952015-01-15 13:33:51 -08002420 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2421 // For best precision, we use float instead of the associated output
2422 // device format (typically PCM 16 bit).
2423
2424 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2425 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2426 mBufferSize = mFrameSize * mFrameCount;
2427
2428 // TODO: We currently use the associated output device channel mask and sample rate.
2429 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2430 // (if a valid mask) to avoid premature downmix.
2431 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2432 // instead of the output device sample rate to avoid loss of high frequency information.
2433 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2434 }
2435
Andy Hung09a50072014-02-27 14:30:47 -08002436 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002437 double multiplier = 1.0;
2438 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2439 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002440 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2441 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002442
Eric Laurent81784c32012-11-19 14:55:58 -08002443 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2444 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2445 maxNormalFrameCount = maxNormalFrameCount & ~15;
2446 if (maxNormalFrameCount < minNormalFrameCount) {
2447 maxNormalFrameCount = minNormalFrameCount;
2448 }
2449 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2450 if (multiplier <= 1.0) {
2451 multiplier = 1.0;
2452 } else if (multiplier <= 2.0) {
2453 if (2 * mFrameCount <= maxNormalFrameCount) {
2454 multiplier = 2.0;
2455 } else {
2456 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2457 }
2458 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002459 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002460 }
2461 }
2462 mNormalFrameCount = multiplier * mFrameCount;
2463 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002464 if (mType == MIXER || mType == DUPLICATING) {
2465 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2466 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002467 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002468 mNormalFrameCount);
2469
Andy Hung08fb1742015-05-31 23:22:10 -07002470 // Check if we want to throttle the processing to no more than 2x normal rate
2471 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002472 mThreadThrottleTimeMs = 0;
2473 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002474 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2475
Andy Hung010a1a12014-03-13 13:57:33 -07002476 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2477 // Originally this was int16_t[] array, need to remove legacy implications.
2478 free(mSinkBuffer);
2479 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002480 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2481 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2482 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002483 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002484
Andy Hung69aed5f2014-02-25 17:24:40 -08002485 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2486 // drives the output.
2487 free(mMixerBuffer);
2488 mMixerBuffer = NULL;
2489 if (mMixerBufferEnabled) {
2490 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2491 mMixerBufferSize = mNormalFrameCount * mChannelCount
2492 * audio_bytes_per_sample(mMixerBufferFormat);
2493 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2494 }
Andy Hung98ef9782014-03-04 14:46:50 -08002495 free(mEffectBuffer);
2496 mEffectBuffer = NULL;
2497 if (mEffectBufferEnabled) {
2498 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2499 mEffectBufferSize = mNormalFrameCount * mChannelCount
2500 * audio_bytes_per_sample(mEffectBufferFormat);
2501 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2502 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002503
Eric Laurent81784c32012-11-19 14:55:58 -08002504 // force reconfiguration of effect chains and engines to take new buffer size and audio
2505 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002506 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002507 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2508 // matter.
2509 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2510 Vector< sp<EffectChain> > effectChains = mEffectChains;
2511 for (size_t i = 0; i < effectChains.size(); i ++) {
2512 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2513 }
2514}
2515
2516
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002517status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002518{
2519 if (halFrames == NULL || dspFrames == NULL) {
2520 return BAD_VALUE;
2521 }
2522 Mutex::Autolock _l(mLock);
2523 if (initCheck() != NO_ERROR) {
2524 return INVALID_OPERATION;
2525 }
Andy Hung818e7a32016-02-16 18:08:07 -08002526 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002527 *halFrames = framesWritten;
2528
2529 if (isSuspended()) {
2530 // return an estimation of rendered frames when the output is suspended
2531 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002532 *dspFrames = (uint32_t)
2533 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002534 return NO_ERROR;
2535 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002536 status_t status;
2537 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002538 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002539 *dspFrames = (size_t)frames;
2540 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002541 }
2542}
2543
Eric Laurent4c415062016-06-17 16:14:16 -07002544// hasAudioSession_l() must be called with ThreadBase::mLock held
2545uint32_t AudioFlinger::PlaybackThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08002546{
Eric Laurent81784c32012-11-19 14:55:58 -08002547 uint32_t result = 0;
2548 if (getEffectChain_l(sessionId) != 0) {
2549 result = EFFECT_SESSION;
2550 }
2551
2552 for (size_t i = 0; i < mTracks.size(); ++i) {
2553 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002554 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002555 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07002556 if (track->isFastTrack()) {
2557 result |= FAST_SESSION;
2558 }
Eric Laurent81784c32012-11-19 14:55:58 -08002559 break;
2560 }
2561 }
2562
2563 return result;
2564}
2565
Glenn Kastend848eb42016-03-08 13:42:11 -08002566uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08002567{
2568 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2569 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2570 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2571 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2572 }
2573 for (size_t i = 0; i < mTracks.size(); i++) {
2574 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002575 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002576 return AudioSystem::getStrategyForStream(track->streamType());
2577 }
2578 }
2579 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2580}
2581
2582
Phil Burk062e67a2015-02-11 13:40:50 -08002583AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002584{
2585 Mutex::Autolock _l(mLock);
2586 return mOutput;
2587}
2588
Phil Burk062e67a2015-02-11 13:40:50 -08002589AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002590{
2591 Mutex::Autolock _l(mLock);
2592 AudioStreamOut *output = mOutput;
2593 mOutput = NULL;
2594 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2595 // must push a NULL and wait for ack
2596 mOutputSink.clear();
2597 mPipeSink.clear();
2598 mNormalSink.clear();
2599 return output;
2600}
2601
2602// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002603sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08002604{
2605 if (mOutput == NULL) {
2606 return NULL;
2607 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002608 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08002609}
2610
2611uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2612{
2613 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2614}
2615
2616status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2617{
2618 if (!isValidSyncEvent(event)) {
2619 return BAD_VALUE;
2620 }
2621
2622 Mutex::Autolock _l(mLock);
2623
2624 for (size_t i = 0; i < mTracks.size(); ++i) {
2625 sp<Track> track = mTracks[i];
2626 if (event->triggerSession() == track->sessionId()) {
2627 (void) track->setSyncEvent(event);
2628 return NO_ERROR;
2629 }
2630 }
2631
2632 return NAME_NOT_FOUND;
2633}
2634
2635bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2636{
2637 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2638}
2639
2640void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2641 const Vector< sp<Track> >& tracksToRemove)
2642{
2643 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002644 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002645 for (size_t i = 0 ; i < count ; i++) {
2646 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002647 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002648 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002649 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002650#ifdef ADD_BATTERY_DATA
2651 // to track the speaker usage
2652 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2653#endif
2654 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002655 AudioSystem::releaseOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002656 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002657 }
Eric Laurent81784c32012-11-19 14:55:58 -08002658 }
2659 }
2660 }
Eric Laurent81784c32012-11-19 14:55:58 -08002661}
2662
2663void AudioFlinger::PlaybackThread::checkSilentMode_l()
2664{
2665 if (!mMasterMute) {
2666 char value[PROPERTY_VALUE_MAX];
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07002667 if (mOutDevice == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) {
2668 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
2669 return;
2670 }
Eric Laurent81784c32012-11-19 14:55:58 -08002671 if (property_get("ro.audio.silent", value, "0") > 0) {
2672 char *endptr;
2673 unsigned long ul = strtoul(value, &endptr, 0);
2674 if (*endptr == '\0' && ul != 0) {
2675 ALOGD("Silence is golden");
2676 // The setprop command will not allow a property to be changed after
2677 // the first time it is set, so we don't have to worry about un-muting.
2678 setMasterMute_l(true);
2679 }
2680 }
2681 }
2682}
2683
2684// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002685ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002686{
Eric Laurent81784c32012-11-19 14:55:58 -08002687 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002688 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002689 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002690
2691 // If an NBAIO sink is present, use it to write the normal mixer's submix
2692 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002693
Andy Hung010a1a12014-03-13 13:57:33 -07002694 const size_t count = mBytesRemaining / mFrameSize;
2695
Simon Wilson2d590962012-11-29 15:18:50 -08002696 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002697 // update the setpoint when AudioFlinger::mScreenState changes
2698 uint32_t screenState = AudioFlinger::mScreenState;
2699 if (screenState != mScreenState) {
2700 mScreenState = screenState;
2701 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2702 if (pipe != NULL) {
2703 pipe->setAvgFrames((mScreenState & 1) ?
2704 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2705 }
2706 }
Andy Hung010a1a12014-03-13 13:57:33 -07002707 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002708 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002709 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002710 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002711 } else {
2712 bytesWritten = framesWritten;
2713 }
2714 // otherwise use the HAL / AudioStreamOut directly
2715 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002716 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002717
Eric Laurentbfb1b832013-01-07 09:53:42 -08002718 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002719 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2720 mWriteAckSequence += 2;
2721 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002722 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002723 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002724 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002725 // FIXME We should have an implementation of timestamps for direct output threads.
2726 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002727 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurent51716182016-02-29 18:00:56 -08002728
Eric Laurentbfb1b832013-01-07 09:53:42 -08002729 if (mUseAsyncWrite &&
2730 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2731 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002732 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002733 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002734 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002735 }
Eric Laurent81784c32012-11-19 14:55:58 -08002736 }
2737
Eric Laurent81784c32012-11-19 14:55:58 -08002738 mNumWrites++;
2739 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002740 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002741 return bytesWritten;
2742}
2743
2744void AudioFlinger::PlaybackThread::threadLoop_drain()
2745{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002746 bool supportsDrain = false;
2747 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002748 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2749 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002750 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2751 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002752 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002753 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002754 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07002755 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002756 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002757 }
2758}
2759
2760void AudioFlinger::PlaybackThread::threadLoop_exit()
2761{
Eric Laurent275e8e92014-11-30 15:14:47 -08002762 {
2763 Mutex::Autolock _l(mLock);
2764 for (size_t i = 0; i < mTracks.size(); i++) {
2765 sp<Track> track = mTracks[i];
2766 track->invalidate();
2767 }
2768 }
Eric Laurent81784c32012-11-19 14:55:58 -08002769}
2770
2771/*
2772The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002773 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002774 - mActiveSleepTimeUs from activeSleepTimeUs()
2775 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08002776 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
2777 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08002778 - maxPeriod from frame count and sample rate (MIXER only)
2779
2780The parameters that affect these derived values are:
2781 - frame count
2782 - frame size
2783 - sample rate
2784 - device type: A2DP or not
2785 - device latency
2786 - format: PCM or not
2787 - active sleep time
2788 - idle sleep time
2789*/
2790
2791void AudioFlinger::PlaybackThread::cacheParameters_l()
2792{
Andy Hung25c2dac2014-02-27 14:56:00 -08002793 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002794 mActiveSleepTimeUs = activeSleepTimeUs();
2795 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08002796
2797 // make sure standby delay is not too short when connected to an A2DP sink to avoid
2798 // truncating audio when going to standby.
2799 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
2800 if ((mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != 0) {
2801 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
2802 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
2803 }
2804 }
Eric Laurent81784c32012-11-19 14:55:58 -08002805}
2806
Eric Laurent13084622016-05-17 10:51:49 -07002807bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08002808{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002809 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08002810 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07002811 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002812 size_t size = mTracks.size();
2813 for (size_t i = 0; i < size; i++) {
2814 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07002815 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002816 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07002817 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002818 }
2819 }
Eric Laurent13084622016-05-17 10:51:49 -07002820 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08002821}
2822
Haynes Mathew George05317d22016-05-03 16:34:26 -07002823void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2824{
2825 Mutex::Autolock _l(mLock);
2826 invalidateTracks_l(streamType);
2827}
2828
Eric Laurent81784c32012-11-19 14:55:58 -08002829status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2830{
Glenn Kastend848eb42016-03-08 13:42:11 -08002831 audio_session_t session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002832 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2833 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002834 bool ownsBuffer = false;
2835
2836 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Glenn Kastend848eb42016-03-08 13:42:11 -08002837 if (session > AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002838 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002839 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002840 if (mType != DIRECT) {
2841 size_t numSamples = mNormalFrameCount * mChannelCount;
2842 buffer = new int16_t[numSamples];
2843 memset(buffer, 0, numSamples * sizeof(int16_t));
2844 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2845 ownsBuffer = true;
2846 }
2847
2848 // Attach all tracks with same session ID to this chain.
2849 for (size_t i = 0; i < mTracks.size(); ++i) {
2850 sp<Track> track = mTracks[i];
2851 if (session == track->sessionId()) {
2852 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2853 buffer);
2854 track->setMainBuffer(buffer);
2855 chain->incTrackCnt();
2856 }
2857 }
2858
2859 // indicate all active tracks in the chain
Andy Hung2f366df2016-10-31 14:01:16 -07002860 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08002861 if (session == track->sessionId()) {
2862 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2863 chain->incActiveTrackCnt();
2864 }
2865 }
2866 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002867 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08002868 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002869 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2870 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002871 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Glenn Kastend848eb42016-03-08 13:42:11 -08002872 // chains list in order to be processed last as it contains output stage effects.
Eric Laurent81784c32012-11-19 14:55:58 -08002873 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2874 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08002875 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08002876 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08002877 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08002878 // Effect chain for other sessions are inserted at beginning of effect
2879 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08002880 // sessions is not important.
2881 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
2882 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX,
2883 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08002884 size_t size = mEffectChains.size();
2885 size_t i = 0;
2886 for (i = 0; i < size; i++) {
2887 if (mEffectChains[i]->sessionId() < session) {
2888 break;
2889 }
2890 }
2891 mEffectChains.insertAt(chain, i);
2892 checkSuspendOnAddEffectChain_l(chain);
2893
2894 return NO_ERROR;
2895}
2896
2897size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2898{
Glenn Kastend848eb42016-03-08 13:42:11 -08002899 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08002900
2901 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2902
2903 for (size_t i = 0; i < mEffectChains.size(); i++) {
2904 if (chain == mEffectChains[i]) {
2905 mEffectChains.removeAt(i);
2906 // detach all active tracks from the chain
Andy Hung2f366df2016-10-31 14:01:16 -07002907 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08002908 if (session == track->sessionId()) {
2909 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2910 chain.get(), session);
2911 chain->decActiveTrackCnt();
2912 }
2913 }
2914
2915 // detach all tracks with same session ID from this chain
2916 for (size_t i = 0; i < mTracks.size(); ++i) {
2917 sp<Track> track = mTracks[i];
2918 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002919 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002920 chain->decTrackCnt();
2921 }
2922 }
2923 break;
2924 }
2925 }
2926 return mEffectChains.size();
2927}
2928
2929status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002930 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08002931{
2932 Mutex::Autolock _l(mLock);
2933 return attachAuxEffect_l(track, EffectId);
2934}
2935
2936status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002937 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08002938{
2939 status_t status = NO_ERROR;
2940
2941 if (EffectId == 0) {
2942 track->setAuxBuffer(0, NULL);
2943 } else {
2944 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2945 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2946 if (effect != 0) {
2947 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2948 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2949 } else {
2950 status = INVALID_OPERATION;
2951 }
2952 } else {
2953 status = BAD_VALUE;
2954 }
2955 }
2956 return status;
2957}
2958
2959void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2960{
2961 for (size_t i = 0; i < mTracks.size(); ++i) {
2962 sp<Track> track = mTracks[i];
2963 if (track->auxEffectId() == effectId) {
2964 attachAuxEffect_l(track, 0);
2965 }
2966 }
2967}
2968
2969bool AudioFlinger::PlaybackThread::threadLoop()
2970{
2971 Vector< sp<Track> > tracksToRemove;
2972
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002973 mStandbyTimeNs = systemTime();
Andy Hung69488c42016-05-16 18:43:33 -07002974 nsecs_t lastWriteFinished = -1; // time last server write completed
2975 int64_t lastFramesWritten = -1; // track changes in timestamp server frames written
Eric Laurent81784c32012-11-19 14:55:58 -08002976
2977 // MIXER
2978 nsecs_t lastWarning = 0;
2979
2980 // DUPLICATING
2981 // FIXME could this be made local to while loop?
2982 writeFrames = 0;
2983
2984 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002985 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002986
2987 if (mType == MIXER) {
2988 sleepTimeShift = 0;
2989 }
2990
2991 CpuStats cpuStats;
2992 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2993
2994 acquireWakeLock();
2995
Glenn Kasten9e58b552013-01-18 15:09:48 -08002996 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2997 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2998 // and then that string will be logged at the next convenient opportunity.
2999 const char *logString = NULL;
3000
Eric Laurent664539d2013-09-23 18:24:31 -07003001 checkSilentMode_l();
3002
Eric Laurent81784c32012-11-19 14:55:58 -08003003 while (!exitPending())
3004 {
3005 cpuStats.sample(myName);
3006
3007 Vector< sp<EffectChain> > effectChains;
3008
Eric Laurent81784c32012-11-19 14:55:58 -08003009 { // scope for mLock
3010
3011 Mutex::Autolock _l(mLock);
3012
Eric Laurent021cf962014-05-13 10:18:14 -07003013 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07003014
Glenn Kasten9e58b552013-01-18 15:09:48 -08003015 if (logString != NULL) {
3016 mNBLogWriter->logTimestamp();
3017 mNBLogWriter->log(logString);
3018 logString = NULL;
3019 }
3020
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003021 // Gather the framesReleased counters for all active tracks,
Andy Hunge10393e2015-06-12 13:59:33 -07003022 // and associate with the sink frames written out. We need
3023 // this to convert the sink timestamp to the track timestamp.
Andy Hung69488c42016-05-16 18:43:33 -07003024 bool kernelLocationUpdate = false;
Andy Hunge10393e2015-06-12 13:59:33 -07003025 if (mNormalSink != 0) {
Andy Hungc54b1ff2016-02-23 14:07:07 -08003026 // Note: The DuplicatingThread may not have a mNormalSink.
Andy Hung818e7a32016-02-16 18:08:07 -08003027 // We always fetch the timestamp here because often the downstream
Andy Hung69488c42016-05-16 18:43:33 -07003028 // sink will block while writing.
Andy Hung818e7a32016-02-16 18:08:07 -08003029 ExtendedTimestamp timestamp; // use private copy to fetch
3030 (void) mNormalSink->getTimestamp(timestamp);
Andy Hung6d7b1192016-05-07 22:59:48 -07003031
3032 // We keep track of the last valid kernel position in case we are in underrun
3033 // and the normal mixer period is the same as the fast mixer period, or there
3034 // is some error from the HAL.
3035 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3036 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3037 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
3038 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3039 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
3040
3041 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3042 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
3043 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3044 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
Andy Hung69488c42016-05-16 18:43:33 -07003045 }
3046
3047 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3048 kernelLocationUpdate = true;
Andy Hung6d7b1192016-05-07 22:59:48 -07003049 } else {
Eric Laurent122f7e72016-06-29 11:53:29 -07003050 ALOGVV("getTimestamp error - no valid kernel position");
Andy Hung6d7b1192016-05-07 22:59:48 -07003051 }
3052
Andy Hung818e7a32016-02-16 18:08:07 -08003053 // copy over kernel info
3054 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
Andy Hung238fa3d2016-07-28 10:53:22 -07003055 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3056 + mSuspendedFrames; // add frames discarded when suspended
Andy Hung818e7a32016-02-16 18:08:07 -08003057 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
3058 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hungc54b1ff2016-02-23 14:07:07 -08003059 }
3060 // mFramesWritten for non-offloaded tracks are contiguous
3061 // even after standby() is called. This is useful for the track frame
3062 // to sink frame mapping.
Andy Hung69488c42016-05-16 18:43:33 -07003063 bool serverLocationUpdate = false;
3064 if (mFramesWritten != lastFramesWritten) {
3065 serverLocationUpdate = true;
3066 lastFramesWritten = mFramesWritten;
3067 }
3068 // Only update timestamps if there is a meaningful change.
3069 // Either the kernel timestamp must be valid or we have written something.
3070 if (kernelLocationUpdate || serverLocationUpdate) {
3071 if (serverLocationUpdate) {
3072 // use the time before we called the HAL write - it is a bit more accurate
3073 // to when the server last read data than the current time here.
3074 //
3075 // If we haven't written anything, mLastWriteTime will be -1
3076 // and we use systemTime().
3077 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
3078 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastWriteTime == -1
3079 ? systemTime() : mLastWriteTime;
3080 }
Andy Hung2f366df2016-10-31 14:01:16 -07003081
3082 for (const sp<Track> &t : mActiveTracks) {
3083 if (!t->isFastTrack()) {
Andy Hung69488c42016-05-16 18:43:33 -07003084 t->updateTrackFrameInfo(
3085 t->mAudioTrackServerProxy->framesReleased(),
3086 mFramesWritten,
3087 mTimestamp);
3088 }
Andy Hunge10393e2015-06-12 13:59:33 -07003089 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07003090 }
3091
Eric Laurent81784c32012-11-19 14:55:58 -08003092 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003093 if (mSignalPending) {
3094 // A signal was raised while we were unlocked
3095 mSignalPending = false;
3096 } else if (waitingAsyncCallback_l()) {
3097 if (exitPending()) {
3098 break;
3099 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003100 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003101 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003102 releaseWakeLock_l();
3103 released = true;
3104 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003105 ALOGV("wait async completion");
3106 mWaitWorkCV.wait(mLock);
3107 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003108 if (released) {
3109 acquireWakeLock_l();
3110 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003111 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3112 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003113
3114 continue;
3115 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003116 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003117 isSuspended()) {
3118 // put audio hardware into standby after short delay
3119 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003120
3121 threadLoop_standby();
3122
3123 mStandby = true;
3124 }
3125
3126 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
3127 // we're about to wait, flush the binder command buffer
3128 IPCThreadState::self()->flushCommands();
3129
3130 clearOutputTracks();
3131
3132 if (exitPending()) {
3133 break;
3134 }
3135
3136 releaseWakeLock_l();
3137 // wait until we have something to do...
3138 ALOGV("%s going to sleep", myName.string());
3139 mWaitWorkCV.wait(mLock);
3140 ALOGV("%s waking up", myName.string());
3141 acquireWakeLock_l();
3142
3143 mMixerStatus = MIXER_IDLE;
3144 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3145 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003146 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003147 checkSilentMode_l();
3148
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003149 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3150 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003151 if (mType == MIXER) {
3152 sleepTimeShift = 0;
3153 }
3154
3155 continue;
3156 }
3157 }
Eric Laurent81784c32012-11-19 14:55:58 -08003158 // mMixerStatusIgnoringFastTracks is also updated internally
3159 mMixerStatus = prepareTracks_l(&tracksToRemove);
3160
Andy Hung2f366df2016-10-31 14:01:16 -07003161 mActiveTracks.updateWakeLockUids(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003162
Eric Laurent81784c32012-11-19 14:55:58 -08003163 // prevent any changes in effect chain list and in each effect chain
3164 // during mixing and effect process as the audio buffers could be deleted
3165 // or modified if an effect is created or deleted
3166 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003167 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003168
Eric Laurentbfb1b832013-01-07 09:53:42 -08003169 if (mBytesRemaining == 0) {
3170 mCurrentWriteLength = 0;
3171 if (mMixerStatus == MIXER_TRACKS_READY) {
3172 // threadLoop_mix() sets mCurrentWriteLength
3173 threadLoop_mix();
3174 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3175 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003176 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003177 // must be written to HAL
3178 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003179 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003180 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003181 }
3182 }
Andy Hung98ef9782014-03-04 14:46:50 -08003183 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003184 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003185 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3186 // or mSinkBuffer (if there are no effects).
3187 //
3188 // This is done pre-effects computation; if effects change to
3189 // support higher precision, this needs to move.
3190 //
3191 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003192 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003193 if (mMixerBufferValid) {
3194 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3195 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3196
Andy Hung2ddee192015-12-18 17:34:44 -08003197 // mono blend occurs for mixer threads only (not direct or offloaded)
3198 // and is handled here if we're going directly to the sink.
3199 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003200 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3201 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003202 }
3203
Andy Hung98ef9782014-03-04 14:46:50 -08003204 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
3205 mNormalFrameCount * mChannelCount);
3206 }
3207
Eric Laurentbfb1b832013-01-07 09:53:42 -08003208 mBytesRemaining = mCurrentWriteLength;
3209 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003210 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3211 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3212 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3213 mBytesWritten += mBytesRemaining;
3214 mFramesWritten += framesRemaining;
3215 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003216 mBytesRemaining = 0;
3217 }
Eric Laurent81784c32012-11-19 14:55:58 -08003218
Eric Laurentbfb1b832013-01-07 09:53:42 -08003219 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003220 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003221 for (size_t i = 0; i < effectChains.size(); i ++) {
3222 effectChains[i]->process_l();
3223 }
Eric Laurent81784c32012-11-19 14:55:58 -08003224 }
3225 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003226 // Process effect chains for offloaded thread even if no audio
3227 // was read from audio track: process only updates effect state
3228 // and thus does have to be synchronized with audio writes but may have
3229 // to be called while waiting for async write callback
3230 if (mType == OFFLOAD) {
3231 for (size_t i = 0; i < effectChains.size(); i ++) {
3232 effectChains[i]->process_l();
3233 }
3234 }
Eric Laurent81784c32012-11-19 14:55:58 -08003235
Andy Hung98ef9782014-03-04 14:46:50 -08003236 // Only if the Effects buffer is enabled and there is data in the
3237 // Effects buffer (buffer valid), we need to
3238 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003239 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003240 if (mEffectBufferValid) {
3241 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003242
3243 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003244 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3245 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003246 }
3247
Andy Hung98ef9782014-03-04 14:46:50 -08003248 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
3249 mNormalFrameCount * mChannelCount);
3250 }
3251
Eric Laurent81784c32012-11-19 14:55:58 -08003252 // enable changes in effect chain
3253 unlockEffectChains(effectChains);
3254
Eric Laurentbfb1b832013-01-07 09:53:42 -08003255 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003256 // mSleepTimeUs == 0 means we must write to audio hardware
3257 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003258 ssize_t ret = 0;
Andy Hung69488c42016-05-16 18:43:33 -07003259 // We save lastWriteFinished here, as previousLastWriteFinished,
3260 // for throttling. On thread start, previousLastWriteFinished will be
3261 // set to -1, which properly results in no throttling after the first write.
3262 nsecs_t previousLastWriteFinished = lastWriteFinished;
3263 nsecs_t delta = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003264 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003265 // FIXME rewrite to reduce number of system calls
3266 mLastWriteTime = systemTime(); // also used for dumpsys
Andy Hung08fb1742015-05-31 23:22:10 -07003267 ret = threadLoop_write();
Andy Hung69488c42016-05-16 18:43:33 -07003268 lastWriteFinished = systemTime();
3269 delta = lastWriteFinished - mLastWriteTime;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003270 if (ret < 0) {
3271 mBytesRemaining = 0;
3272 } else {
3273 mBytesWritten += ret;
3274 mBytesRemaining -= ret;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003275 mFramesWritten += ret / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003276 }
3277 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3278 (mMixerStatus == MIXER_DRAIN_ALL)) {
3279 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003280 }
Andy Hung08fb1742015-05-31 23:22:10 -07003281 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003282 // write blocked detection
Andy Hung08fb1742015-05-31 23:22:10 -07003283 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003284 mNumDelayedWrites++;
Andy Hung69488c42016-05-16 18:43:33 -07003285 if ((lastWriteFinished - lastWarning) > kWarningThrottleNs) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003286 ATRACE_NAME("underrun");
3287 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003288 (unsigned long long) ns2ms(delta), mNumDelayedWrites, this);
Andy Hung69488c42016-05-16 18:43:33 -07003289 lastWarning = lastWriteFinished;
Glenn Kasten4944acb2013-08-19 08:39:20 -07003290 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003291 }
Andy Hung08fb1742015-05-31 23:22:10 -07003292
3293 if (mThreadThrottle
3294 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
3295 && ret > 0) { // we wrote something
3296 // Limit MixerThread data processing to no more than twice the
3297 // expected processing rate.
3298 //
3299 // This helps prevent underruns with NuPlayer and other applications
3300 // which may set up buffers that are close to the minimum size, or use
3301 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3302 //
3303 // The throttle smooths out sudden large data drains from the device,
3304 // e.g. when it comes out of standby, which often causes problems with
3305 // (1) mixer threads without a fast mixer (which has its own warm-up)
3306 // (2) minimum buffer sized tracks (even if the track is full,
3307 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07003308 //
3309 // Total time spent in last processing cycle equals time spent in
3310 // 1. threadLoop_write, as well as time spent in
3311 // 2. threadLoop_mix (significant for heavy mixing, especially
3312 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07003313
Andy Hung69488c42016-05-16 18:43:33 -07003314 // it's OK if deltaMs is an overestimate.
3315 const int32_t deltaMs =
3316 (lastWriteFinished - previousLastWriteFinished) / 1000000;
Andy Hung08fb1742015-05-31 23:22:10 -07003317 const int32_t throttleMs = mHalfBufferMs - deltaMs;
3318 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3319 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003320 // notify of throttle start on verbose log
3321 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3322 "mixer(%p) throttle begin:"
3323 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003324 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003325 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07003326 // Throttle must be attributed to the previous mixer loop's write time
3327 // to allow back-to-back throttling.
3328 lastWriteFinished += throttleMs * 1000000;
Andy Hung40eb1a12015-06-18 13:42:02 -07003329 } else {
3330 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3331 if (diff > 0) {
3332 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07003333 // but prevent spamming for bluetooth
3334 ALOGD_IF(!audio_is_a2dp_out_device(outDevice()),
3335 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07003336 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3337 }
Andy Hung08fb1742015-05-31 23:22:10 -07003338 }
3339 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003340 }
Eric Laurent81784c32012-11-19 14:55:58 -08003341
Eric Laurentbfb1b832013-01-07 09:53:42 -08003342 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003343 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07003344 Mutex::Autolock _l(mLock);
3345 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
3346 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08003347 }
Glenn Kastene7754022014-10-31 12:11:26 -07003348 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003349 }
Eric Laurent81784c32012-11-19 14:55:58 -08003350 }
3351
3352 // Finally let go of removed track(s), without the lock held
3353 // since we can't guarantee the destructors won't acquire that
3354 // same lock. This will also mutate and push a new fast mixer state.
3355 threadLoop_removeTracks(tracksToRemove);
3356 tracksToRemove.clear();
3357
3358 // FIXME I don't understand the need for this here;
3359 // it was in the original code but maybe the
3360 // assignment in saveOutputTracks() makes this unnecessary?
3361 clearOutputTracks();
3362
3363 // Effect chains will be actually deleted here if they were removed from
3364 // mEffectChains list during mixing or effects processing
3365 effectChains.clear();
3366
3367 // FIXME Note that the above .clear() is no longer necessary since effectChains
3368 // is now local to this block, but will keep it for now (at least until merge done).
3369 }
3370
Eric Laurentbfb1b832013-01-07 09:53:42 -08003371 threadLoop_exit();
3372
Eric Laurentcf817a22014-08-04 20:36:31 -07003373 if (!mStandby) {
3374 threadLoop_standby();
3375 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003376 }
3377
3378 releaseWakeLock();
3379
3380 ALOGV("Thread %p type %d exiting", this, mType);
3381 return false;
3382}
3383
Eric Laurentbfb1b832013-01-07 09:53:42 -08003384// removeTracks_l() must be called with ThreadBase::mLock held
3385void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3386{
3387 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003388 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003389 for (size_t i=0 ; i<count ; i++) {
3390 const sp<Track>& track = tracksToRemove.itemAt(i);
3391 mActiveTracks.remove(track);
3392 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3393 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3394 if (chain != 0) {
3395 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3396 track->sessionId());
3397 chain->decActiveTrackCnt();
3398 }
3399 if (track->isTerminated()) {
3400 removeTrack_l(track);
3401 }
3402 }
3403 }
3404
3405}
Eric Laurent81784c32012-11-19 14:55:58 -08003406
Eric Laurentaccc1472013-09-20 09:36:34 -07003407status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3408{
3409 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08003410 ExtendedTimestamp ets;
3411 status_t status = mNormalSink->getTimestamp(ets);
3412 if (status == NO_ERROR) {
3413 status = ets.getBestTimestamp(&timestamp);
3414 }
3415 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07003416 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003417 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003418 uint64_t position64;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003419 if (mOutput->getPresentationPosition(&position64, &timestamp.mTime) == OK) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003420 timestamp.mPosition = (uint32_t)position64;
3421 return NO_ERROR;
3422 }
3423 }
3424 return INVALID_OPERATION;
3425}
Eric Laurent1c333e22014-05-20 10:48:17 -07003426
Eric Laurent054d9d32015-04-24 08:48:48 -07003427status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3428 audio_patch_handle_t *handle)
3429{
Andy Hungf60abce2016-08-26 11:37:54 -07003430 status_t status;
3431 if (property_get_bool("af.patch_park", false /* default_value */)) {
3432 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3433 // or if HAL does not properly lock against access.
3434 AutoPark<FastMixer> park(mFastMixer);
3435 status = PlaybackThread::createAudioPatch_l(patch, handle);
3436 } else {
3437 status = PlaybackThread::createAudioPatch_l(patch, handle);
3438 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003439 return status;
3440}
3441
Eric Laurent1c333e22014-05-20 10:48:17 -07003442status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3443 audio_patch_handle_t *handle)
3444{
3445 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003446
3447 // store new device and send to effects
3448 audio_devices_t type = AUDIO_DEVICE_NONE;
3449 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3450 type |= patch->sinks[i].ext.device.type;
3451 }
3452
3453#ifdef ADD_BATTERY_DATA
3454 // when changing the audio output device, call addBatteryData to notify
3455 // the change
3456 if (mOutDevice != type) {
3457 uint32_t params = 0;
3458 // check whether speaker is on
3459 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3460 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003461 }
3462
Eric Laurent054d9d32015-04-24 08:48:48 -07003463 audio_devices_t deviceWithoutSpeaker
3464 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3465 // check if any other device (except speaker) is on
3466 if (type & deviceWithoutSpeaker) {
3467 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3468 }
3469
3470 if (params != 0) {
3471 addBatteryData(params);
3472 }
3473 }
3474#endif
3475
3476 for (size_t i = 0; i < mEffectChains.size(); i++) {
3477 mEffectChains[i]->setDevice_l(type);
3478 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003479
3480 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3481 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3482 bool configChanged = mPrevOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003483 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003484 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003485
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003486 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003487 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3488 status = hwDevice->createAudioPatch(patch->num_sources,
3489 patch->sources,
3490 patch->num_sinks,
3491 patch->sinks,
3492 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003493 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003494 char *address;
3495 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3496 //FIXME: we only support address on first sink with HAL version < 3.0
3497 address = audio_device_address_to_parameter(
3498 patch->sinks[0].ext.device.type,
3499 patch->sinks[0].ext.device.address);
3500 } else {
3501 address = (char *)calloc(1, 1);
3502 }
3503 AudioParameter param = AudioParameter(String8(address));
3504 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07003505 param.addInt(String8(AudioParameter::keyRouting), (int)type);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003506 status = mOutput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07003507 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003508 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003509 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003510 mPrevOutDevice = type;
Eric Laurente8726fe2015-06-26 09:39:24 -07003511 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3512 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003513 return status;
3514}
3515
Eric Laurent054d9d32015-04-24 08:48:48 -07003516status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3517{
Andy Hungf60abce2016-08-26 11:37:54 -07003518 status_t status;
3519 if (property_get_bool("af.patch_park", false /* default_value */)) {
3520 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3521 // or if HAL does not properly lock against access.
3522 AutoPark<FastMixer> park(mFastMixer);
3523 status = PlaybackThread::releaseAudioPatch_l(handle);
3524 } else {
3525 status = PlaybackThread::releaseAudioPatch_l(handle);
3526 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003527 return status;
3528}
3529
Eric Laurent1c333e22014-05-20 10:48:17 -07003530status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3531{
3532 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003533
3534 mOutDevice = AUDIO_DEVICE_NONE;
3535
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003536 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003537 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3538 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003539 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003540 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07003541 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003542 status = mOutput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07003543 }
3544 return status;
3545}
3546
Eric Laurent83b88082014-06-20 18:31:16 -07003547void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3548{
3549 Mutex::Autolock _l(mLock);
3550 mTracks.add(track);
3551}
3552
3553void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3554{
3555 Mutex::Autolock _l(mLock);
3556 destroyTrack_l(track);
3557}
3558
3559void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3560{
3561 ThreadBase::getAudioPortConfig(config);
3562 config->role = AUDIO_PORT_ROLE_SOURCE;
3563 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3564 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3565}
3566
Eric Laurent81784c32012-11-19 14:55:58 -08003567// ----------------------------------------------------------------------------
3568
3569AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003570 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3571 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003572 // mAudioMixer below
3573 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08003574 mFastMixerFutex(0),
3575 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08003576 // mOutputSink below
3577 // mPipeSink below
3578 // mNormalSink below
3579{
3580 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003581 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%zu, "
3582 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003583 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3584 mNormalFrameCount);
3585 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3586
Andy Hungfbfc3952015-01-15 13:33:51 -08003587 if (type == DUPLICATING) {
3588 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3589 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3590 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3591 return;
3592 }
Eric Laurent81784c32012-11-19 14:55:58 -08003593 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07003594 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08003595 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003596 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003597#if !LOG_NDEBUG
3598 ssize_t index =
3599#else
3600 (void)
3601#endif
3602 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003603 ALOG_ASSERT(index == 0);
3604
3605 // initialize fast mixer depending on configuration
3606 bool initFastMixer;
3607 switch (kUseFastMixer) {
3608 case FastMixer_Never:
3609 initFastMixer = false;
3610 break;
3611 case FastMixer_Always:
3612 initFastMixer = true;
3613 break;
3614 case FastMixer_Static:
3615 case FastMixer_Dynamic:
3616 initFastMixer = mFrameCount < mNormalFrameCount;
3617 break;
3618 }
3619 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003620 audio_format_t fastMixerFormat;
3621 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3622 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3623 } else {
3624 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3625 }
3626 if (mFormat != fastMixerFormat) {
3627 // change our Sink format to accept our intermediate precision
3628 mFormat = fastMixerFormat;
3629 free(mSinkBuffer);
3630 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3631 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3632 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3633 }
Eric Laurent81784c32012-11-19 14:55:58 -08003634
3635 // create a MonoPipe to connect our submix to FastMixer
3636 NBAIO_Format format = mOutputSink->format();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003637#ifdef TEE_SINK
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003638 NBAIO_Format origformat = format;
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003639#endif
Andy Hung1258c1a2014-05-23 21:22:17 -07003640 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07003641 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003642 format.mFormat = fastMixerFormat;
3643 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3644
Eric Laurent81784c32012-11-19 14:55:58 -08003645 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3646 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3647 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3648 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3649 const NBAIO_Format offers[1] = {format};
3650 size_t numCounterOffers = 0;
Glenn Kastenfc302fd2016-04-11 14:11:26 -07003651#if !LOG_NDEBUG || defined(TEE_SINK)
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003652 ssize_t index =
3653#else
3654 (void)
3655#endif
3656 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003657 ALOG_ASSERT(index == 0);
3658 monoPipe->setAvgFrames((mScreenState & 1) ?
3659 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3660 mPipeSink = monoPipe;
3661
Glenn Kasten46909e72013-02-26 09:20:22 -08003662#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003663 if (mTeeSinkOutputEnabled) {
3664 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003665 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3666 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003667 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003668 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003669 ALOG_ASSERT(index == 0);
3670 mTeeSink = teeSink;
3671 PipeReader *teeSource = new PipeReader(*teeSink);
3672 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003673 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003674 ALOG_ASSERT(index == 0);
3675 mTeeSource = teeSource;
3676 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003677#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003678
3679 // create fast mixer and configure it initially with just one fast track for our submix
3680 mFastMixer = new FastMixer();
3681 FastMixerStateQueue *sq = mFastMixer->sq();
3682#ifdef STATE_QUEUE_DUMP
3683 sq->setObserverDump(&mStateQueueObserverDump);
3684 sq->setMutatorDump(&mStateQueueMutatorDump);
3685#endif
3686 FastMixerState *state = sq->begin();
3687 FastTrack *fastTrack = &state->mFastTracks[0];
3688 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3689 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3690 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003691 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3692 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003693 fastTrack->mGeneration++;
3694 state->mFastTracksGen++;
3695 state->mTrackMask = 1;
3696 // fast mixer will use the HAL output sink
3697 state->mOutputSink = mOutputSink.get();
3698 state->mOutputSinkGen++;
3699 state->mFrameCount = mFrameCount;
3700 state->mCommand = FastMixerState::COLD_IDLE;
3701 // already done in constructor initialization list
3702 //mFastMixerFutex = 0;
3703 state->mColdFutexAddr = &mFastMixerFutex;
3704 state->mColdGen++;
3705 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003706#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003707 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003708#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003709 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3710 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003711 sq->end();
3712 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3713
3714 // start the fast mixer
3715 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3716 pid_t tid = mFastMixer->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003717 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003718
3719#ifdef AUDIO_WATCHDOG
3720 // create and start the watchdog
3721 mAudioWatchdog = new AudioWatchdog();
3722 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3723 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3724 tid = mAudioWatchdog->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003725 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003726#endif
3727
Eric Laurent81784c32012-11-19 14:55:58 -08003728 }
3729
3730 switch (kUseFastMixer) {
3731 case FastMixer_Never:
3732 case FastMixer_Dynamic:
3733 mNormalSink = mOutputSink;
3734 break;
3735 case FastMixer_Always:
3736 mNormalSink = mPipeSink;
3737 break;
3738 case FastMixer_Static:
3739 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3740 break;
3741 }
3742}
3743
3744AudioFlinger::MixerThread::~MixerThread()
3745{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003746 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003747 FastMixerStateQueue *sq = mFastMixer->sq();
3748 FastMixerState *state = sq->begin();
3749 if (state->mCommand == FastMixerState::COLD_IDLE) {
3750 int32_t old = android_atomic_inc(&mFastMixerFutex);
3751 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003752 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003753 }
3754 }
3755 state->mCommand = FastMixerState::EXIT;
3756 sq->end();
3757 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3758 mFastMixer->join();
3759 // Though the fast mixer thread has exited, it's state queue is still valid.
3760 // We'll use that extract the final state which contains one remaining fast track
3761 // corresponding to our sub-mix.
3762 state = sq->begin();
3763 ALOG_ASSERT(state->mTrackMask == 1);
3764 FastTrack *fastTrack = &state->mFastTracks[0];
3765 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3766 delete fastTrack->mBufferProvider;
3767 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003768 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003769#ifdef AUDIO_WATCHDOG
3770 if (mAudioWatchdog != 0) {
3771 mAudioWatchdog->requestExit();
3772 mAudioWatchdog->requestExitAndWait();
3773 mAudioWatchdog.clear();
3774 }
3775#endif
3776 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003777 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003778 delete mAudioMixer;
3779}
3780
3781
3782uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3783{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003784 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003785 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3786 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3787 }
3788 return latency;
3789}
3790
3791
3792void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3793{
3794 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3795}
3796
Eric Laurentbfb1b832013-01-07 09:53:42 -08003797ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003798{
3799 // FIXME we should only do one push per cycle; confirm this is true
3800 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003801 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003802 FastMixerStateQueue *sq = mFastMixer->sq();
3803 FastMixerState *state = sq->begin();
3804 if (state->mCommand != FastMixerState::MIX_WRITE &&
3805 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3806 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07003807
3808 // FIXME workaround for first HAL write being CPU bound on some devices
3809 ATRACE_BEGIN("write");
3810 mOutput->write((char *)mSinkBuffer, 0);
3811 ATRACE_END();
3812
Eric Laurent81784c32012-11-19 14:55:58 -08003813 int32_t old = android_atomic_inc(&mFastMixerFutex);
3814 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003815 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003816 }
3817#ifdef AUDIO_WATCHDOG
3818 if (mAudioWatchdog != 0) {
3819 mAudioWatchdog->resume();
3820 }
3821#endif
3822 }
3823 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003824#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003825 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003826 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003827#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003828 sq->end();
3829 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3830 if (kUseFastMixer == FastMixer_Dynamic) {
3831 mNormalSink = mPipeSink;
3832 }
3833 } else {
3834 sq->end(false /*didModify*/);
3835 }
3836 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003837 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003838}
3839
3840void AudioFlinger::MixerThread::threadLoop_standby()
3841{
3842 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003843 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003844 FastMixerStateQueue *sq = mFastMixer->sq();
3845 FastMixerState *state = sq->begin();
3846 if (!(state->mCommand & FastMixerState::IDLE)) {
3847 state->mCommand = FastMixerState::COLD_IDLE;
3848 state->mColdFutexAddr = &mFastMixerFutex;
3849 state->mColdGen++;
3850 mFastMixerFutex = 0;
3851 sq->end();
3852 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3853 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3854 if (kUseFastMixer == FastMixer_Dynamic) {
3855 mNormalSink = mOutputSink;
3856 }
3857#ifdef AUDIO_WATCHDOG
3858 if (mAudioWatchdog != 0) {
3859 mAudioWatchdog->pause();
3860 }
3861#endif
3862 } else {
3863 sq->end(false /*didModify*/);
3864 }
3865 }
3866 PlaybackThread::threadLoop_standby();
3867}
3868
Eric Laurentbfb1b832013-01-07 09:53:42 -08003869bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3870{
3871 return false;
3872}
3873
3874bool AudioFlinger::PlaybackThread::shouldStandby_l()
3875{
3876 return !mStandby;
3877}
3878
3879bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3880{
3881 Mutex::Autolock _l(mLock);
3882 return waitingAsyncCallback_l();
3883}
3884
Eric Laurent81784c32012-11-19 14:55:58 -08003885// shared by MIXER and DIRECT, overridden by DUPLICATING
3886void AudioFlinger::PlaybackThread::threadLoop_standby()
3887{
3888 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08003889 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003890 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003891 // discard any pending drain or write ack by incrementing sequence
3892 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3893 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003894 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003895 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3896 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003897 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003898 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003899}
3900
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003901void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3902{
3903 ALOGV("signal playback thread");
3904 broadcast_l();
3905}
3906
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003907void AudioFlinger::PlaybackThread::onAsyncError()
3908{
3909 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
3910 invalidateTracks((audio_stream_type_t)i);
3911 }
3912}
3913
Eric Laurent81784c32012-11-19 14:55:58 -08003914void AudioFlinger::MixerThread::threadLoop_mix()
3915{
Eric Laurent81784c32012-11-19 14:55:58 -08003916 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08003917 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08003918 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003919 // increase sleep time progressively when application underrun condition clears.
3920 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3921 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3922 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003923 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003924 sleepTimeShift--;
3925 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003926 mSleepTimeUs = 0;
3927 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08003928 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003929
Eric Laurent81784c32012-11-19 14:55:58 -08003930}
3931
3932void AudioFlinger::MixerThread::threadLoop_sleepTime()
3933{
3934 // If no tracks are ready, sleep once for the duration of an output
3935 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003936 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003937 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003938 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
3939 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
3940 mSleepTimeUs = kMinThreadSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003941 }
3942 // reduce sleep time in case of consecutive application underruns to avoid
3943 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3944 // duration we would end up writing less data than needed by the audio HAL if
3945 // the condition persists.
3946 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3947 sleepTimeShift++;
3948 }
3949 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003950 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003951 }
3952 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003953 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3954 // before effects processing or output.
3955 if (mMixerBufferValid) {
3956 memset(mMixerBuffer, 0, mMixerBufferSize);
3957 } else {
3958 memset(mSinkBuffer, 0, mSinkBufferSize);
3959 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003960 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003961 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3962 "anticipated start");
3963 }
3964 // TODO add standby time extension fct of effect tail
3965}
3966
3967// prepareTracks_l() must be called with ThreadBase::mLock held
3968AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3969 Vector< sp<Track> > *tracksToRemove)
3970{
3971
3972 mixer_state mixerStatus = MIXER_IDLE;
3973 // find out which tracks need to be processed
3974 size_t count = mActiveTracks.size();
3975 size_t mixedTracks = 0;
3976 size_t tracksWithEffect = 0;
3977 // counts only _active_ fast tracks
3978 size_t fastTracks = 0;
3979 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3980
3981 float masterVolume = mMasterVolume;
3982 bool masterMute = mMasterMute;
3983
3984 if (masterMute) {
3985 masterVolume = 0;
3986 }
3987 // Delegate master volume control to effect in output mix effect chain if needed
3988 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3989 if (chain != 0) {
3990 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3991 chain->setVolume_l(&v, &v);
3992 masterVolume = (float)((v + (1 << 23)) >> 24);
3993 chain.clear();
3994 }
3995
3996 // prepare a new state to push
3997 FastMixerStateQueue *sq = NULL;
3998 FastMixerState *state = NULL;
3999 bool didModify = false;
4000 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004001 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004002 sq = mFastMixer->sq();
4003 state = sq->begin();
4004 }
4005
Andy Hung69aed5f2014-02-25 17:24:40 -08004006 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08004007 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08004008
Eric Laurent81784c32012-11-19 14:55:58 -08004009 for (size_t i=0 ; i<count ; i++) {
Andy Hung2f366df2016-10-31 14:01:16 -07004010 const sp<Track> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004011
4012 // this const just means the local variable doesn't change
4013 Track* const track = t.get();
4014
4015 // process fast tracks
4016 if (track->isFastTrack()) {
4017
4018 // It's theoretically possible (though unlikely) for a fast track to be created
4019 // and then removed within the same normal mix cycle. This is not a problem, as
4020 // the track never becomes active so it's fast mixer slot is never touched.
4021 // The converse, of removing an (active) track and then creating a new track
4022 // at the identical fast mixer slot within the same normal mix cycle,
4023 // is impossible because the slot isn't marked available until the end of each cycle.
4024 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07004025 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08004026 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
4027 FastTrack *fastTrack = &state->mFastTracks[j];
4028
4029 // Determine whether the track is currently in underrun condition,
4030 // and whether it had a recent underrun.
4031 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
4032 FastTrackUnderruns underruns = ftDump->mUnderruns;
4033 uint32_t recentFull = (underruns.mBitFields.mFull -
4034 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
4035 uint32_t recentPartial = (underruns.mBitFields.mPartial -
4036 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
4037 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
4038 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
4039 uint32_t recentUnderruns = recentPartial + recentEmpty;
4040 track->mObservedUnderruns = underruns;
4041 // don't count underruns that occur while stopping or pausing
4042 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07004043 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
4044 recentUnderruns > 0) {
4045 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
4046 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Phil Burk2812d9e2016-01-04 10:34:30 -08004047 } else {
4048 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Eric Laurent81784c32012-11-19 14:55:58 -08004049 }
4050
4051 // This is similar to the state machine for normal tracks,
4052 // with a few modifications for fast tracks.
4053 bool isActive = true;
4054 switch (track->mState) {
4055 case TrackBase::STOPPING_1:
4056 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08004057 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004058 track->mState = TrackBase::STOPPING_2;
4059 }
4060 break;
4061 case TrackBase::PAUSING:
4062 // ramp down is not yet implemented
4063 track->setPaused();
4064 break;
4065 case TrackBase::RESUMING:
4066 // ramp up is not yet implemented
4067 track->mState = TrackBase::ACTIVE;
4068 break;
4069 case TrackBase::ACTIVE:
4070 if (recentFull > 0 || recentPartial > 0) {
4071 // track has provided at least some frames recently: reset retry count
4072 track->mRetryCount = kMaxTrackRetries;
4073 }
4074 if (recentUnderruns == 0) {
4075 // no recent underruns: stay active
4076 break;
4077 }
4078 // there has recently been an underrun of some kind
4079 if (track->sharedBuffer() == 0) {
4080 // were any of the recent underruns "empty" (no frames available)?
4081 if (recentEmpty == 0) {
4082 // no, then ignore the partial underruns as they are allowed indefinitely
4083 break;
4084 }
4085 // there has recently been an "empty" underrun: decrement the retry counter
4086 if (--(track->mRetryCount) > 0) {
4087 break;
4088 }
4089 // indicate to client process that the track was disabled because of underrun;
4090 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004091 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004092 // remove from active list, but state remains ACTIVE [confusing but true]
4093 isActive = false;
4094 break;
4095 }
4096 // fall through
4097 case TrackBase::STOPPING_2:
4098 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08004099 case TrackBase::STOPPED:
4100 case TrackBase::FLUSHED: // flush() while active
4101 // Check for presentation complete if track is inactive
4102 // We have consumed all the buffers of this track.
4103 // This would be incomplete if we auto-paused on underrun
4104 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004105 uint32_t latency = 0;
4106 status_t result = mOutput->stream->getLatency(&latency);
4107 ALOGE_IF(result != OK,
4108 "Error when retrieving output stream latency: %d", result);
4109 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004110 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004111 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
4112 // track stays in active list until presentation is complete
4113 break;
4114 }
4115 }
4116 if (track->isStopping_2()) {
4117 track->mState = TrackBase::STOPPED;
4118 }
4119 if (track->isStopped()) {
4120 // Can't reset directly, as fast mixer is still polling this track
4121 // track->reset();
4122 // So instead mark this track as needing to be reset after push with ack
4123 resetMask |= 1 << i;
4124 }
4125 isActive = false;
4126 break;
4127 case TrackBase::IDLE:
4128 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08004129 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08004130 }
4131
4132 if (isActive) {
4133 // was it previously inactive?
4134 if (!(state->mTrackMask & (1 << j))) {
4135 ExtendedAudioBufferProvider *eabp = track;
4136 VolumeProvider *vp = track;
4137 fastTrack->mBufferProvider = eabp;
4138 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08004139 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07004140 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08004141 fastTrack->mGeneration++;
4142 state->mTrackMask |= 1 << j;
4143 didModify = true;
4144 // no acknowledgement required for newly active tracks
4145 }
4146 // cache the combined master volume and stream type volume for fast mixer; this
4147 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08004148 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08004149 ++fastTracks;
4150 } else {
4151 // was it previously active?
4152 if (state->mTrackMask & (1 << j)) {
4153 fastTrack->mBufferProvider = NULL;
4154 fastTrack->mGeneration++;
4155 state->mTrackMask &= ~(1 << j);
4156 didModify = true;
4157 // If any fast tracks were removed, we must wait for acknowledgement
4158 // because we're about to decrement the last sp<> on those tracks.
4159 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4160 } else {
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08004161 LOG_ALWAYS_FATAL("fast track %d should have been active; "
4162 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
4163 j, track->mState, state->mTrackMask, recentUnderruns,
4164 track->sharedBuffer() != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004165 }
4166 tracksToRemove->add(track);
4167 // Avoids a misleading display in dumpsys
4168 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
4169 }
4170 continue;
4171 }
4172
4173 { // local variable scope to avoid goto warning
4174
4175 audio_track_cblk_t* cblk = track->cblk();
4176
4177 // The first time a track is added we wait
4178 // for all its buffers to be filled before processing it
4179 int name = track->name();
4180 // make sure that we have enough frames to mix one full buffer.
4181 // enforce this condition only once to enable draining the buffer in case the client
4182 // app does not call stop() and relies on underrun to stop:
4183 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
4184 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004185 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07004186 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004187 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004188
4189 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004190 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004191 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
4192 // add frames already consumed but not yet released by the resampler
4193 // because mAudioTrackServerProxy->framesReady() will include these frames
4194 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
4195
Eric Laurent81784c32012-11-19 14:55:58 -08004196 uint32_t minFrames = 1;
4197 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
4198 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004199 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08004200 }
Eric Laurent13e4c962013-12-20 17:36:01 -08004201
4202 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07004203 if (ATRACE_ENABLED()) {
4204 // I wish we had formatted trace names
4205 char traceName[16];
4206 strcpy(traceName, "nRdy");
4207 int name = track->name();
4208 if (AudioMixer::TRACK0 <= name &&
4209 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
4210 name -= AudioMixer::TRACK0;
4211 traceName[4] = (name / 10) + '0';
4212 traceName[5] = (name % 10) + '0';
4213 } else {
4214 traceName[4] = '?';
4215 traceName[5] = '?';
4216 }
4217 traceName[6] = '\0';
4218 ATRACE_INT(traceName, framesReady);
4219 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004220 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08004221 !track->isPaused() && !track->isTerminated())
4222 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004223 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004224
4225 mixedTracks++;
4226
Andy Hung69aed5f2014-02-25 17:24:40 -08004227 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
4228 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08004229 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08004230 if (track->mainBuffer() != mSinkBuffer &&
4231 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004232 if (mEffectBufferEnabled) {
4233 mEffectBufferValid = true; // Later can set directly.
4234 }
Eric Laurent81784c32012-11-19 14:55:58 -08004235 chain = getEffectChain_l(track->sessionId());
4236 // Delegate volume control to effect in track effect chain if needed
4237 if (chain != 0) {
4238 tracksWithEffect++;
4239 } else {
4240 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
4241 "session %d",
4242 name, track->sessionId());
4243 }
4244 }
4245
4246
4247 int param = AudioMixer::VOLUME;
4248 if (track->mFillingUpStatus == Track::FS_FILLED) {
4249 // no ramp for the first volume setting
4250 track->mFillingUpStatus = Track::FS_ACTIVE;
4251 if (track->mState == TrackBase::RESUMING) {
4252 track->mState = TrackBase::ACTIVE;
4253 param = AudioMixer::RAMP_VOLUME;
4254 }
4255 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004256 // FIXME should not make a decision based on mServer
4257 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004258 // If the track is stopped before the first frame was mixed,
4259 // do not apply ramp
4260 param = AudioMixer::RAMP_VOLUME;
4261 }
4262
4263 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07004264 uint32_t vl, vr; // in U8.24 integer format
4265 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08004266 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07004267 vl = vr = 0;
4268 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08004269 if (track->isPausing()) {
4270 track->setPaused();
4271 }
4272 } else {
4273
4274 // read original volumes with volume control
4275 float typeVolume = mStreamTypes[track->streamType()].volume;
4276 float v = masterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07004277 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004278 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07004279 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
4280 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08004281 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07004282 if (vlf > GAIN_FLOAT_UNITY) {
4283 ALOGV("Track left volume out of range: %.3g", vlf);
4284 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004285 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07004286 if (vrf > GAIN_FLOAT_UNITY) {
4287 ALOGV("Track right volume out of range: %.3g", vrf);
4288 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004289 }
4290 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07004291 vlf *= v;
4292 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08004293 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07004294 // then derive vl and vr as U8.24 versions for the effect chain
4295 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
4296 vl = (uint32_t) (scaleto8_24 * vlf);
4297 vr = (uint32_t) (scaleto8_24 * vrf);
4298 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08004299 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08004300 // send level comes from shared memory and so may be corrupt
4301 if (sendLevel > MAX_GAIN_INT) {
4302 ALOGV("Track send level out of range: %04X", sendLevel);
4303 sendLevel = MAX_GAIN_INT;
4304 }
Andy Hung6be49402014-05-30 10:42:03 -07004305 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4306 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08004307 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004308
Eric Laurent81784c32012-11-19 14:55:58 -08004309 // Delegate volume control to effect in track effect chain if needed
4310 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4311 // Do not ramp volume if volume is controlled by effect
4312 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08004313 // Update remaining floating point volume levels
4314 vlf = (float)vl / (1 << 24);
4315 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004316 track->mHasVolumeController = true;
4317 } else {
4318 // force no volume ramp when volume controller was just disabled or removed
4319 // from effect chain to avoid volume spike
4320 if (track->mHasVolumeController) {
4321 param = AudioMixer::VOLUME;
4322 }
4323 track->mHasVolumeController = false;
4324 }
4325
Eric Laurent81784c32012-11-19 14:55:58 -08004326 // XXX: these things DON'T need to be done each time
4327 mAudioMixer->setBufferProvider(name, track);
4328 mAudioMixer->enable(name);
4329
Andy Hung6be49402014-05-30 10:42:03 -07004330 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
4331 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
4332 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004333 mAudioMixer->setParameter(
4334 name,
4335 AudioMixer::TRACK,
4336 AudioMixer::FORMAT, (void *)track->format());
4337 mAudioMixer->setParameter(
4338 name,
4339 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004340 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004341 mAudioMixer->setParameter(
4342 name,
4343 AudioMixer::TRACK,
4344 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004345 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004346 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004347 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004348 if (reqSampleRate == 0) {
4349 reqSampleRate = mSampleRate;
4350 } else if (reqSampleRate > maxSampleRate) {
4351 reqSampleRate = maxSampleRate;
4352 }
Eric Laurent81784c32012-11-19 14:55:58 -08004353 mAudioMixer->setParameter(
4354 name,
4355 AudioMixer::RESAMPLE,
4356 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004357 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004358
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004359 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004360 mAudioMixer->setParameter(
4361 name,
4362 AudioMixer::TIMESTRETCH,
4363 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004364 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004365
Andy Hung69aed5f2014-02-25 17:24:40 -08004366 /*
4367 * Select the appropriate output buffer for the track.
4368 *
Andy Hung98ef9782014-03-04 14:46:50 -08004369 * Tracks with effects go into their own effects chain buffer
4370 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004371 *
4372 * Other tracks can use mMixerBuffer for higher precision
4373 * channel accumulation. If this buffer is enabled
4374 * (mMixerBufferEnabled true), then selected tracks will accumulate
4375 * into it.
4376 *
4377 */
4378 if (mMixerBufferEnabled
4379 && (track->mainBuffer() == mSinkBuffer
4380 || track->mainBuffer() == mMixerBuffer)) {
4381 mAudioMixer->setParameter(
4382 name,
4383 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004384 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004385 mAudioMixer->setParameter(
4386 name,
4387 AudioMixer::TRACK,
4388 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4389 // TODO: override track->mainBuffer()?
4390 mMixerBufferValid = true;
4391 } else {
4392 mAudioMixer->setParameter(
4393 name,
4394 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004395 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004396 mAudioMixer->setParameter(
4397 name,
4398 AudioMixer::TRACK,
4399 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4400 }
Eric Laurent81784c32012-11-19 14:55:58 -08004401 mAudioMixer->setParameter(
4402 name,
4403 AudioMixer::TRACK,
4404 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4405
4406 // reset retry count
4407 track->mRetryCount = kMaxTrackRetries;
4408
4409 // If one track is ready, set the mixer ready if:
4410 // - the mixer was not ready during previous round OR
4411 // - no other track is not ready
4412 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4413 mixerStatus != MIXER_TRACKS_ENABLED) {
4414 mixerStatus = MIXER_TRACKS_READY;
4415 }
4416 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004417 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hung08fb1742015-05-31 23:22:10 -07004418 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)",
4419 track, framesReady, desiredFrames);
Glenn Kasten82aaf942013-07-17 16:05:07 -07004420 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08004421 } else {
4422 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004423 }
Phil Burk2812d9e2016-01-04 10:34:30 -08004424
Eric Laurent81784c32012-11-19 14:55:58 -08004425 // clear effect chain input buffer if an active track underruns to avoid sending
4426 // previous audio buffer again to effects
4427 chain = getEffectChain_l(track->sessionId());
4428 if (chain != 0) {
4429 chain->clearInputBuffer();
4430 }
4431
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004432 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004433 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4434 track->isStopped() || track->isPaused()) {
4435 // We have consumed all the buffers of this track.
4436 // Remove it from the list of active tracks.
4437 // TODO: use actual buffer filling status instead of latency when available from
4438 // audio HAL
4439 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004440 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004441 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4442 if (track->isStopped()) {
4443 track->reset();
4444 }
4445 tracksToRemove->add(track);
4446 }
4447 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004448 // No buffers for this track. Give it a few chances to
4449 // fill a buffer, then remove it from active list.
4450 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004451 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004452 tracksToRemove->add(track);
4453 // indicate to client process that the track was disabled because of underrun;
4454 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004455 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004456 // If one track is not ready, mark the mixer also not ready if:
4457 // - the mixer was ready during previous round OR
4458 // - no other track is ready
4459 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4460 mixerStatus != MIXER_TRACKS_READY) {
4461 mixerStatus = MIXER_TRACKS_ENABLED;
4462 }
4463 }
4464 mAudioMixer->disable(name);
4465 }
4466
4467 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08004468
4469 }
4470
4471 // Push the new FastMixer state if necessary
4472 bool pauseAudioWatchdog = false;
4473 if (didModify) {
4474 state->mFastTracksGen++;
4475 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4476 if (kUseFastMixer == FastMixer_Dynamic &&
4477 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4478 state->mCommand = FastMixerState::COLD_IDLE;
4479 state->mColdFutexAddr = &mFastMixerFutex;
4480 state->mColdGen++;
4481 mFastMixerFutex = 0;
4482 if (kUseFastMixer == FastMixer_Dynamic) {
4483 mNormalSink = mOutputSink;
4484 }
4485 // If we go into cold idle, need to wait for acknowledgement
4486 // so that fast mixer stops doing I/O.
4487 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4488 pauseAudioWatchdog = true;
4489 }
Eric Laurent81784c32012-11-19 14:55:58 -08004490 }
4491 if (sq != NULL) {
4492 sq->end(didModify);
4493 sq->push(block);
4494 }
4495#ifdef AUDIO_WATCHDOG
4496 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4497 mAudioWatchdog->pause();
4498 }
4499#endif
4500
4501 // Now perform the deferred reset on fast tracks that have stopped
4502 while (resetMask != 0) {
4503 size_t i = __builtin_ctz(resetMask);
4504 ALOG_ASSERT(i < count);
4505 resetMask &= ~(1 << i);
Andy Hung2f366df2016-10-31 14:01:16 -07004506 sp<Track> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004507 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4508 track->reset();
4509 }
4510
4511 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004512 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004513
Eric Laurent97d547d2014-09-02 14:45:53 -07004514 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4515 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004516 }
4517
4518 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004519 // as long as there are effects we should clear the effects buffer, to avoid
4520 // passing a non-clean buffer to the effect chain
4521 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004522 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004523 // sink or mix buffer must be cleared if all tracks are connected to an
4524 // effect chain as in this case the mixer will not write to the sink or mix buffer
4525 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004526 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4527 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004528 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004529 if (mMixerBufferValid) {
4530 memset(mMixerBuffer, 0, mMixerBufferSize);
4531 // TODO: In testing, mSinkBuffer below need not be cleared because
4532 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4533 // after mixing.
4534 //
4535 // To enforce this guarantee:
4536 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4537 // (mixedTracks == 0 && fastTracks > 0))
4538 // must imply MIXER_TRACKS_READY.
4539 // Later, we may clear buffers regardless, and skip much of this logic.
4540 }
Andy Hung98ef9782014-03-04 14:46:50 -08004541 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004542 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004543 }
4544
4545 // if any fast tracks, then status is ready
4546 mMixerStatusIgnoringFastTracks = mixerStatus;
4547 if (fastTracks > 0) {
4548 mixerStatus = MIXER_TRACKS_READY;
4549 }
4550 return mixerStatus;
4551}
4552
Eric Laurentad7dd962016-09-22 12:38:37 -07004553// trackCountForUid_l() must be called with ThreadBase::mLock held
4554uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid)
4555{
4556 uint32_t trackCount = 0;
4557 for (size_t i = 0; i < mTracks.size() ; i++) {
4558 if (mTracks[i]->uid() == (int)uid) {
4559 trackCount++;
4560 }
4561 }
4562 return trackCount;
4563}
4564
Eric Laurent81784c32012-11-19 14:55:58 -08004565// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07004566int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
Eric Laurentad7dd962016-09-22 12:38:37 -07004567 audio_format_t format, audio_session_t sessionId, uid_t uid)
Eric Laurent81784c32012-11-19 14:55:58 -08004568{
Eric Laurentad7dd962016-09-22 12:38:37 -07004569 if (trackCountForUid_l(uid) > (PlaybackThread::kMaxTracksPerUid - 1)) {
4570 return -1;
4571 }
Andy Hunge8a1ced2014-05-09 15:02:21 -07004572 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08004573}
4574
4575// deleteTrackName_l() must be called with ThreadBase::mLock held
4576void AudioFlinger::MixerThread::deleteTrackName_l(int name)
4577{
4578 ALOGV("remove track (%d) and delete from mixer", name);
4579 mAudioMixer->deleteTrackName(name);
4580}
4581
Eric Laurent10351942014-05-08 18:49:52 -07004582// checkForNewParameter_l() must be called with ThreadBase::mLock held
4583bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4584 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004585{
Eric Laurent81784c32012-11-19 14:55:58 -08004586 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08004587 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004588
Eric Laurent10351942014-05-08 18:49:52 -07004589 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004590
Glenn Kastenc05b8d72016-03-24 09:48:17 -07004591 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004592
Eric Laurent10351942014-05-08 18:49:52 -07004593 AudioParameter param = AudioParameter(keyValuePair);
4594 int value;
4595 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4596 reconfig = true;
4597 }
4598 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004599 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004600 status = BAD_VALUE;
4601 } else {
4602 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004603 reconfig = true;
4604 }
Eric Laurent10351942014-05-08 18:49:52 -07004605 }
4606 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004607 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004608 status = BAD_VALUE;
4609 } else {
4610 // no need to save value, since it's constant
4611 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004612 }
Eric Laurent10351942014-05-08 18:49:52 -07004613 }
4614 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4615 // do not accept frame count changes if tracks are open as the track buffer
4616 // size depends on frame count and correct behavior would not be guaranteed
4617 // if frame count is changed after track creation
4618 if (!mTracks.isEmpty()) {
4619 status = INVALID_OPERATION;
4620 } else {
4621 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004622 }
Eric Laurent10351942014-05-08 18:49:52 -07004623 }
4624 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004625#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004626 // when changing the audio output device, call addBatteryData to notify
4627 // the change
4628 if (mOutDevice != value) {
4629 uint32_t params = 0;
4630 // check whether speaker is on
4631 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4632 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004633 }
Eric Laurent10351942014-05-08 18:49:52 -07004634
4635 audio_devices_t deviceWithoutSpeaker
4636 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4637 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07004638 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07004639 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4640 }
4641
4642 if (params != 0) {
4643 addBatteryData(params);
4644 }
4645 }
Eric Laurent81784c32012-11-19 14:55:58 -08004646#endif
4647
Eric Laurent10351942014-05-08 18:49:52 -07004648 // forward device change to effects that have requested to be
4649 // aware of attached audio device.
4650 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08004651 a2dpDeviceChanged =
4652 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07004653 mOutDevice = value;
4654 for (size_t i = 0; i < mEffectChains.size(); i++) {
4655 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004656 }
4657 }
Eric Laurent10351942014-05-08 18:49:52 -07004658 }
Eric Laurent81784c32012-11-19 14:55:58 -08004659
Eric Laurent10351942014-05-08 18:49:52 -07004660 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004661 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07004662 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004663 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004664 mStandby = true;
4665 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004666 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08004667 }
Eric Laurent10351942014-05-08 18:49:52 -07004668 if (status == NO_ERROR && reconfig) {
4669 readOutputParameters_l();
4670 delete mAudioMixer;
4671 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4672 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004673 int name = getTrackName_l(mTracks[i]->mChannelMask,
Eric Laurentad7dd962016-09-22 12:38:37 -07004674 mTracks[i]->mFormat, mTracks[i]->mSessionId, mTracks[i]->uid());
Eric Laurent10351942014-05-08 18:49:52 -07004675 if (name < 0) {
4676 break;
4677 }
4678 mTracks[i]->mName = name;
4679 }
Eric Laurent73e26b62015-04-27 16:55:58 -07004680 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004681 }
Eric Laurent81784c32012-11-19 14:55:58 -08004682 }
4683
Eric Laurent42537be2016-01-08 17:16:42 -08004684 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08004685}
4686
4687
4688void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4689{
Eric Laurent81784c32012-11-19 14:55:58 -08004690 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07004691 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Elliott Hughes87cebad2014-05-22 10:14:43 -07004692 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Andy Hung2ddee192015-12-18 17:34:44 -08004693 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent81784c32012-11-19 14:55:58 -08004694
4695 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten2f90c512015-12-02 11:40:09 -08004696 // while we are dumping it. It may be inconsistent, but it won't mutate!
4697 // This is a large object so we place it on the heap.
4698 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
4699 const FastMixerDumpState *copy = new FastMixerDumpState(mFastMixerDumpState);
4700 copy->dump(fd);
4701 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08004702
4703#ifdef STATE_QUEUE_DUMP
4704 // Similar for state queue
4705 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4706 observerCopy.dump(fd);
4707 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4708 mutatorCopy.dump(fd);
4709#endif
4710
Glenn Kasten46909e72013-02-26 09:20:22 -08004711#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004712 // Write the tee output to a .wav file
4713 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08004714#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004715
4716#ifdef AUDIO_WATCHDOG
4717 if (mAudioWatchdog != 0) {
4718 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4719 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4720 wdCopy.dump(fd);
4721 }
4722#endif
4723}
4724
4725uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4726{
4727 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4728}
4729
4730uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4731{
4732 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4733}
4734
4735void AudioFlinger::MixerThread::cacheParameters_l()
4736{
4737 PlaybackThread::cacheParameters_l();
4738
4739 // FIXME: Relaxed timing because of a certain device that can't meet latency
4740 // Should be reduced to 2x after the vendor fixes the driver issue
4741 // increase threshold again due to low power audio mode. The way this warning
4742 // threshold is calculated and its usefulness should be reconsidered anyway.
4743 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4744}
4745
4746// ----------------------------------------------------------------------------
4747
4748AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07004749 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady)
4750 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08004751 // mLeftVolFloat, mRightVolFloat
4752{
4753}
4754
Eric Laurentbfb1b832013-01-07 09:53:42 -08004755AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4756 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurente93cc032016-05-05 10:15:10 -07004757 ThreadBase::type_t type, bool systemReady)
4758 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004759 // mLeftVolFloat, mRightVolFloat
4760{
4761}
4762
Eric Laurent81784c32012-11-19 14:55:58 -08004763AudioFlinger::DirectOutputThread::~DirectOutputThread()
4764{
4765}
4766
Eric Laurentbfb1b832013-01-07 09:53:42 -08004767void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
4768{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004769 float left, right;
4770
4771 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4772 left = right = 0;
4773 } else {
4774 float typeVolume = mStreamTypes[track->streamType()].volume;
4775 float v = mMasterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07004776 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004777 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4778 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4779 if (left > GAIN_FLOAT_UNITY) {
4780 left = GAIN_FLOAT_UNITY;
4781 }
4782 left *= v;
4783 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4784 if (right > GAIN_FLOAT_UNITY) {
4785 right = GAIN_FLOAT_UNITY;
4786 }
4787 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004788 }
4789
4790 if (lastTrack) {
4791 if (left != mLeftVolFloat || right != mRightVolFloat) {
4792 mLeftVolFloat = left;
4793 mRightVolFloat = right;
4794
4795 // Convert volumes from float to 8.24
4796 uint32_t vl = (uint32_t)(left * (1 << 24));
4797 uint32_t vr = (uint32_t)(right * (1 << 24));
4798
4799 // Delegate volume control to effect in track effect chain if needed
4800 // only one effect chain can be present on DirectOutputThread, so if
4801 // there is one, the track is connected to it
4802 if (!mEffectChains.isEmpty()) {
4803 mEffectChains[0]->setVolume_l(&vl, &vr);
4804 left = (float)vl / (1 << 24);
4805 right = (float)vr / (1 << 24);
4806 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004807 status_t result = mOutput->stream->setVolume(left, right);
4808 ALOGE_IF(result != OK, "Error when setting output stream volume: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004809 }
4810 }
4811}
4812
Phil Burk43b4dcc2015-06-09 16:53:44 -07004813void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
4814{
4815 sp<Track> previousTrack = mPreviousTrack.promote();
Andy Hung2f366df2016-10-31 14:01:16 -07004816 sp<Track> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004817
Eric Laurent0f0631e2015-07-06 18:01:25 -07004818 if (previousTrack != 0 && latestTrack != 0) {
4819 if (mType == DIRECT) {
4820 if (previousTrack.get() != latestTrack.get()) {
4821 mFlushPending = true;
4822 }
4823 } else /* mType == OFFLOAD */ {
4824 if (previousTrack->sessionId() != latestTrack->sessionId()) {
4825 mFlushPending = true;
4826 }
4827 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004828 }
4829 PlaybackThread::onAddNewTrack_l();
4830}
Eric Laurentbfb1b832013-01-07 09:53:42 -08004831
Eric Laurent81784c32012-11-19 14:55:58 -08004832AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4833 Vector< sp<Track> > *tracksToRemove
4834)
4835{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004836 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004837 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004838 bool doHwPause = false;
4839 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004840
4841 // find out which tracks need to be processed
Andy Hung2f366df2016-10-31 14:01:16 -07004842 for (const sp<Track> &t : mActiveTracks) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004843 if (t->isInvalid()) {
4844 ALOGW("An invalidated track shouldn't be in active list");
4845 tracksToRemove->add(t);
4846 continue;
4847 }
4848
Eric Laurent81784c32012-11-19 14:55:58 -08004849 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004850#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08004851 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004852#endif
Eric Laurentfd477972013-10-25 18:10:40 -07004853 // Only consider last track started for volume and mixer state control.
4854 // In theory an older track could underrun and restart after the new one starts
4855 // but as we only care about the transition phase between two tracks on a
4856 // direct output, it is not a problem to ignore the underrun case.
Andy Hung2f366df2016-10-31 14:01:16 -07004857 sp<Track> l = mActiveTracks.getLatest();
Eric Laurentfd477972013-10-25 18:10:40 -07004858 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004859
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004860 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004861 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004862 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004863 doHwPause = true;
4864 mHwPaused = true;
4865 }
4866 tracksToRemove->add(track);
4867 } else if (track->isFlushPending()) {
4868 track->flushAck();
4869 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004870 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004871 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004872 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004873 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07004874 if (last) {
4875 mLeftVolFloat = mRightVolFloat = -1.0;
4876 if (mHwPaused) {
4877 doHwResume = true;
4878 mHwPaused = false;
4879 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004880 }
4881 }
4882
Eric Laurent81784c32012-11-19 14:55:58 -08004883 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004884 // for all its buffers to be filled before processing it.
4885 // Allow draining the buffer in case the client
4886 // app does not call stop() and relies on underrun to stop:
4887 // hence the test on (track->mRetryCount > 1).
4888 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07004889 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08004890 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004891 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08004892 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004893 minFrames = mNormalFrameCount;
4894 } else {
4895 minFrames = 1;
4896 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004897
Eric Laurentab5cdba2014-06-09 17:22:27 -07004898 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4899 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004900 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004901 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004902
4903 if (track->mFillingUpStatus == Track::FS_FILLED) {
4904 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07004905 if (last) {
4906 // make sure processVolume_l() will apply new volume even if 0
4907 mLeftVolFloat = mRightVolFloat = -1.0;
4908 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004909 if (!mHwSupportsPause) {
4910 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004911 }
4912 }
4913
4914 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004915 processVolume_l(track, last);
4916 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004917 sp<Track> previousTrack = mPreviousTrack.promote();
4918 if (previousTrack != 0) {
4919 if (track != previousTrack.get()) {
4920 // Flush any data still being written from last track
4921 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07004922 // Invalidate previous track to force a seek when resuming.
4923 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004924 }
4925 }
4926 mPreviousTrack = track;
4927
Eric Laurentd595b7c2013-04-03 17:27:56 -07004928 // reset retry count
4929 track->mRetryCount = kMaxTrackRetriesDirect;
4930 mActiveTrack = t;
4931 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07004932 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004933 doHwResume = true;
4934 mHwPaused = false;
4935 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004936 }
Eric Laurent81784c32012-11-19 14:55:58 -08004937 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004938 // clear effect chain input buffer if the last active track started underruns
4939 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004940 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004941 mEffectChains[0]->clearInputBuffer();
4942 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004943 if (track->isStopping_1()) {
4944 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07004945 if (last && mHwPaused) {
4946 doHwResume = true;
4947 mHwPaused = false;
4948 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004949 }
4950 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4951 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004952 // We have consumed all the buffers of this track.
4953 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004954 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08004955 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004956 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4957 } else {
4958 audioHALFrames = 0;
4959 }
4960
Andy Hung818e7a32016-02-16 18:08:07 -08004961 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004962 if (mStandby || !last ||
4963 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004964 if (track->isStopping_2()) {
4965 track->mState = TrackBase::STOPPED;
4966 }
Eric Laurent81784c32012-11-19 14:55:58 -08004967 if (track->isStopped()) {
4968 track->reset();
4969 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004970 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004971 }
4972 } else {
4973 // No buffers for this track. Give it a few chances to
4974 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004975 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004976 if (--(track->mRetryCount) <= 0) {
4977 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004978 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004979 // indicate to client process that the track was disabled because of underrun;
4980 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004981 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004982 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07004983 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
4984 "minFrames = %u, mFormat = %#x",
4985 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08004986 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07004987 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004988 doHwPause = true;
4989 mHwPaused = true;
4990 }
Eric Laurent81784c32012-11-19 14:55:58 -08004991 }
4992 }
4993 }
4994 }
4995
Eric Laurentd1f69b02014-12-15 14:33:13 -08004996 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07004997 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004998 for (size_t i = 0; i < mTracks.size(); i++) {
4999 if (mTracks[i]->isFlushPending()) {
5000 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005001 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005002 }
5003 }
5004 }
5005
5006 // make sure the pause/flush/resume sequence is executed in the right order.
5007 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5008 // before flush and then resume HW. This can happen in case of pause/flush/resume
5009 // if resume is received before pause is executed.
5010 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07005011 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005012 status_t result = mOutput->stream->pause();
5013 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005014 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005015 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005016 flushHw_l();
5017 }
5018 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005019 status_t result = mOutput->stream->resume();
5020 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005021 }
Eric Laurent81784c32012-11-19 14:55:58 -08005022 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005023 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005024
5025 return mixerStatus;
5026}
5027
5028void AudioFlinger::DirectOutputThread::threadLoop_mix()
5029{
Eric Laurent81784c32012-11-19 14:55:58 -08005030 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08005031 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005032 // output audio to hardware
5033 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07005034 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005035 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08005036 status_t status = mActiveTrack->getNextBuffer(&buffer);
5037 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08005038 // no need to pad with 0 for compressed audio
5039 if (audio_has_proportional_frames(mFormat)) {
5040 memset(curBuf, 0, frameCount * mFrameSize);
5041 }
Eric Laurent81784c32012-11-19 14:55:58 -08005042 break;
5043 }
5044 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
5045 frameCount -= buffer.frameCount;
5046 curBuf += buffer.frameCount * mFrameSize;
5047 mActiveTrack->releaseBuffer(&buffer);
5048 }
Andy Hung2098f272014-02-27 14:00:06 -08005049 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005050 mSleepTimeUs = 0;
5051 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005052 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005053}
5054
5055void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
5056{
Eric Laurentd1f69b02014-12-15 14:33:13 -08005057 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005058 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005059 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005060 return;
5061 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005062 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005063 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurente93cc032016-05-05 10:15:10 -07005064 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005065 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005066 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005067 }
Phil Burkfdb3c072016-02-09 10:47:02 -08005068 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08005069 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005070 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005071 }
5072}
5073
Eric Laurentd1f69b02014-12-15 14:33:13 -08005074void AudioFlinger::DirectOutputThread::threadLoop_exit()
5075{
5076 {
5077 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005078 for (size_t i = 0; i < mTracks.size(); i++) {
5079 if (mTracks[i]->isFlushPending()) {
5080 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005081 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005082 }
5083 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005084 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005085 flushHw_l();
5086 }
5087 }
5088 PlaybackThread::threadLoop_exit();
5089}
5090
5091// must be called with thread mutex locked
5092bool AudioFlinger::DirectOutputThread::shouldStandby_l()
5093{
5094 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07005095 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005096
vivek mehta9cd7ad12016-03-17 00:18:29 -07005097 if ((mType == DIRECT) && audio_is_linear_pcm(mFormat) && !usesHwAvSync()) {
5098 return !mStandby;
5099 }
5100
Eric Laurentd1f69b02014-12-15 14:33:13 -08005101 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
5102 // after a timeout and we will enter standby then.
5103 if (mTracks.size() > 0) {
5104 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07005105 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
5106 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005107 }
5108
Eric Laurent5cff4032015-05-26 13:49:58 -07005109 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08005110}
5111
Eric Laurent81784c32012-11-19 14:55:58 -08005112// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005113int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Eric Laurentad7dd962016-09-22 12:38:37 -07005114 audio_format_t format __unused, audio_session_t sessionId __unused, uid_t uid)
Eric Laurent81784c32012-11-19 14:55:58 -08005115{
Eric Laurentad7dd962016-09-22 12:38:37 -07005116 if (trackCountForUid_l(uid) > (PlaybackThread::kMaxTracksPerUid - 1)) {
5117 return -1;
5118 }
Eric Laurent81784c32012-11-19 14:55:58 -08005119 return 0;
5120}
5121
5122// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005123void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005124{
5125}
5126
Eric Laurent10351942014-05-08 18:49:52 -07005127// checkForNewParameter_l() must be called with ThreadBase::mLock held
5128bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
5129 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005130{
5131 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005132 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005133
Eric Laurent10351942014-05-08 18:49:52 -07005134 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005135
Eric Laurent10351942014-05-08 18:49:52 -07005136 AudioParameter param = AudioParameter(keyValuePair);
5137 int value;
5138 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5139 // forward device change to effects that have requested to be
5140 // aware of attached audio device.
5141 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005142 a2dpDeviceChanged =
5143 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005144 mOutDevice = value;
5145 for (size_t i = 0; i < mEffectChains.size(); i++) {
5146 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07005147 }
5148 }
Eric Laurent81784c32012-11-19 14:55:58 -08005149 }
Eric Laurent10351942014-05-08 18:49:52 -07005150 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5151 // do not accept frame count changes if tracks are open as the track buffer
5152 // size depends on frame count and correct behavior would not be garantied
5153 // if frame count is changed after track creation
5154 if (!mTracks.isEmpty()) {
5155 status = INVALID_OPERATION;
5156 } else {
5157 reconfig = true;
5158 }
5159 }
5160 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005161 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005162 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005163 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005164 mStandby = true;
5165 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005166 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005167 }
5168 if (status == NO_ERROR && reconfig) {
5169 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07005170 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005171 }
5172 }
5173
Eric Laurent42537be2016-01-08 17:16:42 -08005174 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005175}
5176
5177uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
5178{
5179 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005180 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005181 time = PlaybackThread::activeSleepTimeUs();
5182 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005183 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005184 }
5185 return time;
5186}
5187
5188uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
5189{
5190 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005191 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005192 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
5193 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005194 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005195 }
5196 return time;
5197}
5198
5199uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
5200{
5201 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005202 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005203 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
5204 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005205 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005206 }
5207 return time;
5208}
5209
5210void AudioFlinger::DirectOutputThread::cacheParameters_l()
5211{
5212 PlaybackThread::cacheParameters_l();
5213
5214 // use shorter standby delay as on normal output to release
5215 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07005216 // no delay on outputs with HW A/V sync
5217 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005218 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08005219 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005220 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07005221 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005222 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07005223 }
Eric Laurent81784c32012-11-19 14:55:58 -08005224}
5225
Eric Laurente659ef42014-09-29 13:06:46 -07005226void AudioFlinger::DirectOutputThread::flushHw_l()
5227{
Phil Burk062e67a2015-02-11 13:40:50 -08005228 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08005229 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005230 mFlushPending = false;
Eric Laurente659ef42014-09-29 13:06:46 -07005231}
5232
Eric Laurent81784c32012-11-19 14:55:58 -08005233// ----------------------------------------------------------------------------
5234
Eric Laurentbfb1b832013-01-07 09:53:42 -08005235AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07005236 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005237 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07005238 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07005239 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005240 mDrainSequence(0),
5241 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005242{
5243}
5244
5245AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
5246{
5247}
5248
5249void AudioFlinger::AsyncCallbackThread::onFirstRef()
5250{
5251 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
5252}
5253
5254bool AudioFlinger::AsyncCallbackThread::threadLoop()
5255{
5256 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005257 uint32_t writeAckSequence;
5258 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005259 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005260
5261 {
5262 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005263 while (!((mWriteAckSequence & 1) ||
5264 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005265 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005266 exitPending())) {
5267 mWaitWorkCV.wait(mLock);
5268 }
5269
Eric Laurentbfb1b832013-01-07 09:53:42 -08005270 if (exitPending()) {
5271 break;
5272 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005273 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
5274 mWriteAckSequence, mDrainSequence);
5275 writeAckSequence = mWriteAckSequence;
5276 mWriteAckSequence &= ~1;
5277 drainSequence = mDrainSequence;
5278 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005279 asyncError = mAsyncError;
5280 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005281 }
5282 {
Eric Laurent4de95592013-09-26 15:28:21 -07005283 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
5284 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005285 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005286 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005287 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005288 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005289 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005290 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005291 if (asyncError) {
5292 playbackThread->onAsyncError();
5293 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005294 }
5295 }
5296 }
5297 return false;
5298}
5299
5300void AudioFlinger::AsyncCallbackThread::exit()
5301{
5302 ALOGV("AsyncCallbackThread::exit");
5303 Mutex::Autolock _l(mLock);
5304 requestExit();
5305 mWaitWorkCV.broadcast();
5306}
5307
Eric Laurent3b4529e2013-09-05 18:09:19 -07005308void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005309{
5310 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005311 // bit 0 is cleared
5312 mWriteAckSequence = sequence << 1;
5313}
5314
5315void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5316{
5317 Mutex::Autolock _l(mLock);
5318 // ignore unexpected callbacks
5319 if (mWriteAckSequence & 2) {
5320 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005321 mWaitWorkCV.signal();
5322 }
5323}
5324
Eric Laurent3b4529e2013-09-05 18:09:19 -07005325void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005326{
5327 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005328 // bit 0 is cleared
5329 mDrainSequence = sequence << 1;
5330}
5331
5332void AudioFlinger::AsyncCallbackThread::resetDraining()
5333{
5334 Mutex::Autolock _l(mLock);
5335 // ignore unexpected callbacks
5336 if (mDrainSequence & 2) {
5337 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005338 mWaitWorkCV.signal();
5339 }
5340}
5341
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005342void AudioFlinger::AsyncCallbackThread::setAsyncError()
5343{
5344 Mutex::Autolock _l(mLock);
5345 mAsyncError = true;
5346 mWaitWorkCV.signal();
5347}
5348
Eric Laurentbfb1b832013-01-07 09:53:42 -08005349
5350// ----------------------------------------------------------------------------
5351AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07005352 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
5353 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07005354 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
5355 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005356{
Eric Laurentfd477972013-10-25 18:10:40 -07005357 //FIXME: mStandby should be set to true by ThreadBase constructor
5358 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07005359 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005360}
5361
Eric Laurentbfb1b832013-01-07 09:53:42 -08005362void AudioFlinger::OffloadThread::threadLoop_exit()
5363{
5364 if (mFlushPending || mHwPaused) {
5365 // If a flush is pending or track was paused, just discard buffered data
5366 flushHw_l();
5367 } else {
5368 mMixerStatus = MIXER_DRAIN_ALL;
5369 threadLoop_drain();
5370 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005371 if (mUseAsyncWrite) {
5372 ALOG_ASSERT(mCallbackThread != 0);
5373 mCallbackThread->exit();
5374 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005375 PlaybackThread::threadLoop_exit();
5376}
5377
5378AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5379 Vector< sp<Track> > *tracksToRemove
5380)
5381{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005382 size_t count = mActiveTracks.size();
5383
5384 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005385 bool doHwPause = false;
5386 bool doHwResume = false;
5387
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005388 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07005389
Eric Laurentbfb1b832013-01-07 09:53:42 -08005390 // find out which tracks need to be processed
Andy Hung2f366df2016-10-31 14:01:16 -07005391 for (const sp<Track> &t : mActiveTracks) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005392 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005393#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08005394 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005395#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005396 // Only consider last track started for volume and mixer state control.
5397 // In theory an older track could underrun and restart after the new one starts
5398 // but as we only care about the transition phase between two tracks on a
5399 // direct output, it is not a problem to ignore the underrun case.
Andy Hung2f366df2016-10-31 14:01:16 -07005400 sp<Track> l = mActiveTracks.getLatest();
Eric Laurentfd477972013-10-25 18:10:40 -07005401 bool last = l.get() == track;
5402
Haynes Mathew George7844f672014-01-15 12:32:55 -08005403 if (track->isInvalid()) {
5404 ALOGW("An invalidated track shouldn't be in active list");
5405 tracksToRemove->add(track);
5406 continue;
5407 }
5408
5409 if (track->mState == TrackBase::IDLE) {
5410 ALOGW("An idle track shouldn't be in active list");
5411 continue;
5412 }
5413
Eric Laurentbfb1b832013-01-07 09:53:42 -08005414 if (track->isPausing()) {
5415 track->setPaused();
5416 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005417 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005418 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005419 mHwPaused = true;
5420 }
5421 // If we were part way through writing the mixbuffer to
5422 // the HAL we must save this until we resume
5423 // BUG - this will be wrong if a different track is made active,
5424 // in that case we want to discard the pending data in the
5425 // mixbuffer and tell the client to present it again when the
5426 // track is resumed
5427 mPausedWriteLength = mCurrentWriteLength;
5428 mPausedBytesRemaining = mBytesRemaining;
5429 mBytesRemaining = 0; // stop writing
5430 }
5431 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005432 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005433 if (track->isStopping_1()) {
5434 track->mRetryCount = kMaxTrackStopRetriesOffload;
5435 } else {
5436 track->mRetryCount = kMaxTrackRetriesOffload;
5437 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08005438 track->flushAck();
5439 if (last) {
5440 mFlushPending = true;
5441 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005442 } else if (track->isResumePending()){
5443 track->resumeAck();
5444 if (last) {
5445 if (mPausedBytesRemaining) {
5446 // Need to continue write that was interrupted
5447 mCurrentWriteLength = mPausedWriteLength;
5448 mBytesRemaining = mPausedBytesRemaining;
5449 mPausedBytesRemaining = 0;
5450 }
5451 if (mHwPaused) {
5452 doHwResume = true;
5453 mHwPaused = false;
5454 // threadLoop_mix() will handle the case that we need to
5455 // resume an interrupted write
5456 }
5457 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005458 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005459
Eric Laurent3df841a2016-07-15 15:15:40 -07005460 mLeftVolFloat = mRightVolFloat = -1.0;
5461
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005462 // Do not handle new data in this iteration even if track->framesReady()
5463 mixerStatus = MIXER_TRACKS_ENABLED;
5464 }
5465 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005466 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005467 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005468 if (track->mFillingUpStatus == Track::FS_FILLED) {
5469 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005470 if (last) {
5471 // make sure processVolume_l() will apply new volume even if 0
5472 mLeftVolFloat = mRightVolFloat = -1.0;
5473 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005474 }
5475
5476 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005477 sp<Track> previousTrack = mPreviousTrack.promote();
5478 if (previousTrack != 0) {
5479 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005480 // Flush any data still being written from last track
5481 mBytesRemaining = 0;
5482 if (mPausedBytesRemaining) {
5483 // Last track was paused so we also need to flush saved
5484 // mixbuffer state and invalidate track so that it will
5485 // re-submit that unwritten data when it is next resumed
5486 mPausedBytesRemaining = 0;
5487 // Invalidate is a bit drastic - would be more efficient
5488 // to have a flag to tell client that some of the
5489 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005490 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005491 }
5492 // flush data already sent to the DSP if changing audio session as audio
5493 // comes from a different source. Also invalidate previous track to force a
5494 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005495 if (previousTrack->sessionId() != track->sessionId()) {
5496 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005497 }
5498 }
5499 }
5500 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005501 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07005502 if (track->isStopping_1()) {
5503 track->mRetryCount = kMaxTrackStopRetriesOffload;
5504 } else {
5505 track->mRetryCount = kMaxTrackRetriesOffload;
5506 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005507 mActiveTrack = t;
5508 mixerStatus = MIXER_TRACKS_READY;
5509 }
5510 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005511 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005512 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005513 if (--(track->mRetryCount) <= 0) {
5514 // Hardware buffer can hold a large amount of audio so we must
5515 // wait for all current track's data to drain before we say
5516 // that the track is stopped.
5517 if (mBytesRemaining == 0) {
5518 // Only start draining when all data in mixbuffer
5519 // has been written
5520 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5521 track->mState = TrackBase::STOPPING_2; // so presentation completes after
5522 // drain do not drain if no data was ever sent to HAL (mStandby == true)
5523 if (last && !mStandby) {
5524 // do not modify drain sequence if we are already draining. This happens
5525 // when resuming from pause after drain.
5526 if ((mDrainSequence & 1) == 0) {
5527 mSleepTimeUs = 0;
5528 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
5529 mixerStatus = MIXER_DRAIN_TRACK;
5530 mDrainSequence += 2;
5531 }
5532 if (mHwPaused) {
5533 // It is possible to move from PAUSED to STOPPING_1 without
5534 // a resume so we must ensure hardware is running
5535 doHwResume = true;
5536 mHwPaused = false;
5537 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005538 }
5539 }
Eric Laurente93cc032016-05-05 10:15:10 -07005540 } else if (last) {
5541 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
5542 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005543 }
5544 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005545 // Drain has completed or we are in standby, signal presentation complete
5546 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005547 track->mState = TrackBase::STOPPED;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005548 uint32_t latency = 0;
5549 status_t result = mOutput->stream->getLatency(&latency);
5550 ALOGE_IF(result != OK,
5551 "Error when retrieving output stream latency: %d", result);
5552 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005553 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005554 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005555 track->presentationComplete(framesWritten, audioHALFrames);
5556 track->reset();
5557 tracksToRemove->add(track);
5558 }
5559 } else {
5560 // No buffers for this track. Give it a few chances to
5561 // fill a buffer, then remove it from active list.
5562 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07005563 bool running = false;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005564 uint64_t position = 0;
5565 struct timespec unused;
5566 // The running check restarts the retry counter at least once.
5567 status_t ret = mOutput->stream->getPresentationPosition(&position, &unused);
5568 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
5569 running = true;
5570 mOffloadUnderrunPosition = position;
5571 }
5572 if (ret == NO_ERROR) {
Andy Hungf8044752016-07-27 14:58:11 -07005573 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
5574 (long long)position, (long long)mOffloadUnderrunPosition);
5575 }
5576 if (running) { // still running, give us more time.
5577 track->mRetryCount = kMaxTrackRetriesOffload;
5578 } else {
5579 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5580 track->name());
5581 tracksToRemove->add(track);
5582 // indicate to client process that the track was disabled because of underrun;
5583 // it will then automatically call start() when data is available
5584 track->disable();
5585 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005586 } else if (last){
5587 mixerStatus = MIXER_TRACKS_ENABLED;
5588 }
5589 }
5590 }
5591 // compute volume for this track
5592 processVolume_l(track, last);
5593 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005594
Eric Laurentea0fade2013-10-04 16:23:48 -07005595 // make sure the pause/flush/resume sequence is executed in the right order.
5596 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5597 // before flush and then resume HW. This can happen in case of pause/flush/resume
5598 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07005599 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005600 status_t result = mOutput->stream->pause();
5601 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07005602 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005603 if (mFlushPending) {
5604 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005605 }
Eric Laurentfd477972013-10-25 18:10:40 -07005606 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005607 status_t result = mOutput->stream->resume();
5608 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07005609 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005610
Eric Laurentbfb1b832013-01-07 09:53:42 -08005611 // remove all the tracks that need to be...
5612 removeTracks_l(*tracksToRemove);
5613
5614 return mixerStatus;
5615}
5616
Eric Laurentbfb1b832013-01-07 09:53:42 -08005617// must be called with thread mutex locked
5618bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5619{
Eric Laurent3b4529e2013-09-05 18:09:19 -07005620 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5621 mWriteAckSequence, mDrainSequence);
5622 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005623 return true;
5624 }
5625 return false;
5626}
5627
Eric Laurentbfb1b832013-01-07 09:53:42 -08005628bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5629{
5630 Mutex::Autolock _l(mLock);
5631 return waitingAsyncCallback_l();
5632}
5633
5634void AudioFlinger::OffloadThread::flushHw_l()
5635{
Eric Laurente659ef42014-09-29 13:06:46 -07005636 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005637 // Flush anything still waiting in the mixbuffer
5638 mCurrentWriteLength = 0;
5639 mBytesRemaining = 0;
5640 mPausedWriteLength = 0;
5641 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07005642 // reset bytes written count to reflect that DSP buffers are empty after flush.
5643 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07005644 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08005645
Eric Laurentbfb1b832013-01-07 09:53:42 -08005646 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005647 // discard any pending drain or write ack by incrementing sequence
5648 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5649 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005650 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005651 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5652 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005653 }
5654}
5655
Haynes Mathew George05317d22016-05-03 16:34:26 -07005656void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
5657{
5658 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07005659 if (PlaybackThread::invalidateTracks_l(streamType)) {
5660 mFlushPending = true;
5661 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07005662}
5663
Eric Laurentbfb1b832013-01-07 09:53:42 -08005664// ----------------------------------------------------------------------------
5665
Eric Laurent81784c32012-11-19 14:55:58 -08005666AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005667 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005668 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07005669 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08005670 mWaitTimeMs(UINT_MAX)
5671{
5672 addOutputTrack(mainThread);
5673}
5674
5675AudioFlinger::DuplicatingThread::~DuplicatingThread()
5676{
5677 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5678 mOutputTracks[i]->destroy();
5679 }
5680}
5681
5682void AudioFlinger::DuplicatingThread::threadLoop_mix()
5683{
5684 // mix buffers...
5685 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08005686 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08005687 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005688 if (mMixerBufferValid) {
5689 memset(mMixerBuffer, 0, mMixerBufferSize);
5690 } else {
5691 memset(mSinkBuffer, 0, mSinkBufferSize);
5692 }
Eric Laurent81784c32012-11-19 14:55:58 -08005693 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005694 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005695 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005696 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005697 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005698}
5699
5700void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5701{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005702 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005703 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005704 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005705 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005706 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005707 }
5708 } else if (mBytesWritten != 0) {
5709 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5710 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005711 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005712 } else {
5713 // flush remaining overflow buffers in output tracks
5714 writeFrames = 0;
5715 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005716 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005717 }
5718}
5719
Eric Laurentbfb1b832013-01-07 09:53:42 -08005720ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005721{
5722 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005723 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005724 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005725 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005726 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005727}
5728
5729void AudioFlinger::DuplicatingThread::threadLoop_standby()
5730{
5731 // DuplicatingThread implements standby by stopping all tracks
5732 for (size_t i = 0; i < outputTracks.size(); i++) {
5733 outputTracks[i]->stop();
5734 }
5735}
5736
5737void AudioFlinger::DuplicatingThread::saveOutputTracks()
5738{
5739 outputTracks = mOutputTracks;
5740}
5741
5742void AudioFlinger::DuplicatingThread::clearOutputTracks()
5743{
5744 outputTracks.clear();
5745}
5746
5747void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5748{
5749 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005750 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5751 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5752 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5753 const size_t frameCount =
5754 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5755 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5756 // from different OutputTracks and their associated MixerThreads (e.g. one may
5757 // nearly empty and the other may be dropping data).
5758
5759 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005760 this,
5761 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005762 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005763 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005764 frameCount,
5765 IPCThreadState::self()->getCallingUid());
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07005766 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
5767 if (status != NO_ERROR) {
5768 ALOGE("addOutputTrack() initCheck failed %d", status);
5769 return;
Eric Laurent81784c32012-11-19 14:55:58 -08005770 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07005771 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
5772 mOutputTracks.add(outputTrack);
5773 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
5774 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005775}
5776
5777void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5778{
5779 Mutex::Autolock _l(mLock);
5780 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5781 if (mOutputTracks[i]->thread() == thread) {
5782 mOutputTracks[i]->destroy();
5783 mOutputTracks.removeAt(i);
5784 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07005785 if (thread->getOutput() == mOutput) {
5786 mOutput = NULL;
5787 }
Eric Laurent81784c32012-11-19 14:55:58 -08005788 return;
5789 }
5790 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07005791 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005792}
5793
5794// caller must hold mLock
5795void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5796{
5797 mWaitTimeMs = UINT_MAX;
5798 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5799 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5800 if (strong != 0) {
5801 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5802 if (waitTimeMs < mWaitTimeMs) {
5803 mWaitTimeMs = waitTimeMs;
5804 }
5805 }
5806 }
5807}
5808
5809
5810bool AudioFlinger::DuplicatingThread::outputsReady(
5811 const SortedVector< sp<OutputTrack> > &outputTracks)
5812{
5813 for (size_t i = 0; i < outputTracks.size(); i++) {
5814 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5815 if (thread == 0) {
5816 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5817 outputTracks[i].get());
5818 return false;
5819 }
5820 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5821 // see note at standby() declaration
5822 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5823 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5824 thread.get());
5825 return false;
5826 }
5827 }
5828 return true;
5829}
5830
5831uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5832{
5833 return (mWaitTimeMs * 1000) / 2;
5834}
5835
5836void AudioFlinger::DuplicatingThread::cacheParameters_l()
5837{
5838 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5839 updateWaitTime_l();
5840
5841 MixerThread::cacheParameters_l();
5842}
5843
5844// ----------------------------------------------------------------------------
5845// Record
5846// ----------------------------------------------------------------------------
5847
5848AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5849 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005850 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005851 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07005852 audio_devices_t inDevice,
5853 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08005854#ifdef TEE_SINK
5855 , const sp<NBAIO_Sink>& teeSink
5856#endif
5857 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07005858 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Andy Hung2f366df2016-10-31 14:01:16 -07005859 mInput(input), mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07005860 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005861 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005862#ifdef TEE_SINK
5863 , mTeeSink(teeSink)
5864#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005865 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5866 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005867 // mFastCapture below
5868 , mFastCaptureFutex(0)
5869 // mInputSource
5870 // mPipeSink
5871 // mPipeSource
5872 , mPipeFramesP2(0)
5873 // mPipeMemory
5874 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005875 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005876{
Glenn Kastend7dca052015-03-05 16:05:54 -08005877 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5878 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08005879
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005880 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005881
5882 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07005883 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005884 size_t numCounterOffers = 0;
5885 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005886#if !LOG_NDEBUG
5887 ssize_t index =
5888#else
5889 (void)
5890#endif
5891 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005892 ALOG_ASSERT(index == 0);
5893
5894 // initialize fast capture depending on configuration
5895 bool initFastCapture;
5896 switch (kUseFastCapture) {
5897 case FastCapture_Never:
5898 initFastCapture = false;
5899 break;
5900 case FastCapture_Always:
5901 initFastCapture = true;
5902 break;
5903 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07005904 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005905 break;
5906 // case FastCapture_Dynamic:
5907 }
5908
5909 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07005910 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005911 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07005912 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
5913 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005914 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5915 void *pipeBuffer;
5916 const sp<MemoryDealer> roHeap(readOnlyHeap());
5917 sp<IMemory> pipeMemory;
5918 if ((roHeap == 0) ||
5919 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5920 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5921 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5922 goto failed;
5923 }
5924 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5925 memset(pipeBuffer, 0, pipeSize);
5926 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5927 const NBAIO_Format offers[1] = {format};
5928 size_t numCounterOffers = 0;
5929 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5930 ALOG_ASSERT(index == 0);
5931 mPipeSink = pipe;
5932 PipeReader *pipeReader = new PipeReader(*pipe);
5933 numCounterOffers = 0;
5934 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5935 ALOG_ASSERT(index == 0);
5936 mPipeSource = pipeReader;
5937 mPipeFramesP2 = pipeFramesP2;
5938 mPipeMemory = pipeMemory;
5939
5940 // create fast capture
5941 mFastCapture = new FastCapture();
5942 FastCaptureStateQueue *sq = mFastCapture->sq();
5943#ifdef STATE_QUEUE_DUMP
5944 // FIXME
5945#endif
5946 FastCaptureState *state = sq->begin();
5947 state->mCblk = NULL;
5948 state->mInputSource = mInputSource.get();
5949 state->mInputSourceGen++;
5950 state->mPipeSink = pipe;
5951 state->mPipeSinkGen++;
5952 state->mFrameCount = mFrameCount;
5953 state->mCommand = FastCaptureState::COLD_IDLE;
5954 // already done in constructor initialization list
5955 //mFastCaptureFutex = 0;
5956 state->mColdFutexAddr = &mFastCaptureFutex;
5957 state->mColdGen++;
5958 state->mDumpState = &mFastCaptureDumpState;
5959#ifdef TEE_SINK
5960 // FIXME
5961#endif
5962 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
5963 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
5964 sq->end();
5965 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5966
5967 // start the fast capture
5968 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
5969 pid_t tid = mFastCapture->getTid();
Glenn Kasten8379b722016-03-18 14:54:17 -07005970 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005971#ifdef AUDIO_WATCHDOG
5972 // FIXME
5973#endif
5974
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005975 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005976 }
5977failed: ;
5978
5979 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08005980}
5981
Eric Laurent81784c32012-11-19 14:55:58 -08005982AudioFlinger::RecordThread::~RecordThread()
5983{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005984 if (mFastCapture != 0) {
5985 FastCaptureStateQueue *sq = mFastCapture->sq();
5986 FastCaptureState *state = sq->begin();
5987 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5988 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5989 if (old == -1) {
5990 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5991 }
5992 }
5993 state->mCommand = FastCaptureState::EXIT;
5994 sq->end();
5995 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5996 mFastCapture->join();
5997 mFastCapture.clear();
5998 }
5999 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07006000 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07006001 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08006002}
6003
6004void AudioFlinger::RecordThread::onFirstRef()
6005{
Glenn Kastend7dca052015-03-05 16:05:54 -08006006 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08006007}
6008
Eric Laurent81784c32012-11-19 14:55:58 -08006009bool AudioFlinger::RecordThread::threadLoop()
6010{
Eric Laurent81784c32012-11-19 14:55:58 -08006011 nsecs_t lastWarning = 0;
6012
6013 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006014
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006015reacquire_wakelock:
6016 sp<RecordTrack> activeTrack;
6017 {
6018 Mutex::Autolock _l(mLock);
Andy Hung2f366df2016-10-31 14:01:16 -07006019 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006020 }
6021
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006022 // used to request a deferred sleep, to be executed later while mutex is unlocked
6023 uint32_t sleepUs = 0;
6024
6025 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006026 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006027 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07006028
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006029 // activeTracks accumulates a copy of a subset of mActiveTracks
6030 Vector< sp<RecordTrack> > activeTracks;
6031
Glenn Kasten735f45f2014-08-18 15:51:59 -07006032 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006033 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07006034
Glenn Kasten735f45f2014-08-18 15:51:59 -07006035 // reference to a fast track which is about to be removed
6036 sp<RecordTrack> fastTrackToRemove;
6037
Eric Laurent81784c32012-11-19 14:55:58 -08006038 { // scope for mLock
6039 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08006040
Eric Laurent021cf962014-05-13 10:18:14 -07006041 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006042
Eric Laurent000a4192014-01-29 15:17:32 -08006043 // check exitPending here because checkForNewParameters_l() and
6044 // checkForNewParameters_l() can temporarily release mLock
6045 if (exitPending()) {
6046 break;
6047 }
6048
Eric Laurent5c25d562016-07-13 17:17:45 -07006049 // sleep with mutex unlocked
6050 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07006051 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07006052 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
6053 ATRACE_END();
6054 sleepUs = 0;
6055 continue;
6056 }
6057
Glenn Kasten2b806402013-11-20 16:37:38 -08006058 // if no active track(s), then standby and release wakelock
6059 size_t size = mActiveTracks.size();
6060 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07006061 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006062 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08006063 releaseWakeLock_l();
6064 ALOGV("RecordThread: loop stopping");
6065 // go to sleep
6066 mWaitWorkCV.wait(mLock);
6067 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006068 goto reacquire_wakelock;
6069 }
6070
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006071 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07006072 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006073 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07006074
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006075 activeTrack = mActiveTracks[i];
6076 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07006077 if (activeTrack->isFastTrack()) {
6078 ALOG_ASSERT(fastTrackToRemove == 0);
6079 fastTrackToRemove = activeTrack;
6080 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006081 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08006082 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006083 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07006084 continue;
6085 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006086
6087 TrackBase::track_state activeTrackState = activeTrack->mState;
6088 switch (activeTrackState) {
6089
6090 case TrackBase::PAUSING:
6091 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006092 doBroadcast = true;
6093 size--;
6094 continue;
6095
6096 case TrackBase::STARTING_1:
6097 sleepUs = 10000;
6098 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07006099 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006100 continue;
6101
6102 case TrackBase::STARTING_2:
6103 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006104 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07006105 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07006106 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006107 break;
6108
6109 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07006110 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006111 break;
6112
6113 case TrackBase::IDLE:
6114 i++;
6115 continue;
6116
6117 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08006118 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07006119 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006120
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006121 activeTracks.add(activeTrack);
6122 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07006123
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006124 if (activeTrack->isFastTrack()) {
6125 ALOG_ASSERT(!mFastTrackAvail);
6126 ALOG_ASSERT(fastTrack == 0);
6127 fastTrack = activeTrack;
6128 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006129 }
Eric Laurent5c25d562016-07-13 17:17:45 -07006130
Andy Hung2f366df2016-10-31 14:01:16 -07006131 mActiveTracks.updateWakeLockUids(this);
6132
Eric Laurent5c25d562016-07-13 17:17:45 -07006133 if (allStopped) {
6134 standbyIfNotAlreadyInStandby();
6135 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006136 if (doBroadcast) {
6137 mStartStopCond.broadcast();
6138 }
6139
6140 // sleep if there are no active tracks to process
6141 if (activeTracks.size() == 0) {
6142 if (sleepUs == 0) {
6143 sleepUs = kRecordThreadSleepUs;
6144 }
6145 continue;
6146 }
6147 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07006148
Eric Laurent81784c32012-11-19 14:55:58 -08006149 lockEffectChains_l(effectChains);
6150 }
6151
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006152 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07006153
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006154 size_t size = effectChains.size();
6155 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006156 // thread mutex is not locked, but effect chain is locked
6157 effectChains[i]->process_l();
6158 }
6159
Glenn Kasten735f45f2014-08-18 15:51:59 -07006160 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006161 if (mFastCapture != 0) {
6162 FastCaptureStateQueue *sq = mFastCapture->sq();
6163 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07006164 bool didModify = false;
6165 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006166 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
6167 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
6168 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6169 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6170 if (old == -1) {
6171 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6172 }
6173 }
6174 state->mCommand = FastCaptureState::READ_WRITE;
6175#if 0 // FIXME
6176 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08006177 FastThreadDumpState::kSamplingNforLowRamDevice :
6178 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006179#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07006180 didModify = true;
6181 }
6182 audio_track_cblk_t *cblkOld = state->mCblk;
6183 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
6184 if (cblkNew != cblkOld) {
6185 state->mCblk = cblkNew;
6186 // block until acked if removing a fast track
6187 if (cblkOld != NULL) {
6188 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
6189 }
6190 didModify = true;
6191 }
6192 sq->end(didModify);
6193 if (didModify) {
6194 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006195#if 0
6196 if (kUseFastCapture == FastCapture_Dynamic) {
6197 mNormalSource = mPipeSource;
6198 }
6199#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006200 }
6201 }
6202
Glenn Kasten735f45f2014-08-18 15:51:59 -07006203 // now run the fast track destructor with thread mutex unlocked
6204 fastTrackToRemove.clear();
6205
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006206 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
6207 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
6208 // slow, then this RecordThread will overrun by not calling HAL read often enough.
6209 // If destination is non-contiguous, first read past the nominal end of buffer, then
6210 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006211
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006212 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006213 ssize_t framesRead;
6214
6215 // If an NBAIO source is present, use it to read the normal capture's data
6216 if (mPipeSource != 0) {
6217 size_t framesToRead = mBufferSize / mFrameSize;
Glenn Kasten1b291842016-07-18 14:55:21 -07006218 framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hung57446612015-04-19 23:56:46 -07006219 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
Glenn Kastend79072e2016-01-06 08:41:20 -08006220 framesToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07006221 // since pipe is non-blocking, simulate blocking input by waiting for 1/2 of
6222 // buffer size or at least for 20ms.
6223 size_t sleepFrames = max(
6224 min(mPipeFramesP2, mRsmpInFramesP2) / 2, FMS_20 * mSampleRate / 1000);
6225 if (framesRead <= (ssize_t) sleepFrames) {
6226 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
6227 }
6228 if (framesRead < 0) {
6229 status_t status = (status_t) framesRead;
6230 switch (status) {
6231 case OVERRUN:
6232 ALOGW("overrun on read from pipe");
6233 framesRead = 0;
6234 break;
6235 case NEGOTIATE:
6236 ALOGE("re-negotiation is needed");
6237 framesRead = -1; // Will cause an attempt to recover.
6238 break;
6239 default:
6240 ALOGE("unknown error %d on read from pipe", status);
6241 break;
6242 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006243 }
6244 // otherwise use the HAL / AudioStreamIn directly
6245 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07006246 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006247 size_t bytesRead;
6248 status_t result = mInput->stream->read(
6249 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07006250 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006251 if (result < 0) {
6252 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006253 } else {
6254 framesRead = bytesRead / mFrameSize;
6255 }
6256 }
6257
Andy Hung3f0c9022016-01-15 17:49:46 -08006258 // Update server timestamp with server stats
6259 // systemTime() is optional if the hardware supports timestamps.
6260 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
6261 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6262
6263 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006264 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08006265 int64_t position, time;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006266 int ret = mInput->stream->getCapturePosition(&position, &time);
Andy Hung3f0c9022016-01-15 17:49:46 -08006267 if (ret == NO_ERROR) {
6268 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
6269 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
6270 // Note: In general record buffers should tend to be empty in
6271 // a properly running pipeline.
6272 //
6273 // Also, it is not advantageous to call get_presentation_position during the read
6274 // as the read obtains a lock, preventing the timestamp call from executing.
6275 }
6276 }
6277 // Use this to track timestamp information
6278 // ALOGD("%s", mTimestamp.toString().c_str());
6279
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006280 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006281 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006282 // Force input into standby so that it tries to recover at next read attempt
6283 inputStandBy();
6284 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006285 }
6286 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006287 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006288 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006289 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006290
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006291 if (mTeeSink != 0) {
Andy Hung57446612015-04-19 23:56:46 -07006292 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006293 }
6294 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006295 {
6296 size_t part1 = mRsmpInFramesP2 - rear;
6297 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07006298 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006299 (framesRead - part1) * mFrameSize);
6300 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006301 }
6302 rear = mRsmpInRear += framesRead;
6303
6304 size = activeTracks.size();
6305 // loop over each active track
6306 for (size_t i = 0; i < size; i++) {
6307 activeTrack = activeTracks[i];
6308
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006309 // skip fast tracks, as those are handled directly by FastCapture
6310 if (activeTrack->isFastTrack()) {
6311 continue;
6312 }
6313
Andy Hung73c02e42015-03-29 01:13:58 -07006314 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07006315 // TODO: Update the activeTrack buffer converter in case of reconfigure.
6316
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006317 enum {
6318 OVERRUN_UNKNOWN,
6319 OVERRUN_TRUE,
6320 OVERRUN_FALSE
6321 } overrun = OVERRUN_UNKNOWN;
6322
6323 // loop over getNextBuffer to handle circular sink
6324 for (;;) {
6325
6326 activeTrack->mSink.frameCount = ~0;
6327 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
6328 size_t framesOut = activeTrack->mSink.frameCount;
6329 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
6330
Andy Hung73c02e42015-03-29 01:13:58 -07006331 // check available frames and handle overrun conditions
6332 // if the record track isn't draining fast enough.
6333 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006334 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07006335 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
6336 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006337 overrun = OVERRUN_TRUE;
6338 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006339 if (framesOut == 0 || framesIn == 0) {
6340 break;
6341 }
6342
Andy Hung6770c6f2015-04-07 13:43:36 -07006343 // Don't allow framesOut to be larger than what is possible with resampling
6344 // from framesIn.
6345 // This isn't strictly necessary but helps limit buffer resizing in
6346 // RecordBufferConverter. TODO: remove when no longer needed.
6347 framesOut = min(framesOut,
6348 destinationFramesPossible(
6349 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07006350 // process frames from the RecordThread buffer provider to the RecordTrack buffer
6351 framesOut = activeTrack->mRecordBufferConverter->convert(
6352 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006353
6354 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
6355 overrun = OVERRUN_FALSE;
6356 }
6357
6358 if (activeTrack->mFramesToDrop == 0) {
6359 if (framesOut > 0) {
6360 activeTrack->mSink.frameCount = framesOut;
6361 activeTrack->releaseBuffer(&activeTrack->mSink);
6362 }
6363 } else {
6364 // FIXME could do a partial drop of framesOut
6365 if (activeTrack->mFramesToDrop > 0) {
6366 activeTrack->mFramesToDrop -= framesOut;
6367 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006368 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006369 }
6370 } else {
6371 activeTrack->mFramesToDrop += framesOut;
6372 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
6373 activeTrack->mSyncStartEvent->isCancelled()) {
6374 ALOGW("Synced record %s, session %d, trigger session %d",
6375 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
6376 activeTrack->sessionId(),
6377 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08006378 activeTrack->mSyncStartEvent->triggerSession() :
6379 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006380 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006381 }
6382 }
6383 }
6384
6385 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006386 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006387 }
6388 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006389
6390 switch (overrun) {
6391 case OVERRUN_TRUE:
6392 // client isn't retrieving buffers fast enough
6393 if (!activeTrack->setOverflow()) {
6394 nsecs_t now = systemTime();
6395 // FIXME should lastWarning per track?
6396 if ((now - lastWarning) > kWarningThrottleNs) {
6397 ALOGW("RecordThread: buffer overflow");
6398 lastWarning = now;
6399 }
6400 }
6401 break;
6402 case OVERRUN_FALSE:
6403 activeTrack->clearOverflow();
6404 break;
6405 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006406 break;
6407 }
6408
Andy Hung3f0c9022016-01-15 17:49:46 -08006409 // update frame information and push timestamp out
6410 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08006411 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08006412 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
6413 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006414 }
6415
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006416unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08006417 // enable changes in effect chain
6418 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006419 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08006420 }
6421
Glenn Kasten93e471f2013-08-19 08:40:07 -07006422 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08006423
6424 {
6425 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07006426 for (size_t i = 0; i < mTracks.size(); i++) {
6427 sp<RecordTrack> track = mTracks[i];
6428 track->invalidate();
6429 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006430 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006431 mStartStopCond.broadcast();
6432 }
6433
6434 releaseWakeLock();
6435
6436 ALOGV("RecordThread %p exiting", this);
6437 return false;
6438}
6439
Glenn Kasten93e471f2013-08-19 08:40:07 -07006440void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08006441{
6442 if (!mStandby) {
6443 inputStandBy();
6444 mStandby = true;
6445 }
6446}
6447
6448void AudioFlinger::RecordThread::inputStandBy()
6449{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006450 // Idle the fast capture if it's currently running
6451 if (mFastCapture != 0) {
6452 FastCaptureStateQueue *sq = mFastCapture->sq();
6453 FastCaptureState *state = sq->begin();
6454 if (!(state->mCommand & FastCaptureState::IDLE)) {
6455 state->mCommand = FastCaptureState::COLD_IDLE;
6456 state->mColdFutexAddr = &mFastCaptureFutex;
6457 state->mColdGen++;
6458 mFastCaptureFutex = 0;
6459 sq->end();
6460 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
6461 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
6462#if 0
6463 if (kUseFastCapture == FastCapture_Dynamic) {
6464 // FIXME
6465 }
6466#endif
6467#ifdef AUDIO_WATCHDOG
6468 // FIXME
6469#endif
6470 } else {
6471 sq->end(false /*didModify*/);
6472 }
6473 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006474 status_t result = mInput->stream->standby();
6475 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07006476
6477 // If going into standby, flush the pipe source.
6478 if (mPipeSource.get() != nullptr) {
6479 const ssize_t flushed = mPipeSource->flush();
6480 if (flushed > 0) {
6481 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
6482 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
6483 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6484 }
6485 }
Eric Laurent81784c32012-11-19 14:55:58 -08006486}
6487
Glenn Kasten05997e22014-03-13 15:08:33 -07006488// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07006489sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08006490 const sp<AudioFlinger::Client>& client,
6491 uint32_t sampleRate,
6492 audio_format_t format,
6493 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08006494 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08006495 audio_session_t sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07006496 size_t *notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006497 int uid,
Eric Laurent05067782016-06-01 18:27:28 -07006498 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08006499 pid_t tid,
6500 status_t *status)
6501{
Glenn Kasten74935e42013-12-19 08:56:45 -08006502 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08006503 sp<RecordTrack> track;
6504 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07006505 audio_input_flags_t inputFlags = mInput->flags;
6506
6507 // special case for FAST flag considered OK if fast capture is present
6508 if (hasFastCapture()) {
6509 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
6510 }
6511
6512 // Check if requested flags are compatible with output stream flags
6513 if ((*flags & inputFlags) != *flags) {
6514 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
6515 " input flags (%08x)",
6516 *flags, inputFlags);
6517 *flags = (audio_input_flags_t)(*flags & inputFlags);
6518 }
Eric Laurent81784c32012-11-19 14:55:58 -08006519
Glenn Kasten90e58b12013-07-31 16:16:02 -07006520 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07006521 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006522 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07006523 // we formerly checked for a callback handler (non-0 tid),
6524 // but that is no longer required for TRANSFER_OBTAIN mode
6525 //
Glenn Kasten74105912014-07-03 12:28:53 -07006526 // frame count is not specified, or is exactly the pipe depth
6527 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006528 // PCM data
6529 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006530 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006531 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006532 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006533 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006534 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07006535 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006536 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006537 hasFastCapture() &&
6538 // there are sufficient fast track slots available
6539 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07006540 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07006541 // check compatibility with audio effects.
6542 Mutex::Autolock _l(mLock);
6543 // Do not accept FAST flag if the session has software effects
6544 sp<EffectChain> chain = getEffectChain_l(sessionId);
6545 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07006546 audio_input_flags_t old = *flags;
6547 chain->checkInputFlagCompatibility(flags);
6548 if (old != *flags) {
6549 ALOGV("AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
6550 (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07006551 }
6552 }
Eric Laurent122f7e72016-06-29 11:53:29 -07006553 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07006554 "AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
6555 frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006556 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006557 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
Glenn Kasten74105912014-07-03 12:28:53 -07006558 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006559 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07006560 frameCount, mFrameCount, mPipeFramesP2,
6561 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
6562 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07006563 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07006564 }
6565 }
6566
6567 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07006568 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07006569 // fast track: frame count is exactly the pipe depth
6570 frameCount = mPipeFramesP2;
6571 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
6572 *notificationFrames = mFrameCount;
6573 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006574 // not fast track: max notification period is resampled equivalent of one HAL buffer time
6575 // or 20 ms if there is a fast capture
6576 // TODO This could be a roundupRatio inline, and const
6577 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
6578 * sampleRate + mSampleRate - 1) / mSampleRate;
6579 // minimum number of notification periods is at least kMinNotifications,
6580 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
6581 static const size_t kMinNotifications = 3;
6582 static const uint32_t kMinMs = 30;
6583 // TODO This could be a roundupRatio inline
6584 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
6585 // TODO This could be a roundupRatio inline
6586 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
6587 maxNotificationFrames;
6588 const size_t minFrameCount = maxNotificationFrames *
6589 max(kMinNotifications, minNotificationsByMs);
6590 frameCount = max(frameCount, minFrameCount);
6591 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
6592 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07006593 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07006594 }
Glenn Kasten74935e42013-12-19 08:56:45 -08006595 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07006596
Glenn Kasten15e57982013-09-24 11:52:37 -07006597 lStatus = initCheck();
6598 if (lStatus != NO_ERROR) {
6599 ALOGE("createRecordTrack_l() audio driver not initialized");
6600 goto Exit;
6601 }
Eric Laurent81784c32012-11-19 14:55:58 -08006602
6603 { // scope for mLock
6604 Mutex::Autolock _l(mLock);
6605
6606 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07006607 format, channelMask, frameCount, NULL, sessionId, uid,
6608 *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08006609
Glenn Kasten03003332013-08-06 15:40:54 -07006610 lStatus = track->initCheck();
6611 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07006612 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08006613 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08006614 goto Exit;
6615 }
6616 mTracks.add(track);
6617
6618 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6619 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6620 mAudioFlinger->btNrecIsOff();
6621 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6622 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006623
Eric Laurent05067782016-06-01 18:27:28 -07006624 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006625 pid_t callingPid = IPCThreadState::self()->getCallingPid();
6626 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
6627 // so ask activity manager to do this on our behalf
6628 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
6629 }
Eric Laurent81784c32012-11-19 14:55:58 -08006630 }
Glenn Kasten05997e22014-03-13 15:08:33 -07006631
Eric Laurent81784c32012-11-19 14:55:58 -08006632 lStatus = NO_ERROR;
6633
6634Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07006635 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08006636 return track;
6637}
6638
6639status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6640 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08006641 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08006642{
6643 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6644 sp<ThreadBase> strongMe = this;
6645 status_t status = NO_ERROR;
6646
6647 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006648 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006649 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006650 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08006651 triggerSession,
6652 recordTrack->sessionId(),
6653 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006654 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08006655 // Sync event can be cancelled by the trigger session if the track is not in a
6656 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006657 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006658 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006659 } else {
6660 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006661 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006662 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08006663 }
6664 }
6665
6666 {
Glenn Kasten47c20702013-08-13 15:37:35 -07006667 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08006668 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006669 if (mActiveTracks.indexOf(recordTrack) >= 0) {
6670 if (recordTrack->mState == TrackBase::PAUSING) {
6671 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006672 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006673 } else {
6674 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08006675 }
6676 return status;
6677 }
6678
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006679 // TODO consider other ways of handling this, such as changing the state to :STARTING and
6680 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6681 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006682 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08006683 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07006684 status_t status = NO_ERROR;
6685 if (recordTrack->isExternalTrack()) {
6686 mLock.unlock();
Glenn Kastend848eb42016-03-08 13:42:11 -08006687 status = AudioSystem::startInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006688 mLock.lock();
6689 // FIXME should verify that recordTrack is still in mActiveTracks
6690 if (status != NO_ERROR) {
6691 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07006692 recordTrack->clearSyncStartEvent();
6693 ALOGV("RecordThread::start error %d", status);
6694 return status;
6695 }
Eric Laurent81784c32012-11-19 14:55:58 -08006696 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006697 // Catch up with current buffer indices if thread is already running.
6698 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
6699 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6700 // see previously buffered data before it called start(), but with greater risk of overrun.
6701
Andy Hung73c02e42015-03-29 01:13:58 -07006702 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07006703 // clear any converter state as new data will be discontinuous
6704 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006705 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08006706 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08006707 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08006708 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006709 ALOGV("Record failed to start");
6710 status = BAD_VALUE;
6711 goto startError;
6712 }
Eric Laurent81784c32012-11-19 14:55:58 -08006713 return status;
6714 }
Glenn Kasten7c027242012-12-26 14:43:16 -08006715
Eric Laurent81784c32012-11-19 14:55:58 -08006716startError:
Eric Laurent83b88082014-06-20 18:31:16 -07006717 if (recordTrack->isExternalTrack()) {
Glenn Kastend848eb42016-03-08 13:42:11 -08006718 AudioSystem::stopInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006719 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006720 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006721 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08006722 return status;
6723}
6724
Eric Laurent81784c32012-11-19 14:55:58 -08006725void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6726{
6727 sp<SyncEvent> strongEvent = event.promote();
6728
6729 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08006730 sp<RefBase> ptr = strongEvent->cookie().promote();
6731 if (ptr != 0) {
6732 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6733 recordTrack->handleSyncStartEvent(strongEvent);
6734 }
Eric Laurent81784c32012-11-19 14:55:58 -08006735 }
6736}
6737
Glenn Kastena8356f62013-07-25 14:37:52 -07006738bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08006739 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07006740 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006741 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08006742 return false;
6743 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006744 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006745 recordTrack->mState = TrackBase::PAUSING;
Eric Laurent5c25d562016-07-13 17:17:45 -07006746 // signal thread to stop
6747 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08006748 // do not wait for mStartStopCond if exiting
6749 if (exitPending()) {
6750 return true;
6751 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006752 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08006753 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006754 // if we have been restarted, recordTrack is in mActiveTracks here
6755 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006756 ALOGV("Record stopped OK");
6757 return true;
6758 }
6759 return false;
6760}
6761
Glenn Kasten0f11b512014-01-31 16:18:54 -08006762bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08006763{
6764 return false;
6765}
6766
Glenn Kasten0f11b512014-01-31 16:18:54 -08006767status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006768{
6769#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6770 if (!isValidSyncEvent(event)) {
6771 return BAD_VALUE;
6772 }
6773
Glenn Kastend848eb42016-03-08 13:42:11 -08006774 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08006775 status_t ret = NAME_NOT_FOUND;
6776
6777 Mutex::Autolock _l(mLock);
6778
6779 for (size_t i = 0; i < mTracks.size(); i++) {
6780 sp<RecordTrack> track = mTracks[i];
6781 if (eventSession == track->sessionId()) {
6782 (void) track->setSyncEvent(event);
6783 ret = NO_ERROR;
6784 }
6785 }
6786 return ret;
6787#else
6788 return BAD_VALUE;
6789#endif
6790}
6791
6792// destroyTrack_l() must be called with ThreadBase::mLock held
6793void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6794{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006795 track->terminate();
6796 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006797 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006798 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006799 removeTrack_l(track);
6800 }
6801}
6802
6803void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6804{
6805 mTracks.remove(track);
6806 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006807 if (track->isFastTrack()) {
6808 ALOG_ASSERT(!mFastTrackAvail);
6809 mFastTrackAvail = true;
6810 }
Eric Laurent81784c32012-11-19 14:55:58 -08006811}
6812
6813void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6814{
6815 dumpInternals(fd, args);
6816 dumpTracks(fd, args);
6817 dumpEffectChains(fd, args);
6818}
6819
6820void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6821{
Elliott Hughes87cebad2014-05-22 10:14:43 -07006822 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08006823
Glenn Kasten44182c22015-03-05 17:12:23 -08006824 dumpBase(fd, args);
6825
6826 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006827 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006828 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006829 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006830 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08006831
Glenn Kasten2f90c512015-12-02 11:40:09 -08006832 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
6833 // while we are dumping it. It may be inconsistent, but it won't mutate!
6834 // This is a large object so we place it on the heap.
6835 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
6836 const FastCaptureDumpState *copy = new FastCaptureDumpState(mFastCaptureDumpState);
6837 copy->dump(fd);
6838 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08006839}
6840
Glenn Kasten0f11b512014-01-31 16:18:54 -08006841void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006842{
6843 const size_t SIZE = 256;
6844 char buffer[SIZE];
6845 String8 result;
6846
Marco Nelissenb2208842014-02-07 14:00:50 -08006847 size_t numtracks = mTracks.size();
6848 size_t numactive = mActiveTracks.size();
6849 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006850 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006851 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006852 dprintf(fd, " of which %zu are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006853 RecordTrack::appendDumpHeader(result);
6854 for (size_t i = 0; i < numtracks ; ++i) {
6855 sp<RecordTrack> track = mTracks[i];
6856 if (track != 0) {
6857 bool active = mActiveTracks.indexOf(track) >= 0;
6858 if (active) {
6859 numactiveseen++;
6860 }
6861 track->dump(buffer, SIZE, active);
6862 result.append(buffer);
6863 }
Eric Laurent81784c32012-11-19 14:55:58 -08006864 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006865 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006866 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006867 }
6868
Marco Nelissenb2208842014-02-07 14:00:50 -08006869 if (numactiveseen != numactive) {
6870 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6871 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006872 result.append(buffer);
6873 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006874 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006875 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006876 if (mTracks.indexOf(track) < 0) {
6877 track->dump(buffer, SIZE, true);
6878 result.append(buffer);
6879 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006880 }
Eric Laurent81784c32012-11-19 14:55:58 -08006881
6882 }
6883 write(fd, result.string(), result.size());
6884}
6885
Andy Hung73c02e42015-03-29 01:13:58 -07006886
6887void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
6888{
6889 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6890 RecordThread *recordThread = (RecordThread *) threadBase.get();
6891 mRsmpInFront = recordThread->mRsmpInRear;
6892 mRsmpInUnrel = 0;
6893}
6894
6895void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
6896 size_t *framesAvailable, bool *hasOverrun)
6897{
6898 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6899 RecordThread *recordThread = (RecordThread *) threadBase.get();
6900 const int32_t rear = recordThread->mRsmpInRear;
6901 const int32_t front = mRsmpInFront;
6902 const ssize_t filled = rear - front;
6903
6904 size_t framesIn;
6905 bool overrun = false;
6906 if (filled < 0) {
6907 // should not happen, but treat like a massive overrun and re-sync
6908 framesIn = 0;
6909 mRsmpInFront = rear;
6910 overrun = true;
6911 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
6912 framesIn = (size_t) filled;
6913 } else {
6914 // client is not keeping up with server, but give it latest data
6915 framesIn = recordThread->mRsmpInFrames;
6916 mRsmpInFront = /* front = */ rear - framesIn;
6917 overrun = true;
6918 }
6919 if (framesAvailable != NULL) {
6920 *framesAvailable = framesIn;
6921 }
6922 if (hasOverrun != NULL) {
6923 *hasOverrun = overrun;
6924 }
6925}
6926
Eric Laurent81784c32012-11-19 14:55:58 -08006927// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006928status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08006929 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006930{
Andy Hung73c02e42015-03-29 01:13:58 -07006931 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006932 if (threadBase == 0) {
6933 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006934 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006935 return NOT_ENOUGH_DATA;
6936 }
6937 RecordThread *recordThread = (RecordThread *) threadBase.get();
6938 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07006939 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07006940 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006941 // FIXME should not be P2 (don't want to increase latency)
6942 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006943 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07006944 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006945 front &= recordThread->mRsmpInFramesP2 - 1;
6946 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07006947 if (part1 > (size_t) filled) {
6948 part1 = filled;
6949 }
6950 size_t ask = buffer->frameCount;
6951 ALOG_ASSERT(ask > 0);
6952 if (part1 > ask) {
6953 part1 = ask;
6954 }
6955 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07006956 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07006957 buffer->raw = NULL;
6958 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07006959 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07006960 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08006961 }
6962
Andy Hung57446612015-04-19 23:56:46 -07006963 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07006964 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07006965 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08006966 return NO_ERROR;
6967}
6968
6969// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006970void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
6971 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006972{
Glenn Kasten85948432013-08-19 12:09:05 -07006973 size_t stepCount = buffer->frameCount;
6974 if (stepCount == 0) {
6975 return;
6976 }
Andy Hung73c02e42015-03-29 01:13:58 -07006977 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
6978 mRsmpInUnrel -= stepCount;
6979 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006980 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006981 buffer->frameCount = 0;
6982}
6983
Andy Hung97a893e2015-03-29 01:03:07 -07006984AudioFlinger::RecordThread::RecordBufferConverter::RecordBufferConverter(
6985 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6986 uint32_t srcSampleRate,
6987 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6988 uint32_t dstSampleRate) :
6989 mSrcChannelMask(AUDIO_CHANNEL_INVALID), // updateParameters will set following vars
6990 // mSrcFormat
6991 // mSrcSampleRate
6992 // mDstChannelMask
6993 // mDstFormat
6994 // mDstSampleRate
6995 // mSrcChannelCount
6996 // mDstChannelCount
6997 // mDstFrameSize
6998 mBuf(NULL), mBufFrames(0), mBufFrameSize(0),
Andy Hungd330ee42015-04-20 13:23:41 -07006999 mResampler(NULL),
7000 mIsLegacyDownmix(false),
7001 mIsLegacyUpmix(false),
7002 mRequiresFloat(false),
7003 mInputConverterProvider(NULL)
Andy Hung97a893e2015-03-29 01:03:07 -07007004{
7005 (void)updateParameters(srcChannelMask, srcFormat, srcSampleRate,
7006 dstChannelMask, dstFormat, dstSampleRate);
7007}
7008
7009AudioFlinger::RecordThread::RecordBufferConverter::~RecordBufferConverter() {
7010 free(mBuf);
7011 delete mResampler;
Andy Hungd330ee42015-04-20 13:23:41 -07007012 delete mInputConverterProvider;
Andy Hung97a893e2015-03-29 01:03:07 -07007013}
7014
7015size_t AudioFlinger::RecordThread::RecordBufferConverter::convert(void *dst,
7016 AudioBufferProvider *provider, size_t frames)
7017{
Andy Hungd330ee42015-04-20 13:23:41 -07007018 if (mInputConverterProvider != NULL) {
7019 mInputConverterProvider->setBufferProvider(provider);
7020 provider = mInputConverterProvider;
7021 }
7022
7023 if (mResampler == NULL) {
Andy Hung97a893e2015-03-29 01:03:07 -07007024 ALOGVV("NO RESAMPLING sampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
7025 mSrcSampleRate, mSrcFormat, mDstFormat);
7026
7027 AudioBufferProvider::Buffer buffer;
7028 for (size_t i = frames; i > 0; ) {
7029 buffer.frameCount = i;
Glenn Kastend79072e2016-01-06 08:41:20 -08007030 status_t status = provider->getNextBuffer(&buffer);
Andy Hung97a893e2015-03-29 01:03:07 -07007031 if (status != OK || buffer.frameCount == 0) {
7032 frames -= i; // cannot fill request.
7033 break;
7034 }
Andy Hungd330ee42015-04-20 13:23:41 -07007035 // format convert to destination buffer
7036 convertNoResampler(dst, buffer.raw, buffer.frameCount);
Andy Hung97a893e2015-03-29 01:03:07 -07007037
7038 dst = (int8_t*)dst + buffer.frameCount * mDstFrameSize;
7039 i -= buffer.frameCount;
7040 provider->releaseBuffer(&buffer);
7041 }
7042 } else {
7043 ALOGVV("RESAMPLING mSrcSampleRate:%u mDstSampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
7044 mSrcSampleRate, mDstSampleRate, mSrcFormat, mDstFormat);
7045
Andy Hungd330ee42015-04-20 13:23:41 -07007046 // reallocate buffer if needed
7047 if (mBufFrameSize != 0 && mBufFrames < frames) {
7048 free(mBuf);
7049 mBufFrames = frames;
7050 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
7051 }
Andy Hung97a893e2015-03-29 01:03:07 -07007052 // resampler accumulates, but we only have one source track
Andy Hungd330ee42015-04-20 13:23:41 -07007053 memset(mBuf, 0, frames * mBufFrameSize);
7054 frames = mResampler->resample((int32_t*)mBuf, frames, provider);
7055 // format convert to destination buffer
7056 convertResampler(dst, mBuf, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07007057 }
7058 return frames;
7059}
7060
7061status_t AudioFlinger::RecordThread::RecordBufferConverter::updateParameters(
7062 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
7063 uint32_t srcSampleRate,
7064 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
7065 uint32_t dstSampleRate)
7066{
7067 // quick evaluation if there is any change.
7068 if (mSrcFormat == srcFormat
7069 && mSrcChannelMask == srcChannelMask
7070 && mSrcSampleRate == srcSampleRate
7071 && mDstFormat == dstFormat
7072 && mDstChannelMask == dstChannelMask
7073 && mDstSampleRate == dstSampleRate) {
7074 return NO_ERROR;
7075 }
7076
Andy Hungdb4c0312015-05-06 08:46:52 -07007077 ALOGV("RecordBufferConverter updateParameters srcMask:%#x dstMask:%#x"
7078 " srcFormat:%#x dstFormat:%#x srcRate:%u dstRate:%u",
7079 srcChannelMask, dstChannelMask, srcFormat, dstFormat, srcSampleRate, dstSampleRate);
Andy Hung97a893e2015-03-29 01:03:07 -07007080 const bool valid =
7081 audio_is_input_channel(srcChannelMask)
7082 && audio_is_input_channel(dstChannelMask)
7083 && audio_is_valid_format(srcFormat) && audio_is_linear_pcm(srcFormat)
7084 && audio_is_valid_format(dstFormat) && audio_is_linear_pcm(dstFormat)
7085 && (srcSampleRate <= dstSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX)
7086 ; // no upsampling checks for now
7087 if (!valid) {
7088 return BAD_VALUE;
7089 }
7090
7091 mSrcFormat = srcFormat;
7092 mSrcChannelMask = srcChannelMask;
7093 mSrcSampleRate = srcSampleRate;
7094 mDstFormat = dstFormat;
7095 mDstChannelMask = dstChannelMask;
7096 mDstSampleRate = dstSampleRate;
7097
7098 // compute derived parameters
7099 mSrcChannelCount = audio_channel_count_from_in_mask(srcChannelMask);
7100 mDstChannelCount = audio_channel_count_from_in_mask(dstChannelMask);
7101 mDstFrameSize = mDstChannelCount * audio_bytes_per_sample(mDstFormat);
7102
Andy Hungd330ee42015-04-20 13:23:41 -07007103 // do we need to resample?
7104 delete mResampler;
7105 mResampler = NULL;
7106 if (mSrcSampleRate != mDstSampleRate) {
7107 mResampler = AudioResampler::create(AUDIO_FORMAT_PCM_FLOAT,
7108 mSrcChannelCount, mDstSampleRate);
7109 mResampler->setSampleRate(mSrcSampleRate);
7110 mResampler->setVolume(AudioMixer::UNITY_GAIN_FLOAT, AudioMixer::UNITY_GAIN_FLOAT);
7111 }
7112
7113 // are we running legacy channel conversion modes?
7114 mIsLegacyDownmix = (mSrcChannelMask == AUDIO_CHANNEL_IN_STEREO
7115 || mSrcChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK)
7116 && mDstChannelMask == AUDIO_CHANNEL_IN_MONO;
7117 mIsLegacyUpmix = mSrcChannelMask == AUDIO_CHANNEL_IN_MONO
7118 && (mDstChannelMask == AUDIO_CHANNEL_IN_STEREO
7119 || mDstChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK);
7120
7121 // do we need to process in float?
7122 mRequiresFloat = mResampler != NULL || mIsLegacyDownmix || mIsLegacyUpmix;
7123
7124 // do we need a staging buffer to convert for destination (we can still optimize this)?
7125 // we use mBufFrameSize > 0 to indicate both frame size as well as buffer necessity
7126 if (mResampler != NULL) {
7127 mBufFrameSize = max(mSrcChannelCount, FCC_2)
7128 * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
Andy Hunga97630b2015-07-22 23:27:24 -07007129 } else if (mIsLegacyUpmix || mIsLegacyDownmix) { // legacy modes always float
Andy Hungd330ee42015-04-20 13:23:41 -07007130 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
7131 } else if (mSrcChannelMask != mDstChannelMask && mDstFormat != mSrcFormat) {
Andy Hung97a893e2015-03-29 01:03:07 -07007132 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(mSrcFormat);
7133 } else {
7134 mBufFrameSize = 0;
7135 }
7136 mBufFrames = 0; // force the buffer to be resized.
7137
Andy Hungd330ee42015-04-20 13:23:41 -07007138 // do we need an input converter buffer provider to give us float?
7139 delete mInputConverterProvider;
7140 mInputConverterProvider = NULL;
7141 if (mRequiresFloat && mSrcFormat != AUDIO_FORMAT_PCM_FLOAT) {
7142 mInputConverterProvider = new ReformatBufferProvider(
7143 audio_channel_count_from_in_mask(mSrcChannelMask),
7144 mSrcFormat,
7145 AUDIO_FORMAT_PCM_FLOAT,
7146 256 /* provider buffer frame count */);
7147 }
7148
7149 // do we need a remixer to do channel mask conversion
7150 if (!mIsLegacyDownmix && !mIsLegacyUpmix && mSrcChannelMask != mDstChannelMask) {
7151 (void) memcpy_by_index_array_initialization_from_channel_mask(
7152 mIdxAry, ARRAY_SIZE(mIdxAry), mDstChannelMask, mSrcChannelMask);
Andy Hung97a893e2015-03-29 01:03:07 -07007153 }
7154 return NO_ERROR;
7155}
7156
Andy Hungd330ee42015-04-20 13:23:41 -07007157void AudioFlinger::RecordThread::RecordBufferConverter::convertNoResampler(
7158 void *dst, const void *src, size_t frames)
Andy Hung97a893e2015-03-29 01:03:07 -07007159{
Andy Hungd330ee42015-04-20 13:23:41 -07007160 // src is native type unless there is legacy upmix or downmix, whereupon it is float.
Andy Hung97a893e2015-03-29 01:03:07 -07007161 if (mBufFrameSize != 0 && mBufFrames < frames) {
7162 free(mBuf);
7163 mBufFrames = frames;
7164 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
7165 }
Andy Hungd330ee42015-04-20 13:23:41 -07007166 // do we need to do legacy upmix and downmix?
7167 if (mIsLegacyUpmix || mIsLegacyDownmix) {
Andy Hung97a893e2015-03-29 01:03:07 -07007168 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07007169 if (mIsLegacyUpmix) {
7170 upmix_to_stereo_float_from_mono_float((float *)dstBuf,
7171 (const float *)src, frames);
7172 } else /*mIsLegacyDownmix */ {
7173 downmix_to_mono_float_from_stereo_float((float *)dstBuf,
7174 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07007175 }
Andy Hungd330ee42015-04-20 13:23:41 -07007176 if (mBuf != NULL) {
7177 memcpy_by_audio_format(dst, mDstFormat, mBuf, AUDIO_FORMAT_PCM_FLOAT,
7178 frames * mDstChannelCount);
7179 }
7180 return;
7181 }
7182 // do we need to do channel mask conversion?
7183 if (mSrcChannelMask != mDstChannelMask) {
Andy Hung97a893e2015-03-29 01:03:07 -07007184 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07007185 memcpy_by_index_array(dstBuf, mDstChannelCount,
7186 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mSrcFormat), frames);
7187 if (dstBuf == dst) {
7188 return; // format is the same
7189 }
7190 }
7191 // convert to destination buffer
7192 const void *convertBuf = mBuf != NULL ? mBuf : src;
7193 memcpy_by_audio_format(dst, mDstFormat, convertBuf, mSrcFormat,
7194 frames * mDstChannelCount);
7195}
7196
7197void AudioFlinger::RecordThread::RecordBufferConverter::convertResampler(
7198 void *dst, /*not-a-const*/ void *src, size_t frames)
7199{
7200 // src buffer format is ALWAYS float when entering this routine
7201 if (mIsLegacyUpmix) {
7202 ; // mono to stereo already handled by resampler
7203 } else if (mIsLegacyDownmix
7204 || (mSrcChannelMask == mDstChannelMask && mSrcChannelCount == 1)) {
7205 // the resampler outputs stereo for mono input channel (a feature?)
7206 // must convert to mono
7207 downmix_to_mono_float_from_stereo_float((float *)src,
7208 (const float *)src, frames);
7209 } else if (mSrcChannelMask != mDstChannelMask) {
7210 // convert to mono channel again for channel mask conversion (could be skipped
7211 // with further optimization).
Andy Hung97a893e2015-03-29 01:03:07 -07007212 if (mSrcChannelCount == 1) {
Andy Hungd330ee42015-04-20 13:23:41 -07007213 downmix_to_mono_float_from_stereo_float((float *)src,
7214 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07007215 }
Andy Hungd330ee42015-04-20 13:23:41 -07007216 // convert to destination format (in place, OK as float is larger than other types)
7217 if (mDstFormat != AUDIO_FORMAT_PCM_FLOAT) {
7218 memcpy_by_audio_format(src, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
7219 frames * mSrcChannelCount);
7220 }
7221 // channel convert and save to dst
7222 memcpy_by_index_array(dst, mDstChannelCount,
7223 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mDstFormat), frames);
7224 return;
Andy Hung97a893e2015-03-29 01:03:07 -07007225 }
Andy Hungd330ee42015-04-20 13:23:41 -07007226 // convert to destination format and save to dst
7227 memcpy_by_audio_format(dst, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
7228 frames * mDstChannelCount);
Andy Hung97a893e2015-03-29 01:03:07 -07007229}
7230
Eric Laurent10351942014-05-08 18:49:52 -07007231bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
7232 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007233{
7234 bool reconfig = false;
7235
Eric Laurent10351942014-05-08 18:49:52 -07007236 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007237
Eric Laurent10351942014-05-08 18:49:52 -07007238 audio_format_t reqFormat = mFormat;
7239 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07007240 // 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 -07007241 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
7242
7243 AudioParameter param = AudioParameter(keyValuePair);
7244 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07007245
7246 // scope for AutoPark extends to end of method
7247 AutoPark<FastCapture> park(mFastCapture);
7248
Eric Laurent10351942014-05-08 18:49:52 -07007249 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
7250 // channel count change can be requested. Do we mandate the first client defines the
7251 // HAL sampling rate and channel count or do we allow changes on the fly?
7252 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
7253 samplingRate = value;
7254 reconfig = true;
7255 }
7256 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07007257 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07007258 status = BAD_VALUE;
7259 } else {
7260 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08007261 reconfig = true;
7262 }
Eric Laurent10351942014-05-08 18:49:52 -07007263 }
7264 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
7265 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07007266 if (!audio_is_input_channel(mask) ||
7267 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007268 status = BAD_VALUE;
7269 } else {
7270 channelMask = mask;
7271 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007272 }
Eric Laurent10351942014-05-08 18:49:52 -07007273 }
7274 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7275 // do not accept frame count changes if tracks are open as the track buffer
7276 // size depends on frame count and correct behavior would not be guaranteed
7277 // if frame count is changed after track creation
7278 if (mActiveTracks.size() > 0) {
7279 status = INVALID_OPERATION;
7280 } else {
7281 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007282 }
Eric Laurent10351942014-05-08 18:49:52 -07007283 }
7284 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7285 // forward device change to effects that have requested to be
7286 // aware of attached audio device.
7287 for (size_t i = 0; i < mEffectChains.size(); i++) {
7288 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08007289 }
Eric Laurent81784c32012-11-19 14:55:58 -08007290
Eric Laurent10351942014-05-08 18:49:52 -07007291 // store input device and output device but do not forward output device to audio HAL.
7292 // Note that status is ignored by the caller for output device
7293 // (see AudioFlinger::setParameters()
7294 if (audio_is_output_devices(value)) {
7295 mOutDevice = value;
7296 status = BAD_VALUE;
7297 } else {
7298 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07007299 if (value != AUDIO_DEVICE_NONE) {
7300 mPrevInDevice = value;
7301 }
Eric Laurent10351942014-05-08 18:49:52 -07007302 // disable AEC and NS if the device is a BT SCO headset supporting those
7303 // pre processings
7304 if (mTracks.size() > 0) {
7305 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7306 mAudioFlinger->btNrecIsOff();
7307 for (size_t i = 0; i < mTracks.size(); i++) {
7308 sp<RecordTrack> track = mTracks[i];
7309 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7310 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08007311 }
7312 }
7313 }
Eric Laurent10351942014-05-08 18:49:52 -07007314 }
7315 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
7316 mAudioSource != (audio_source_t)value) {
7317 // forward device change to effects that have requested to be
7318 // aware of attached audio device.
7319 for (size_t i = 0; i < mEffectChains.size(); i++) {
7320 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08007321 }
Eric Laurent10351942014-05-08 18:49:52 -07007322 mAudioSource = (audio_source_t)value;
7323 }
Glenn Kastene198c362013-08-13 09:13:36 -07007324
Eric Laurent10351942014-05-08 18:49:52 -07007325 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007326 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007327 if (status == INVALID_OPERATION) {
7328 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007329 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007330 }
7331 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007332 if (status == BAD_VALUE) {
7333 uint32_t sRate;
7334 audio_channel_mask_t channelMask;
7335 audio_format_t format;
7336 if (mInput->stream->getAudioProperties(&sRate, &channelMask, &format) == OK &&
7337 audio_is_linear_pcm(format) && audio_is_linear_pcm(reqFormat) &&
7338 sRate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
7339 audio_channel_count_from_in_mask(channelMask) <= FCC_8) {
7340 status = NO_ERROR;
7341 }
Eric Laurent81784c32012-11-19 14:55:58 -08007342 }
Eric Laurent10351942014-05-08 18:49:52 -07007343 if (status == NO_ERROR) {
7344 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007345 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08007346 }
7347 }
Eric Laurent81784c32012-11-19 14:55:58 -08007348 }
Eric Laurent10351942014-05-08 18:49:52 -07007349
Eric Laurent81784c32012-11-19 14:55:58 -08007350 return reconfig;
7351}
7352
7353String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
7354{
Eric Laurent81784c32012-11-19 14:55:58 -08007355 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007356 if (initCheck() == NO_ERROR) {
7357 String8 out_s8;
7358 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
7359 return out_s8;
7360 }
Eric Laurent81784c32012-11-19 14:55:58 -08007361 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007362 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08007363}
7364
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007365void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007366 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7367
7368 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08007369
7370 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007371 case AUDIO_INPUT_OPENED:
7372 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07007373 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07007374 desc->mChannelMask = mChannelMask;
7375 desc->mSamplingRate = mSampleRate;
7376 desc->mFormat = mFormat;
7377 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07007378 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07007379 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007380 break;
7381
Eric Laurent73e26b62015-04-27 16:55:58 -07007382 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08007383 default:
7384 break;
7385 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007386 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08007387}
7388
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007389void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007390{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007391 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
7392 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hunge5412692014-05-16 11:25:07 -07007393 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007394 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_8, "HAL channel count %d > %d", mChannelCount, FCC_8);
Andy Hung463be252014-07-10 16:56:07 -07007395 mFormat = mHALFormat;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007396 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
7397 result = mInput->stream->getFrameSize(&mFrameSize);
7398 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
7399 result = mInput->stream->getBufferSize(&mBufferSize);
7400 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08007401 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007402 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08007403 // 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 -07007404 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08007405 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007406 // A larger value should allow more old data to be read after a track calls start(),
7407 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07007408 //
7409 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08007410 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07007411 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07007412 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07007413 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007414
7415 // TODO optimize audio capture buffer sizes ...
7416 // Here we calculate the size of the sliding buffer used as a source
7417 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
7418 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
7419 // be better to have it derived from the pipe depth in the long term.
7420 // The current value is higher than necessary. However it should not add to latency.
7421
Glenn Kasten85948432013-08-19 12:09:05 -07007422 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Glenn Kasten1b291842016-07-18 14:55:21 -07007423 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
7424 (void)posix_memalign(&mRsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
7425 memset(mRsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize); // if posix_memalign fails, will segv here.
Eric Laurent81784c32012-11-19 14:55:58 -08007426
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007427 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
7428 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08007429}
7430
Glenn Kasten5f972c02014-01-13 09:59:31 -08007431uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08007432{
7433 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007434 uint32_t result;
7435 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
7436 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08007437 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007438 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007439}
7440
Eric Laurent4c415062016-06-17 16:14:16 -07007441// hasAudioSession_l() must be called with ThreadBase::mLock held
7442uint32_t AudioFlinger::RecordThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08007443{
Eric Laurent81784c32012-11-19 14:55:58 -08007444 uint32_t result = 0;
7445 if (getEffectChain_l(sessionId) != 0) {
7446 result = EFFECT_SESSION;
7447 }
7448
7449 for (size_t i = 0; i < mTracks.size(); ++i) {
7450 if (sessionId == mTracks[i]->sessionId()) {
7451 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07007452 if (mTracks[i]->isFastTrack()) {
7453 result |= FAST_SESSION;
7454 }
Eric Laurent81784c32012-11-19 14:55:58 -08007455 break;
7456 }
7457 }
7458
7459 return result;
7460}
7461
Glenn Kastend848eb42016-03-08 13:42:11 -08007462KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08007463{
Glenn Kastend848eb42016-03-08 13:42:11 -08007464 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08007465 Mutex::Autolock _l(mLock);
7466 for (size_t j = 0; j < mTracks.size(); ++j) {
7467 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08007468 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08007469 if (ids.indexOfKey(sessionId) < 0) {
7470 ids.add(sessionId, true);
7471 }
7472 }
7473 return ids;
7474}
7475
7476AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7477{
7478 Mutex::Autolock _l(mLock);
7479 AudioStreamIn *input = mInput;
7480 mInput = NULL;
7481 return input;
7482}
7483
7484// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007485sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08007486{
7487 if (mInput == NULL) {
7488 return NULL;
7489 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007490 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08007491}
7492
7493status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7494{
7495 // only one chain per input thread
7496 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07007497 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08007498 return INVALID_OPERATION;
7499 }
7500 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07007501 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08007502 chain->setInBuffer(NULL);
7503 chain->setOutBuffer(NULL);
7504
7505 checkSuspendOnAddEffectChain_l(chain);
7506
Eric Laurent1b928682014-10-02 19:41:47 -07007507 // make sure enabled pre processing effects state is communicated to the HAL as we
7508 // just moved them to a new input stream.
7509 chain->syncHalEffectsState();
7510
Eric Laurent81784c32012-11-19 14:55:58 -08007511 mEffectChains.add(chain);
7512
7513 return NO_ERROR;
7514}
7515
7516size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7517{
7518 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7519 ALOGW_IF(mEffectChains.size() != 1,
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007520 "removeEffectChain_l() %p invalid chain size %zu on thread %p",
Eric Laurent81784c32012-11-19 14:55:58 -08007521 chain.get(), mEffectChains.size(), this);
7522 if (mEffectChains.size() == 1) {
7523 mEffectChains.removeAt(0);
7524 }
7525 return 0;
7526}
7527
Eric Laurent1c333e22014-05-20 10:48:17 -07007528status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7529 audio_patch_handle_t *handle)
7530{
7531 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007532
7533 // store new device and send to effects
7534 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07007535 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07007536 for (size_t i = 0; i < mEffectChains.size(); i++) {
7537 mEffectChains[i]->setDevice_l(mInDevice);
7538 }
7539
7540 // disable AEC and NS if the device is a BT SCO headset supporting those
7541 // pre processings
7542 if (mTracks.size() > 0) {
7543 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7544 mAudioFlinger->btNrecIsOff();
7545 for (size_t i = 0; i < mTracks.size(); i++) {
7546 sp<RecordTrack> track = mTracks[i];
7547 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7548 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
7549 }
7550 }
7551
7552 // store new source and send to effects
7553 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7554 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07007555 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07007556 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07007557 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007558 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007559
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007560 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007561 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7562 status = hwDevice->createAudioPatch(patch->num_sources,
7563 patch->sources,
7564 patch->num_sinks,
7565 patch->sinks,
7566 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007567 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007568 char *address;
7569 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7570 address = audio_device_address_to_parameter(
7571 patch->sources[0].ext.device.type,
7572 patch->sources[0].ext.device.address);
7573 } else {
7574 address = (char *)calloc(1, 1);
7575 }
7576 AudioParameter param = AudioParameter(String8(address));
7577 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007578 param.addInt(String8(AudioParameter::keyRouting),
Eric Laurent054d9d32015-04-24 08:48:48 -07007579 (int)patch->sources[0].ext.device.type);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007580 param.addInt(String8(AudioParameter::keyInputSource),
Eric Laurent054d9d32015-04-24 08:48:48 -07007581 (int)patch->sinks[0].ext.mix.usecase.source);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007582 status = mInput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07007583 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07007584 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007585
Eric Laurente8726fe2015-06-26 09:39:24 -07007586 if (mInDevice != mPrevInDevice) {
7587 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7588 mPrevInDevice = mInDevice;
7589 }
Eric Laurent296fb132015-05-01 11:38:42 -07007590
Eric Laurent1c333e22014-05-20 10:48:17 -07007591 return status;
7592}
7593
7594status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7595{
7596 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007597
7598 mInDevice = AUDIO_DEVICE_NONE;
7599
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007600 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007601 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7602 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007603 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007604 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07007605 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007606 status = mInput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07007607 }
7608 return status;
7609}
7610
Eric Laurent83b88082014-06-20 18:31:16 -07007611void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
7612{
7613 Mutex::Autolock _l(mLock);
7614 mTracks.add(record);
7615}
7616
7617void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
7618{
7619 Mutex::Autolock _l(mLock);
7620 destroyTrack_l(record);
7621}
7622
7623void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
7624{
7625 ThreadBase::getAudioPortConfig(config);
7626 config->role = AUDIO_PORT_ROLE_SINK;
7627 config->ext.mix.hw_module = mInput->audioHwDev->handle();
7628 config->ext.mix.usecase.source = mAudioSource;
7629}
Eric Laurent1c333e22014-05-20 10:48:17 -07007630
Glenn Kasten63238ef2015-03-02 15:50:29 -08007631} // namespace android