blob: c19cb6a816ea389ce83c83d529f30528b54f0962 [file] [log] [blame]
Eric Laurent81784c32012-11-19 14:55:58 -08001/*
2**
3** Copyright 2012, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
Alex Ray371eb972012-11-30 11:11:54 -080021#define ATRACE_TAG ATRACE_TAG_AUDIO
Eric Laurent81784c32012-11-19 14:55:58 -080022
Glenn Kasten153b9fe2013-07-15 11:23:36 -070023#include "Configuration.h"
Eric Laurent81784c32012-11-19 14:55:58 -080024#include <math.h>
25#include <fcntl.h>
Glenn Kastenad8510a2015-02-17 16:24:07 -080026#include <linux/futex.h>
Eric Laurent81784c32012-11-19 14:55:58 -080027#include <sys/stat.h>
Glenn Kastenad8510a2015-02-17 16:24:07 -080028#include <sys/syscall.h>
Eric Laurent81784c32012-11-19 14:55:58 -080029#include <cutils/properties.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070030#include <media/AudioParameter.h>
Andy Hungcd044842014-08-07 11:04:34 -070031#include <media/AudioResamplerPublic.h>
Eric Laurent81784c32012-11-19 14:55:58 -080032#include <utils/Log.h>
Alex Ray371eb972012-11-30 11:11:54 -080033#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080034
35#include <private/media/AudioTrackShared.h>
36#include <hardware/audio.h>
37#include <audio_effects/effect_ns.h>
38#include <audio_effects/effect_aec.h>
Andy Hung2ddee192015-12-18 17:34:44 -080039#include <audio_utils/conversion.h>
Eric Laurent81784c32012-11-19 14:55:58 -080040#include <audio_utils/primitives.h>
Andy Hung98ef9782014-03-04 14:46:50 -080041#include <audio_utils/format.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070042#include <audio_utils/minifloat.h>
Eric Laurent81784c32012-11-19 14:55:58 -080043
44// NBAIO implementations
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070045#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080046#include <media/nbaio/AudioStreamOutSink.h>
47#include <media/nbaio/MonoPipe.h>
48#include <media/nbaio/MonoPipeReader.h>
49#include <media/nbaio/Pipe.h>
50#include <media/nbaio/PipeReader.h>
51#include <media/nbaio/SourceAudioBufferProvider.h>
Wei Jia3f273d12015-11-24 09:06:49 -080052#include <mediautils/BatteryNotifier.h>
Eric Laurent81784c32012-11-19 14:55:58 -080053
54#include <powermanager/PowerManager.h>
55
Eric Laurent81784c32012-11-19 14:55:58 -080056#include "AudioFlinger.h"
57#include "AudioMixer.h"
Andy Hungd330ee42015-04-20 13:23:41 -070058#include "BufferProviders.h"
Eric Laurent81784c32012-11-19 14:55:58 -080059#include "FastMixer.h"
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070060#include "FastCapture.h"
Eric Laurent81784c32012-11-19 14:55:58 -080061#include "ServiceUtilities.h"
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -070062#include "mediautils/SchedulingPolicyService.h"
Eric Laurent81784c32012-11-19 14:55:58 -080063
Eric Laurent81784c32012-11-19 14:55:58 -080064#ifdef ADD_BATTERY_DATA
65#include <media/IMediaPlayerService.h>
66#include <media/IMediaDeathNotifier.h>
67#endif
68
Eric Laurent81784c32012-11-19 14:55:58 -080069#ifdef DEBUG_CPU_USAGE
70#include <cpustats/CentralTendencyStatistics.h>
71#include <cpustats/ThreadCpuUsage.h>
72#endif
73
Glenn Kastenc05b8d72016-03-24 09:48:17 -070074#include "AutoPark.h"
75
Eric Laurent81784c32012-11-19 14:55:58 -080076// ----------------------------------------------------------------------------
77
78// Note: the following macro is used for extremely verbose logging message. In
79// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
80// 0; but one side effect of this is to turn all LOGV's as well. Some messages
81// are so verbose that we want to suppress them even when we have ALOG_ASSERT
82// turned on. Do not uncomment the #def below unless you really know what you
83// are doing and want to see all of the extremely verbose messages.
84//#define VERY_VERY_VERBOSE_LOGGING
85#ifdef VERY_VERY_VERBOSE_LOGGING
86#define ALOGVV ALOGV
87#else
88#define ALOGVV(a...) do { } while(0)
89#endif
90
Andy Hung6770c6f2015-04-07 13:43:36 -070091// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -070092#define max(a, b) ((a) > (b) ? (a) : (b))
Andy Hung6770c6f2015-04-07 13:43:36 -070093template <typename T>
94static inline T min(const T& a, const T& b)
95{
96 return a < b ? a : b;
97}
Glenn Kasten49d00ad2014-07-21 11:22:03 -070098
Andy Hungd330ee42015-04-20 13:23:41 -070099#ifndef ARRAY_SIZE
100#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
101#endif
102
Eric Laurent81784c32012-11-19 14:55:58 -0800103namespace android {
104
105// retry counts for buffer fill timeout
106// 50 * ~20msecs = 1 second
107static const int8_t kMaxTrackRetries = 50;
108static const int8_t kMaxTrackStartupRetries = 50;
109// allow less retry attempts on direct output thread.
110// direct outputs can be a scarce resource in audio hardware and should
111// be released as quickly as possible.
112static const int8_t kMaxTrackRetriesDirect = 2;
Eric Laurente93cc032016-05-05 10:15:10 -0700113
Eric Laurent51716182016-02-29 18:00:56 -0800114
Eric Laurent81784c32012-11-19 14:55:58 -0800115
116// don't warn about blocked writes or record buffer overflows more often than this
117static const nsecs_t kWarningThrottleNs = seconds(5);
118
119// RecordThread loop sleep time upon application overrun or audio HAL read error
120static const int kRecordThreadSleepUs = 5000;
121
Eric Laurent10351942014-05-08 18:49:52 -0700122// maximum time to wait in sendConfigEvent_l() for a status to be received
123static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800124
125// minimum sleep time for the mixer thread loop when tracks are active but in underrun
126static const uint32_t kMinThreadSleepTimeUs = 5000;
127// maximum divider applied to the active sleep time in the mixer thread loop
128static const uint32_t kMaxThreadSleepTimeShift = 2;
129
Andy Hung09a50072014-02-27 14:30:47 -0800130// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700131// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800132static const uint32_t kMinNormalSinkBufferSizeMs = 20;
133// maximum normal sink buffer size
134static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800135
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700136// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
137// FIXME This should be based on experimentally observed scheduling jitter
138static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
139
Eric Laurent972a1732013-09-04 09:42:59 -0700140// Offloaded output thread standby delay: allows track transition without going to standby
141static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
142
Eric Laurent51716182016-02-29 18:00:56 -0800143// Direct output thread minimum sleep time in idle or active(underrun) state
144static const nsecs_t kDirectMinSleepTimeUs = 10000;
145
Eric Laurent51716182016-02-29 18:00:56 -0800146
Eric Laurent81784c32012-11-19 14:55:58 -0800147// Whether to use fast mixer
148static const enum {
149 FastMixer_Never, // never initialize or use: for debugging only
150 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
151 // normal mixer multiplier is 1
152 FastMixer_Static, // initialize if needed, then use all the time if initialized,
153 // multiplier is calculated based on min & max normal mixer buffer size
154 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
155 // multiplier is calculated based on min & max normal mixer buffer size
156 // FIXME for FastMixer_Dynamic:
157 // Supporting this option will require fixing HALs that can't handle large writes.
158 // For example, one HAL implementation returns an error from a large write,
159 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
160 // We could either fix the HAL implementations, or provide a wrapper that breaks
161 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
162} kUseFastMixer = FastMixer_Static;
163
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700164// Whether to use fast capture
165static const enum {
166 FastCapture_Never, // never initialize or use: for debugging only
167 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
168 FastCapture_Static, // initialize if needed, then use all the time if initialized
169} kUseFastCapture = FastCapture_Static;
170
Eric Laurent81784c32012-11-19 14:55:58 -0800171// Priorities for requestPriority
172static const int kPriorityAudioApp = 2;
173static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700174static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800175
Glenn Kastenea38ee72016-04-18 11:08:01 -0700176// IAudioFlinger::createTrack() has an in/out parameter 'pFrameCount' for the total size of the
177// track buffer in shared memory. Zero on input means to use a default value. For fast tracks,
178// AudioFlinger derives the default from HAL buffer size and 'fast track multiplier'.
Glenn Kasten03490092014-05-27 12:30:54 -0700179
180// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800181static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800182
Glenn Kasten03490092014-05-27 12:30:54 -0700183// The minimum and maximum allowed values
184static const int kFastTrackMultiplierMin = 1;
185static const int kFastTrackMultiplierMax = 2;
186
187// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
188static int sFastTrackMultiplier = kFastTrackMultiplier;
189
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700190// See Thread::readOnlyHeap().
191// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
192// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
193// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Glenn Kasten9f81de32014-07-27 15:02:23 -0700194static const size_t kRecordThreadReadOnlyHeapSize = 0x2000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700195
Eric Laurent81784c32012-11-19 14:55:58 -0800196// ----------------------------------------------------------------------------
197
Glenn Kasten03490092014-05-27 12:30:54 -0700198static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
199
200static void sFastTrackMultiplierInit()
201{
202 char value[PROPERTY_VALUE_MAX];
203 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
204 char *endptr;
205 unsigned long ul = strtoul(value, &endptr, 0);
206 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
207 sFastTrackMultiplier = (int) ul;
208 }
209 }
210}
211
212// ----------------------------------------------------------------------------
213
Eric Laurent81784c32012-11-19 14:55:58 -0800214#ifdef ADD_BATTERY_DATA
215// To collect the amplifier usage
216static void addBatteryData(uint32_t params) {
217 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
218 if (service == NULL) {
219 // it already logged
220 return;
221 }
222
223 service->addBatteryData(params);
224}
225#endif
226
Andy Hung3f0c9022016-01-15 17:49:46 -0800227// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
228struct {
229 // call when you acquire a partial wakelock
230 void acquire(const sp<IBinder> &wakeLockToken) {
231 pthread_mutex_lock(&mLock);
232 if (wakeLockToken.get() == nullptr) {
233 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
234 } else {
235 if (mCount == 0) {
236 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
237 }
238 ++mCount;
239 }
240 pthread_mutex_unlock(&mLock);
241 }
242
243 // call when you release a partial wakelock.
244 void release(const sp<IBinder> &wakeLockToken) {
245 if (wakeLockToken.get() == nullptr) {
246 return;
247 }
248 pthread_mutex_lock(&mLock);
249 if (--mCount < 0) {
250 ALOGE("negative wakelock count");
251 mCount = 0;
252 }
253 pthread_mutex_unlock(&mLock);
254 }
255
256 // retrieves the boottime timebase offset from monotonic.
257 int64_t getBoottimeOffset() {
258 pthread_mutex_lock(&mLock);
259 int64_t boottimeOffset = mBoottimeOffset;
260 pthread_mutex_unlock(&mLock);
261 return boottimeOffset;
262 }
263
264 // Adjusts the timebase offset between TIMEBASE_MONOTONIC
265 // and the selected timebase.
266 // Currently only TIMEBASE_BOOTTIME is allowed.
267 //
268 // This only needs to be called upon acquiring the first partial wakelock
269 // after all other partial wakelocks are released.
270 //
271 // We do an empirical measurement of the offset rather than parsing
272 // /proc/timer_list since the latter is not a formal kernel ABI.
273 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
274 int clockbase;
275 switch (timebase) {
276 case ExtendedTimestamp::TIMEBASE_BOOTTIME:
277 clockbase = SYSTEM_TIME_BOOTTIME;
278 break;
279 default:
280 LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
281 break;
282 }
283 // try three times to get the clock offset, choose the one
284 // with the minimum gap in measurements.
285 const int tries = 3;
286 nsecs_t bestGap, measured;
287 for (int i = 0; i < tries; ++i) {
288 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
289 const nsecs_t tbase = systemTime(clockbase);
290 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
291 const nsecs_t gap = tmono2 - tmono;
292 if (i == 0 || gap < bestGap) {
293 bestGap = gap;
294 measured = tbase - ((tmono + tmono2) >> 1);
295 }
296 }
297
298 // to avoid micro-adjusting, we don't change the timebase
299 // unless it is significantly different.
300 //
301 // Assumption: It probably takes more than toleranceNs to
302 // suspend and resume the device.
303 static int64_t toleranceNs = 10000; // 10 us
304 if (llabs(*offset - measured) > toleranceNs) {
305 ALOGV("Adjusting timebase offset old: %lld new: %lld",
306 (long long)*offset, (long long)measured);
307 *offset = measured;
308 }
309 }
310
311 pthread_mutex_t mLock;
312 int32_t mCount;
313 int64_t mBoottimeOffset;
314} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
Eric Laurent81784c32012-11-19 14:55:58 -0800315
316// ----------------------------------------------------------------------------
317// CPU Stats
318// ----------------------------------------------------------------------------
319
320class CpuStats {
321public:
322 CpuStats();
323 void sample(const String8 &title);
324#ifdef DEBUG_CPU_USAGE
325private:
326 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
327 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
328
329 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
330
331 int mCpuNum; // thread's current CPU number
332 int mCpukHz; // frequency of thread's current CPU in kHz
333#endif
334};
335
336CpuStats::CpuStats()
337#ifdef DEBUG_CPU_USAGE
338 : mCpuNum(-1), mCpukHz(-1)
339#endif
340{
341}
342
Glenn Kasten0f11b512014-01-31 16:18:54 -0800343void CpuStats::sample(const String8 &title
344#ifndef DEBUG_CPU_USAGE
345 __unused
346#endif
347 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800348#ifdef DEBUG_CPU_USAGE
349 // get current thread's delta CPU time in wall clock ns
350 double wcNs;
351 bool valid = mCpuUsage.sampleAndEnable(wcNs);
352
353 // record sample for wall clock statistics
354 if (valid) {
355 mWcStats.sample(wcNs);
356 }
357
358 // get the current CPU number
359 int cpuNum = sched_getcpu();
360
361 // get the current CPU frequency in kHz
362 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
363
364 // check if either CPU number or frequency changed
365 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
366 mCpuNum = cpuNum;
367 mCpukHz = cpukHz;
368 // ignore sample for purposes of cycles
369 valid = false;
370 }
371
372 // if no change in CPU number or frequency, then record sample for cycle statistics
373 if (valid && mCpukHz > 0) {
374 double cycles = wcNs * cpukHz * 0.000001;
375 mHzStats.sample(cycles);
376 }
377
378 unsigned n = mWcStats.n();
379 // mCpuUsage.elapsed() is expensive, so don't call it every loop
380 if ((n & 127) == 1) {
381 long long elapsed = mCpuUsage.elapsed();
382 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
383 double perLoop = elapsed / (double) n;
384 double perLoop100 = perLoop * 0.01;
385 double perLoop1k = perLoop * 0.001;
386 double mean = mWcStats.mean();
387 double stddev = mWcStats.stddev();
388 double minimum = mWcStats.minimum();
389 double maximum = mWcStats.maximum();
390 double meanCycles = mHzStats.mean();
391 double stddevCycles = mHzStats.stddev();
392 double minCycles = mHzStats.minimum();
393 double maxCycles = mHzStats.maximum();
394 mCpuUsage.resetElapsed();
395 mWcStats.reset();
396 mHzStats.reset();
397 ALOGD("CPU usage for %s over past %.1f secs\n"
398 " (%u mixer loops at %.1f mean ms per loop):\n"
399 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
400 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
401 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
402 title.string(),
403 elapsed * .000000001, n, perLoop * .000001,
404 mean * .001,
405 stddev * .001,
406 minimum * .001,
407 maximum * .001,
408 mean / perLoop100,
409 stddev / perLoop100,
410 minimum / perLoop100,
411 maximum / perLoop100,
412 meanCycles / perLoop1k,
413 stddevCycles / perLoop1k,
414 minCycles / perLoop1k,
415 maxCycles / perLoop1k);
416
417 }
418 }
419#endif
420};
421
422// ----------------------------------------------------------------------------
423// ThreadBase
424// ----------------------------------------------------------------------------
425
Glenn Kasten97b7b752014-09-28 13:04:24 -0700426// static
427const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
428{
429 switch (type) {
430 case MIXER:
431 return "MIXER";
432 case DIRECT:
433 return "DIRECT";
434 case DUPLICATING:
435 return "DUPLICATING";
436 case RECORD:
437 return "RECORD";
438 case OFFLOAD:
439 return "OFFLOAD";
440 default:
441 return "unknown";
442 }
443}
444
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800445String8 devicesToString(audio_devices_t devices)
446{
447 static const struct mapping {
448 audio_devices_t mDevices;
449 const char * mString;
450 } mappingsOut[] = {
Glenn Kasten818da522015-12-02 13:53:26 -0800451 {AUDIO_DEVICE_OUT_EARPIECE, "EARPIECE"},
452 {AUDIO_DEVICE_OUT_SPEAKER, "SPEAKER"},
453 {AUDIO_DEVICE_OUT_WIRED_HEADSET, "WIRED_HEADSET"},
454 {AUDIO_DEVICE_OUT_WIRED_HEADPHONE, "WIRED_HEADPHONE"},
455 {AUDIO_DEVICE_OUT_BLUETOOTH_SCO, "BLUETOOTH_SCO"},
456 {AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET, "BLUETOOTH_SCO_HEADSET"},
457 {AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT, "BLUETOOTH_SCO_CARKIT"},
458 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, "BLUETOOTH_A2DP"},
459 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,"BLUETOOTH_A2DP_HEADPHONES"},
460 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER, "BLUETOOTH_A2DP_SPEAKER"},
461 {AUDIO_DEVICE_OUT_AUX_DIGITAL, "AUX_DIGITAL"},
462 {AUDIO_DEVICE_OUT_HDMI, "HDMI"},
463 {AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET,"ANLG_DOCK_HEADSET"},
464 {AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET,"DGTL_DOCK_HEADSET"},
465 {AUDIO_DEVICE_OUT_USB_ACCESSORY, "USB_ACCESSORY"},
466 {AUDIO_DEVICE_OUT_USB_DEVICE, "USB_DEVICE"},
467 {AUDIO_DEVICE_OUT_TELEPHONY_TX, "TELEPHONY_TX"},
468 {AUDIO_DEVICE_OUT_LINE, "LINE"},
469 {AUDIO_DEVICE_OUT_HDMI_ARC, "HDMI_ARC"},
470 {AUDIO_DEVICE_OUT_SPDIF, "SPDIF"},
471 {AUDIO_DEVICE_OUT_FM, "FM"},
472 {AUDIO_DEVICE_OUT_AUX_LINE, "AUX_LINE"},
473 {AUDIO_DEVICE_OUT_SPEAKER_SAFE, "SPEAKER_SAFE"},
474 {AUDIO_DEVICE_OUT_IP, "IP"},
Eric Laurent58545be2016-02-22 18:54:20 -0800475 {AUDIO_DEVICE_OUT_BUS, "BUS"},
Glenn Kasten818da522015-12-02 13:53:26 -0800476 {AUDIO_DEVICE_NONE, "NONE"}, // must be last
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800477 }, mappingsIn[] = {
Glenn Kasten818da522015-12-02 13:53:26 -0800478 {AUDIO_DEVICE_IN_COMMUNICATION, "COMMUNICATION"},
479 {AUDIO_DEVICE_IN_AMBIENT, "AMBIENT"},
480 {AUDIO_DEVICE_IN_BUILTIN_MIC, "BUILTIN_MIC"},
481 {AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET, "BLUETOOTH_SCO_HEADSET"},
482 {AUDIO_DEVICE_IN_WIRED_HEADSET, "WIRED_HEADSET"},
483 {AUDIO_DEVICE_IN_AUX_DIGITAL, "AUX_DIGITAL"},
484 {AUDIO_DEVICE_IN_VOICE_CALL, "VOICE_CALL"},
485 {AUDIO_DEVICE_IN_TELEPHONY_RX, "TELEPHONY_RX"},
486 {AUDIO_DEVICE_IN_BACK_MIC, "BACK_MIC"},
487 {AUDIO_DEVICE_IN_REMOTE_SUBMIX, "REMOTE_SUBMIX"},
488 {AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET, "ANLG_DOCK_HEADSET"},
489 {AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET, "DGTL_DOCK_HEADSET"},
490 {AUDIO_DEVICE_IN_USB_ACCESSORY, "USB_ACCESSORY"},
491 {AUDIO_DEVICE_IN_USB_DEVICE, "USB_DEVICE"},
492 {AUDIO_DEVICE_IN_FM_TUNER, "FM_TUNER"},
493 {AUDIO_DEVICE_IN_TV_TUNER, "TV_TUNER"},
494 {AUDIO_DEVICE_IN_LINE, "LINE"},
495 {AUDIO_DEVICE_IN_SPDIF, "SPDIF"},
496 {AUDIO_DEVICE_IN_BLUETOOTH_A2DP, "BLUETOOTH_A2DP"},
497 {AUDIO_DEVICE_IN_LOOPBACK, "LOOPBACK"},
498 {AUDIO_DEVICE_IN_IP, "IP"},
Eric Laurent58545be2016-02-22 18:54:20 -0800499 {AUDIO_DEVICE_IN_BUS, "BUS"},
Glenn Kasten818da522015-12-02 13:53:26 -0800500 {AUDIO_DEVICE_NONE, "NONE"}, // must be last
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800501 };
502 String8 result;
503 audio_devices_t allDevices = AUDIO_DEVICE_NONE;
504 const mapping *entry;
505 if (devices & AUDIO_DEVICE_BIT_IN) {
506 devices &= ~AUDIO_DEVICE_BIT_IN;
507 entry = mappingsIn;
508 } else {
509 entry = mappingsOut;
510 }
511 for ( ; entry->mDevices != AUDIO_DEVICE_NONE; entry++) {
512 allDevices = (audio_devices_t) (allDevices | entry->mDevices);
513 if (devices & entry->mDevices) {
514 if (!result.isEmpty()) {
515 result.append("|");
516 }
517 result.append(entry->mString);
518 }
519 }
520 if (devices & ~allDevices) {
521 if (!result.isEmpty()) {
522 result.append("|");
523 }
524 result.appendFormat("0x%X", devices & ~allDevices);
525 }
526 if (result.isEmpty()) {
527 result.append(entry->mString);
528 }
529 return result;
530}
531
532String8 inputFlagsToString(audio_input_flags_t flags)
533{
534 static const struct mapping {
535 audio_input_flags_t mFlag;
536 const char * mString;
537 } mappings[] = {
Glenn Kasten818da522015-12-02 13:53:26 -0800538 {AUDIO_INPUT_FLAG_FAST, "FAST"},
539 {AUDIO_INPUT_FLAG_HW_HOTWORD, "HW_HOTWORD"},
540 {AUDIO_INPUT_FLAG_RAW, "RAW"},
541 {AUDIO_INPUT_FLAG_SYNC, "SYNC"},
542 {AUDIO_INPUT_FLAG_NONE, "NONE"}, // must be last
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800543 };
544 String8 result;
545 audio_input_flags_t allFlags = AUDIO_INPUT_FLAG_NONE;
546 const mapping *entry;
547 for (entry = mappings; entry->mFlag != AUDIO_INPUT_FLAG_NONE; entry++) {
548 allFlags = (audio_input_flags_t) (allFlags | entry->mFlag);
549 if (flags & entry->mFlag) {
550 if (!result.isEmpty()) {
551 result.append("|");
552 }
553 result.append(entry->mString);
554 }
555 }
556 if (flags & ~allFlags) {
557 if (!result.isEmpty()) {
558 result.append("|");
559 }
560 result.appendFormat("0x%X", flags & ~allFlags);
561 }
562 if (result.isEmpty()) {
563 result.append(entry->mString);
564 }
565 return result;
566}
567
568String8 outputFlagsToString(audio_output_flags_t flags)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700569{
570 static const struct mapping {
571 audio_output_flags_t mFlag;
572 const char * mString;
573 } mappings[] = {
Glenn Kasten818da522015-12-02 13:53:26 -0800574 {AUDIO_OUTPUT_FLAG_DIRECT, "DIRECT"},
575 {AUDIO_OUTPUT_FLAG_PRIMARY, "PRIMARY"},
576 {AUDIO_OUTPUT_FLAG_FAST, "FAST"},
577 {AUDIO_OUTPUT_FLAG_DEEP_BUFFER, "DEEP_BUFFER"},
578 {AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,"COMPRESS_OFFLOAD"},
579 {AUDIO_OUTPUT_FLAG_NON_BLOCKING, "NON_BLOCKING"},
580 {AUDIO_OUTPUT_FLAG_HW_AV_SYNC, "HW_AV_SYNC"},
581 {AUDIO_OUTPUT_FLAG_RAW, "RAW"},
582 {AUDIO_OUTPUT_FLAG_SYNC, "SYNC"},
583 {AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO, "IEC958_NONAUDIO"},
584 {AUDIO_OUTPUT_FLAG_NONE, "NONE"}, // must be last
Glenn Kasten97b7b752014-09-28 13:04:24 -0700585 };
586 String8 result;
587 audio_output_flags_t allFlags = AUDIO_OUTPUT_FLAG_NONE;
588 const mapping *entry;
589 for (entry = mappings; entry->mFlag != AUDIO_OUTPUT_FLAG_NONE; entry++) {
590 allFlags = (audio_output_flags_t) (allFlags | entry->mFlag);
591 if (flags & entry->mFlag) {
592 if (!result.isEmpty()) {
593 result.append("|");
594 }
595 result.append(entry->mString);
596 }
597 }
598 if (flags & ~allFlags) {
599 if (!result.isEmpty()) {
600 result.append("|");
601 }
602 result.appendFormat("0x%X", flags & ~allFlags);
603 }
604 if (result.isEmpty()) {
605 result.append(entry->mString);
606 }
607 return result;
608}
609
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800610const char *sourceToString(audio_source_t source)
611{
612 switch (source) {
613 case AUDIO_SOURCE_DEFAULT: return "default";
614 case AUDIO_SOURCE_MIC: return "mic";
615 case AUDIO_SOURCE_VOICE_UPLINK: return "voice uplink";
616 case AUDIO_SOURCE_VOICE_DOWNLINK: return "voice downlink";
617 case AUDIO_SOURCE_VOICE_CALL: return "voice call";
618 case AUDIO_SOURCE_CAMCORDER: return "camcorder";
619 case AUDIO_SOURCE_VOICE_RECOGNITION: return "voice recognition";
620 case AUDIO_SOURCE_VOICE_COMMUNICATION: return "voice communication";
621 case AUDIO_SOURCE_REMOTE_SUBMIX: return "remote submix";
rago8a397d52015-12-02 11:27:57 -0800622 case AUDIO_SOURCE_UNPROCESSED: return "unprocessed";
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800623 case AUDIO_SOURCE_FM_TUNER: return "FM tuner";
624 case AUDIO_SOURCE_HOTWORD: return "hotword";
625 default: return "unknown";
626 }
627}
628
Eric Laurent81784c32012-11-19 14:55:58 -0800629AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -0700630 audio_devices_t outDevice, audio_devices_t inDevice, type_t type, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -0800631 : Thread(false /*canCallJava*/),
632 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700633 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700634 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800635 // are set by PlaybackThread::readOutputParameters_l() or
636 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700637 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800638 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700639 mPrevOutDevice(AUDIO_DEVICE_NONE), mPrevInDevice(AUDIO_DEVICE_NONE),
640 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800641 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700642 mDeathRecipient(new PMDeathRecipient(this)),
Wei Jia3f273d12015-11-24 09:06:49 -0800643 mSystemReady(systemReady),
644 mNotifiedBatteryStart(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800645{
Eric Laurent296fb132015-05-01 11:38:42 -0700646 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800647}
648
649AudioFlinger::ThreadBase::~ThreadBase()
650{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700651 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700652 mConfigEvents.clear();
653
Eric Laurent81784c32012-11-19 14:55:58 -0800654 // do not lock the mutex in destructor
655 releaseWakeLock_l();
656 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800657 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800658 binder->unlinkToDeath(mDeathRecipient);
659 }
660}
661
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700662status_t AudioFlinger::ThreadBase::readyToRun()
663{
664 status_t status = initCheck();
665 if (status == NO_ERROR) {
666 ALOGI("AudioFlinger's thread %p ready to run", this);
667 } else {
668 ALOGE("No working audio driver found.");
669 }
670 return status;
671}
672
Eric Laurent81784c32012-11-19 14:55:58 -0800673void AudioFlinger::ThreadBase::exit()
674{
675 ALOGV("ThreadBase::exit");
676 // do any cleanup required for exit to succeed
677 preExit();
678 {
679 // This lock prevents the following race in thread (uniprocessor for illustration):
680 // if (!exitPending()) {
681 // // context switch from here to exit()
682 // // exit() calls requestExit(), what exitPending() observes
683 // // exit() calls signal(), which is dropped since no waiters
684 // // context switch back from exit() to here
685 // mWaitWorkCV.wait(...);
686 // // now thread is hung
687 // }
688 AutoMutex lock(mLock);
689 requestExit();
690 mWaitWorkCV.broadcast();
691 }
692 // When Thread::requestExitAndWait is made virtual and this method is renamed to
693 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
694 requestExitAndWait();
695}
696
697status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
698{
Eric Laurent81784c32012-11-19 14:55:58 -0800699 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
700 Mutex::Autolock _l(mLock);
701
Eric Laurent10351942014-05-08 18:49:52 -0700702 return sendSetParameterConfigEvent_l(keyValuePairs);
703}
704
705// sendConfigEvent_l() must be called with ThreadBase::mLock held
706// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
707status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
708{
709 status_t status = NO_ERROR;
710
Eric Laurent72e3f392015-05-20 14:43:50 -0700711 if (event->mRequiresSystemReady && !mSystemReady) {
712 event->mWaitStatus = false;
713 mPendingConfigEvents.add(event);
714 return status;
715 }
Eric Laurent10351942014-05-08 18:49:52 -0700716 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700717 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800718 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700719 mLock.unlock();
720 {
721 Mutex::Autolock _l(event->mLock);
722 while (event->mWaitStatus) {
723 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
724 event->mStatus = TIMED_OUT;
725 event->mWaitStatus = false;
726 }
727 }
728 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800729 }
Eric Laurent10351942014-05-08 18:49:52 -0700730 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800731 return status;
732}
733
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700734void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800735{
736 Mutex::Autolock _l(mLock);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700737 sendIoConfigEvent_l(event, pid);
Eric Laurent81784c32012-11-19 14:55:58 -0800738}
739
740// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700741void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800742{
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700743 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid);
Eric Laurent10351942014-05-08 18:49:52 -0700744 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800745}
746
Eric Laurent72e3f392015-05-20 14:43:50 -0700747void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio)
748{
749 Mutex::Autolock _l(mLock);
750 sendPrioConfigEvent_l(pid, tid, prio);
751}
752
Eric Laurent81784c32012-11-19 14:55:58 -0800753// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
754void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
755{
Eric Laurent10351942014-05-08 18:49:52 -0700756 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio);
757 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800758}
759
Eric Laurent10351942014-05-08 18:49:52 -0700760// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
761status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800762{
Andy Hung2ddee192015-12-18 17:34:44 -0800763 sp<ConfigEvent> configEvent;
764 AudioParameter param(keyValuePair);
765 int value;
766 if (param.getInt(String8(AUDIO_PARAMETER_MONO_OUTPUT), value) == NO_ERROR) {
767 setMasterMono_l(value != 0);
768 if (param.size() == 1) {
769 return NO_ERROR; // should be a solo parameter - we don't pass down
770 }
771 param.remove(String8(AUDIO_PARAMETER_MONO_OUTPUT));
772 configEvent = new SetParameterConfigEvent(param.toString());
773 } else {
774 configEvent = new SetParameterConfigEvent(keyValuePair);
775 }
Eric Laurent10351942014-05-08 18:49:52 -0700776 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700777}
778
Eric Laurent1c333e22014-05-20 10:48:17 -0700779status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
780 const struct audio_patch *patch,
781 audio_patch_handle_t *handle)
782{
783 Mutex::Autolock _l(mLock);
784 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
785 status_t status = sendConfigEvent_l(configEvent);
786 if (status == NO_ERROR) {
787 CreateAudioPatchConfigEventData *data =
788 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
789 *handle = data->mHandle;
790 }
791 return status;
792}
793
794status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
795 const audio_patch_handle_t handle)
796{
797 Mutex::Autolock _l(mLock);
798 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
799 return sendConfigEvent_l(configEvent);
800}
801
802
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700803// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700804void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700805{
Eric Laurent10351942014-05-08 18:49:52 -0700806 bool configChanged = false;
807
Eric Laurent81784c32012-11-19 14:55:58 -0800808 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700809 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700810 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800811 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700812 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700813 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700814 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
815 // FIXME Need to understand why this has to be done asynchronously
816 int err = requestPriority(data->mPid, data->mTid, data->mPrio,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700817 true /*asynchronous*/);
818 if (err != 0) {
819 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700820 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700821 }
822 } break;
823 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700824 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700825 ioConfigChanged(data->mEvent, data->mPid);
Eric Laurent10351942014-05-08 18:49:52 -0700826 } break;
827 case CFG_EVENT_SET_PARAMETER: {
828 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
829 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
830 configChanged = true;
Glenn Kastend5418eb2013-08-14 13:11:06 -0700831 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700832 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700833 case CFG_EVENT_CREATE_AUDIO_PATCH: {
834 CreateAudioPatchConfigEventData *data =
835 (CreateAudioPatchConfigEventData *)event->mData.get();
836 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
837 } break;
838 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
839 ReleaseAudioPatchConfigEventData *data =
840 (ReleaseAudioPatchConfigEventData *)event->mData.get();
841 event->mStatus = releaseAudioPatch_l(data->mHandle);
842 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700843 default:
Eric Laurent10351942014-05-08 18:49:52 -0700844 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700845 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800846 }
Eric Laurent10351942014-05-08 18:49:52 -0700847 {
848 Mutex::Autolock _l(event->mLock);
849 if (event->mWaitStatus) {
850 event->mWaitStatus = false;
851 event->mCond.signal();
852 }
853 }
854 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
855 }
856
857 if (configChanged) {
858 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800859 }
Eric Laurent81784c32012-11-19 14:55:58 -0800860}
861
Marco Nelissenb2208842014-02-07 14:00:50 -0800862String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
863 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700864 const audio_channel_representation_t representation =
865 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700866
867 switch (representation) {
868 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
869 if (output) {
870 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
871 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
872 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
873 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
874 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
875 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
876 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
877 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
878 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
879 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
880 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
881 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
882 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
883 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
884 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
885 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
886 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
887 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
888 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
889 } else {
890 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
891 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
892 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
893 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
894 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
895 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
896 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
897 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
898 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
899 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
900 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
901 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
902 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
903 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
904 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
905 }
906 const int len = s.length();
907 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -0700908 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -0700909 s.unlockBuffer(len - 2); // remove trailing ", "
910 }
911 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800912 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700913 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
914 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
915 return s;
916 default:
917 s.appendFormat("unknown mask, representation:%d bits:%#x",
918 representation, audio_channel_mask_get_bits(mask));
919 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800920 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800921}
922
Glenn Kasten0f11b512014-01-31 16:18:54 -0800923void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800924{
925 const size_t SIZE = 256;
926 char buffer[SIZE];
927 String8 result;
928
929 bool locked = AudioFlinger::dumpTryLock(mLock);
930 if (!locked) {
Glenn Kasten97b7b752014-09-28 13:04:24 -0700931 dprintf(fd, "thread %p may be deadlocked\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -0800932 }
933
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800934 dprintf(fd, " Thread name: %s\n", mThreadName);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700935 dprintf(fd, " I/O handle: %d\n", mId);
936 dprintf(fd, " TID: %d\n", getTid());
937 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700938 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700939 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700940 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat));
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700941 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700942 dprintf(fd, " Channel count: %u\n", mChannelCount);
943 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800944 channelMaskToString(mChannelMask, mType != RECORD).string());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700945 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat));
946 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700947 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800948 size_t numConfig = mConfigEvents.size();
949 if (numConfig) {
950 for (size_t i = 0; i < numConfig; i++) {
951 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700952 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800953 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700954 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800955 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700956 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800957 }
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800958 dprintf(fd, " Output device: %#x (%s)\n", mOutDevice, devicesToString(mOutDevice).string());
959 dprintf(fd, " Input device: %#x (%s)\n", mInDevice, devicesToString(mInDevice).string());
960 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, sourceToString(mAudioSource));
Eric Laurent81784c32012-11-19 14:55:58 -0800961
962 if (locked) {
963 mLock.unlock();
964 }
965}
966
967void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
968{
969 const size_t SIZE = 256;
970 char buffer[SIZE];
971 String8 result;
972
Marco Nelissenb2208842014-02-07 14:00:50 -0800973 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000974 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800975 write(fd, buffer, strlen(buffer));
976
Marco Nelissenb2208842014-02-07 14:00:50 -0800977 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800978 sp<EffectChain> chain = mEffectChains[i];
979 if (chain != 0) {
980 chain->dump(fd, args);
981 }
982 }
983}
984
Marco Nelissene14a5d62013-10-03 08:51:24 -0700985void AudioFlinger::ThreadBase::acquireWakeLock(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800986{
987 Mutex::Autolock _l(mLock);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700988 acquireWakeLock_l(uid);
Eric Laurent81784c32012-11-19 14:55:58 -0800989}
990
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100991String16 AudioFlinger::ThreadBase::getWakeLockTag()
992{
993 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -0800994 case MIXER:
995 return String16("AudioMix");
996 case DIRECT:
997 return String16("AudioDirectOut");
998 case DUPLICATING:
999 return String16("AudioDup");
1000 case RECORD:
1001 return String16("AudioIn");
1002 case OFFLOAD:
1003 return String16("AudioOffload");
1004 default:
1005 ALOG_ASSERT(false);
1006 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001007 }
1008}
1009
Marco Nelissene14a5d62013-10-03 08:51:24 -07001010void AudioFlinger::ThreadBase::acquireWakeLock_l(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -08001011{
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001012 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001013 if (mPowerManager != 0) {
1014 sp<IBinder> binder = new BBinder();
Marco Nelissene14a5d62013-10-03 08:51:24 -07001015 status_t status;
1016 if (uid >= 0) {
Eric Laurent547789d2013-10-04 11:46:55 -07001017 status = mPowerManager->acquireWakeLockWithUid(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -07001018 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001019 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -07001020 String16("audioserver"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -07001021 uid,
1022 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -07001023 } else {
Eric Laurent547789d2013-10-04 11:46:55 -07001024 status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -07001025 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001026 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -07001027 String16("audioserver"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -07001028 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -07001029 }
Eric Laurent81784c32012-11-19 14:55:58 -08001030 if (status == NO_ERROR) {
1031 mWakeLockToken = binder;
1032 }
Glenn Kastend7dca052015-03-05 16:05:54 -08001033 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -08001034 }
Wei Jia3f273d12015-11-24 09:06:49 -08001035
1036 if (!mNotifiedBatteryStart) {
1037 BatteryNotifier::getInstance().noteStartAudio();
1038 mNotifiedBatteryStart = true;
1039 }
Andy Hung3f0c9022016-01-15 17:49:46 -08001040 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -08001041 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
1042 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -08001043}
1044
1045void AudioFlinger::ThreadBase::releaseWakeLock()
1046{
1047 Mutex::Autolock _l(mLock);
1048 releaseWakeLock_l();
1049}
1050
1051void AudioFlinger::ThreadBase::releaseWakeLock_l()
1052{
Andy Hung3f0c9022016-01-15 17:49:46 -08001053 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -08001054 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001055 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001056 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -07001057 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
1058 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -08001059 }
1060 mWakeLockToken.clear();
1061 }
Wei Jia3f273d12015-11-24 09:06:49 -08001062
1063 if (mNotifiedBatteryStart) {
1064 BatteryNotifier::getInstance().noteStopAudio();
1065 mNotifiedBatteryStart = false;
1066 }
Eric Laurent81784c32012-11-19 14:55:58 -08001067}
1068
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001069void AudioFlinger::ThreadBase::updateWakeLockUids(const SortedVector<int> &uids) {
1070 Mutex::Autolock _l(mLock);
1071 updateWakeLockUids_l(uids);
1072}
1073
1074void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -07001075 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001076 // use checkService() to avoid blocking if power service is not up yet
1077 sp<IBinder> binder =
1078 defaultServiceManager()->checkService(String16("power"));
1079 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001080 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001081 } else {
1082 mPowerManager = interface_cast<IPowerManager>(binder);
1083 binder->linkToDeath(mDeathRecipient);
1084 }
1085 }
1086}
1087
1088void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<int> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001089 getPowerManager_l();
Andy Hung438e7572015-12-14 15:51:17 -08001090 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
1091 if (mSystemReady) {
1092 ALOGE("no wake lock to update, but system ready!");
1093 } else {
1094 ALOGW("no wake lock to update, system not ready yet");
1095 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001096 return;
1097 }
1098 if (mPowerManager != 0) {
1099 sp<IBinder> binder = new BBinder();
1100 status_t status;
Glenn Kasten3abc2de2014-09-05 16:45:52 -07001101 status = mPowerManager->updateWakeLockUids(mWakeLockToken, uids.size(), uids.array(),
1102 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent4d231dc2016-03-11 18:38:23 -08001103 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001104 }
1105}
1106
Eric Laurent81784c32012-11-19 14:55:58 -08001107void AudioFlinger::ThreadBase::clearPowerManager()
1108{
1109 Mutex::Autolock _l(mLock);
1110 releaseWakeLock_l();
1111 mPowerManager.clear();
1112}
1113
Glenn Kasten0f11b512014-01-31 16:18:54 -08001114void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001115{
1116 sp<ThreadBase> thread = mThread.promote();
1117 if (thread != 0) {
1118 thread->clearPowerManager();
1119 }
1120 ALOGW("power manager service died !!!");
1121}
1122
1123void AudioFlinger::ThreadBase::setEffectSuspended(
Glenn Kastend848eb42016-03-08 13:42:11 -08001124 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001125{
1126 Mutex::Autolock _l(mLock);
1127 setEffectSuspended_l(type, suspend, sessionId);
1128}
1129
1130void AudioFlinger::ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001131 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001132{
1133 sp<EffectChain> chain = getEffectChain_l(sessionId);
1134 if (chain != 0) {
1135 if (type != NULL) {
1136 chain->setEffectSuspended_l(type, suspend);
1137 } else {
1138 chain->setEffectSuspendedAll_l(suspend);
1139 }
1140 }
1141
1142 updateSuspendedSessions_l(type, suspend, sessionId);
1143}
1144
1145void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1146{
1147 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1148 if (index < 0) {
1149 return;
1150 }
1151
1152 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1153 mSuspendedSessions.valueAt(index);
1154
1155 for (size_t i = 0; i < sessionEffects.size(); i++) {
1156 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1157 for (int j = 0; j < desc->mRefCount; j++) {
1158 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1159 chain->setEffectSuspendedAll_l(true);
1160 } else {
1161 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1162 desc->mType.timeLow);
1163 chain->setEffectSuspended_l(&desc->mType, true);
1164 }
1165 }
1166 }
1167}
1168
1169void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1170 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001171 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001172{
1173 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1174
1175 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1176
1177 if (suspend) {
1178 if (index >= 0) {
1179 sessionEffects = mSuspendedSessions.valueAt(index);
1180 } else {
1181 mSuspendedSessions.add(sessionId, sessionEffects);
1182 }
1183 } else {
1184 if (index < 0) {
1185 return;
1186 }
1187 sessionEffects = mSuspendedSessions.valueAt(index);
1188 }
1189
1190
1191 int key = EffectChain::kKeyForSuspendAll;
1192 if (type != NULL) {
1193 key = type->timeLow;
1194 }
1195 index = sessionEffects.indexOfKey(key);
1196
1197 sp<SuspendedSessionDesc> desc;
1198 if (suspend) {
1199 if (index >= 0) {
1200 desc = sessionEffects.valueAt(index);
1201 } else {
1202 desc = new SuspendedSessionDesc();
1203 if (type != NULL) {
1204 desc->mType = *type;
1205 }
1206 sessionEffects.add(key, desc);
1207 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1208 }
1209 desc->mRefCount++;
1210 } else {
1211 if (index < 0) {
1212 return;
1213 }
1214 desc = sessionEffects.valueAt(index);
1215 if (--desc->mRefCount == 0) {
1216 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1217 sessionEffects.removeItemsAt(index);
1218 if (sessionEffects.isEmpty()) {
1219 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1220 sessionId);
1221 mSuspendedSessions.removeItem(sessionId);
1222 }
1223 }
1224 }
1225 if (!sessionEffects.isEmpty()) {
1226 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1227 }
1228}
1229
1230void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(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 Mutex::Autolock _l(mLock);
1235 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1236}
1237
1238void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1239 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001240 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001241{
1242 if (mType != RECORD) {
1243 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1244 // another session. This gives the priority to well behaved effect control panels
1245 // and applications not using global effects.
1246 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1247 // global effects
1248 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1249 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1250 }
1251 }
1252
1253 sp<EffectChain> chain = getEffectChain_l(sessionId);
1254 if (chain != 0) {
1255 chain->checkSuspendOnEffectEnabled(effect, enabled);
1256 }
1257}
1258
Eric Laurent4c415062016-06-17 16:14:16 -07001259// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1260status_t AudioFlinger::RecordThread::checkEffectCompatibility_l(
1261 const effect_descriptor_t *desc, audio_session_t sessionId)
1262{
1263 // No global effect sessions on record threads
1264 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1265 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1266 desc->name, mThreadName);
1267 return BAD_VALUE;
1268 }
1269 // only pre processing effects on record thread
1270 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1271 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1272 desc->name, mThreadName);
1273 return BAD_VALUE;
1274 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001275
1276 // always allow effects without processing load or latency
1277 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1278 return NO_ERROR;
1279 }
1280
Eric Laurent4c415062016-06-17 16:14:16 -07001281 audio_input_flags_t flags = mInput->flags;
1282 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1283 if (flags & AUDIO_INPUT_FLAG_RAW) {
1284 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1285 desc->name, mThreadName);
1286 return BAD_VALUE;
1287 }
1288 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1289 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1290 desc->name, mThreadName);
1291 return BAD_VALUE;
1292 }
1293 }
1294 return NO_ERROR;
1295}
1296
1297// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1298status_t AudioFlinger::PlaybackThread::checkEffectCompatibility_l(
1299 const effect_descriptor_t *desc, audio_session_t sessionId)
1300{
1301 // no preprocessing on playback threads
1302 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
1303 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback"
1304 " thread %s", desc->name, mThreadName);
1305 return BAD_VALUE;
1306 }
1307
1308 switch (mType) {
1309 case MIXER: {
1310 // Reject any effect on mixer multichannel sinks.
1311 // TODO: fix both format and multichannel issues with effects.
1312 if (mChannelCount != FCC_2) {
1313 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d) on MIXER"
1314 " thread %s", desc->name, mChannelCount, mThreadName);
1315 return BAD_VALUE;
1316 }
1317 audio_output_flags_t flags = mOutput->flags;
1318 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1319 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1320 // global effects are applied only to non fast tracks if they are SW
1321 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1322 break;
1323 }
1324 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1325 // only post processing on output stage session
1326 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1327 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1328 " on output stage session", desc->name);
1329 return BAD_VALUE;
1330 }
1331 } else {
1332 // no restriction on effects applied on non fast tracks
1333 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1334 break;
1335 }
1336 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001337
1338 // always allow effects without processing load or latency
1339 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1340 break;
1341 }
Eric Laurent4c415062016-06-17 16:14:16 -07001342 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
1343 ALOGW("checkEffectCompatibility_l(): effect %s on playback thread in raw mode",
1344 desc->name);
1345 return BAD_VALUE;
1346 }
1347 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1348 ALOGW("checkEffectCompatibility_l(): non HW effect %s on playback thread"
1349 " in fast mode", desc->name);
1350 return BAD_VALUE;
1351 }
1352 }
1353 } break;
1354 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001355 // nothing actionable on offload threads, if the effect:
1356 // - is offloadable: the effect can be created
1357 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1358 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001359 break;
1360 case DIRECT:
1361 // Reject any effect on Direct output threads for now, since the format of
1362 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1363 ALOGW("checkEffectCompatibility_l(): effect %s on DIRECT output thread %s",
1364 desc->name, mThreadName);
1365 return BAD_VALUE;
1366 case DUPLICATING:
1367 // Reject any effect on mixer multichannel sinks.
1368 // TODO: fix both format and multichannel issues with effects.
1369 if (mChannelCount != FCC_2) {
1370 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d)"
1371 " on DUPLICATING thread %s", desc->name, mChannelCount, mThreadName);
1372 return BAD_VALUE;
1373 }
1374 if ((sessionId == AUDIO_SESSION_OUTPUT_STAGE) || (sessionId == AUDIO_SESSION_OUTPUT_MIX)) {
1375 ALOGW("checkEffectCompatibility_l(): global effect %s on DUPLICATING"
1376 " thread %s", desc->name, mThreadName);
1377 return BAD_VALUE;
1378 }
1379 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
1380 ALOGW("checkEffectCompatibility_l(): post processing effect %s on"
1381 " DUPLICATING thread %s", desc->name, mThreadName);
1382 return BAD_VALUE;
1383 }
1384 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1385 ALOGW("checkEffectCompatibility_l(): HW tunneled effect %s on"
1386 " DUPLICATING thread %s", desc->name, mThreadName);
1387 return BAD_VALUE;
1388 }
1389 break;
1390 default:
1391 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1392 }
1393
1394 return NO_ERROR;
1395}
1396
Eric Laurent81784c32012-11-19 14:55:58 -08001397// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1398sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1399 const sp<AudioFlinger::Client>& client,
1400 const sp<IEffectClient>& effectClient,
1401 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001402 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001403 effect_descriptor_t *desc,
1404 int *enabled,
Glenn Kasten9156ef32013-08-06 15:39:08 -07001405 status_t *status)
Eric Laurent81784c32012-11-19 14:55:58 -08001406{
1407 sp<EffectModule> effect;
1408 sp<EffectHandle> handle;
1409 status_t lStatus;
1410 sp<EffectChain> chain;
1411 bool chainCreated = false;
1412 bool effectCreated = false;
1413 bool effectRegistered = false;
1414
1415 lStatus = initCheck();
1416 if (lStatus != NO_ERROR) {
1417 ALOGW("createEffect_l() Audio driver not initialized.");
1418 goto Exit;
1419 }
1420
Eric Laurent81784c32012-11-19 14:55:58 -08001421 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1422
1423 { // scope for mLock
1424 Mutex::Autolock _l(mLock);
1425
Eric Laurent4c415062016-06-17 16:14:16 -07001426 lStatus = checkEffectCompatibility_l(desc, sessionId);
1427 if (lStatus != NO_ERROR) {
1428 goto Exit;
1429 }
1430
Eric Laurent81784c32012-11-19 14:55:58 -08001431 // check for existing effect chain with the requested audio session
1432 chain = getEffectChain_l(sessionId);
1433 if (chain == 0) {
1434 // create a new chain for this session
1435 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1436 chain = new EffectChain(this, sessionId);
1437 addEffectChain_l(chain);
1438 chain->setStrategy(getStrategyForSession_l(sessionId));
1439 chainCreated = true;
1440 } else {
1441 effect = chain->getEffectFromDesc_l(desc);
1442 }
1443
1444 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1445
1446 if (effect == 0) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08001447 audio_unique_id_t id = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001448 // Check CPU and memory usage
1449 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
1450 if (lStatus != NO_ERROR) {
1451 goto Exit;
1452 }
1453 effectRegistered = true;
1454 // create a new effect module if none present in the chain
1455 effect = new EffectModule(this, chain, desc, id, sessionId);
1456 lStatus = effect->status();
1457 if (lStatus != NO_ERROR) {
1458 goto Exit;
1459 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001460 effect->setOffloaded(mType == OFFLOAD, mId);
1461
Eric Laurent81784c32012-11-19 14:55:58 -08001462 lStatus = chain->addEffect_l(effect);
1463 if (lStatus != NO_ERROR) {
1464 goto Exit;
1465 }
1466 effectCreated = true;
1467
1468 effect->setDevice(mOutDevice);
1469 effect->setDevice(mInDevice);
1470 effect->setMode(mAudioFlinger->getMode());
1471 effect->setAudioSource(mAudioSource);
1472 }
1473 // create effect handle and connect it to effect module
1474 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001475 lStatus = handle->initCheck();
1476 if (lStatus == OK) {
1477 lStatus = effect->addHandle(handle.get());
1478 }
Eric Laurent81784c32012-11-19 14:55:58 -08001479 if (enabled != NULL) {
1480 *enabled = (int)effect->isEnabled();
1481 }
1482 }
1483
1484Exit:
1485 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1486 Mutex::Autolock _l(mLock);
1487 if (effectCreated) {
1488 chain->removeEffect_l(effect);
1489 }
1490 if (effectRegistered) {
1491 AudioSystem::unregisterEffect(effect->id());
1492 }
1493 if (chainCreated) {
1494 removeEffectChain_l(chain);
1495 }
1496 handle.clear();
1497 }
1498
Glenn Kasten9156ef32013-08-06 15:39:08 -07001499 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001500 return handle;
1501}
1502
Glenn Kastend848eb42016-03-08 13:42:11 -08001503sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1504 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001505{
1506 Mutex::Autolock _l(mLock);
1507 return getEffect_l(sessionId, effectId);
1508}
1509
Glenn Kastend848eb42016-03-08 13:42:11 -08001510sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1511 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001512{
1513 sp<EffectChain> chain = getEffectChain_l(sessionId);
1514 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1515}
1516
1517// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1518// PlaybackThread::mLock held
1519status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1520{
1521 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001522 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001523 sp<EffectChain> chain = getEffectChain_l(sessionId);
1524 bool chainCreated = false;
1525
Eric Laurent5baf2af2013-09-12 17:37:00 -07001526 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1527 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1528 this, effect->desc().name, effect->desc().flags);
1529
Eric Laurent81784c32012-11-19 14:55:58 -08001530 if (chain == 0) {
1531 // create a new chain for this session
1532 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1533 chain = new EffectChain(this, sessionId);
1534 addEffectChain_l(chain);
1535 chain->setStrategy(getStrategyForSession_l(sessionId));
1536 chainCreated = true;
1537 }
1538 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1539
1540 if (chain->getEffectFromId_l(effect->id()) != 0) {
1541 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1542 this, effect->desc().name, chain.get());
1543 return BAD_VALUE;
1544 }
1545
Eric Laurent5baf2af2013-09-12 17:37:00 -07001546 effect->setOffloaded(mType == OFFLOAD, mId);
1547
Eric Laurent81784c32012-11-19 14:55:58 -08001548 status_t status = chain->addEffect_l(effect);
1549 if (status != NO_ERROR) {
1550 if (chainCreated) {
1551 removeEffectChain_l(chain);
1552 }
1553 return status;
1554 }
1555
1556 effect->setDevice(mOutDevice);
1557 effect->setDevice(mInDevice);
1558 effect->setMode(mAudioFlinger->getMode());
1559 effect->setAudioSource(mAudioSource);
1560 return NO_ERROR;
1561}
1562
1563void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
1564
1565 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
1566 effect_descriptor_t desc = effect->desc();
1567 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1568 detachAuxEffect_l(effect->id());
1569 }
1570
1571 sp<EffectChain> chain = effect->chain().promote();
1572 if (chain != 0) {
1573 // remove effect chain if removing last effect
1574 if (chain->removeEffect_l(effect) == 0) {
1575 removeEffectChain_l(chain);
1576 }
1577 } else {
1578 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1579 }
1580}
1581
1582void AudioFlinger::ThreadBase::lockEffectChains_l(
1583 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1584{
1585 effectChains = mEffectChains;
1586 for (size_t i = 0; i < mEffectChains.size(); i++) {
1587 mEffectChains[i]->lock();
1588 }
1589}
1590
1591void AudioFlinger::ThreadBase::unlockEffectChains(
1592 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1593{
1594 for (size_t i = 0; i < effectChains.size(); i++) {
1595 effectChains[i]->unlock();
1596 }
1597}
1598
Glenn Kastend848eb42016-03-08 13:42:11 -08001599sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001600{
1601 Mutex::Autolock _l(mLock);
1602 return getEffectChain_l(sessionId);
1603}
1604
Glenn Kastend848eb42016-03-08 13:42:11 -08001605sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1606 const
Eric Laurent81784c32012-11-19 14:55:58 -08001607{
1608 size_t size = mEffectChains.size();
1609 for (size_t i = 0; i < size; i++) {
1610 if (mEffectChains[i]->sessionId() == sessionId) {
1611 return mEffectChains[i];
1612 }
1613 }
1614 return 0;
1615}
1616
1617void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1618{
1619 Mutex::Autolock _l(mLock);
1620 size_t size = mEffectChains.size();
1621 for (size_t i = 0; i < size; i++) {
1622 mEffectChains[i]->setMode_l(mode);
1623 }
1624}
1625
Eric Laurent83b88082014-06-20 18:31:16 -07001626void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1627{
1628 config->type = AUDIO_PORT_TYPE_MIX;
1629 config->ext.mix.handle = mId;
1630 config->sample_rate = mSampleRate;
1631 config->format = mFormat;
1632 config->channel_mask = mChannelMask;
1633 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1634 AUDIO_PORT_CONFIG_FORMAT;
1635}
1636
Eric Laurent72e3f392015-05-20 14:43:50 -07001637void AudioFlinger::ThreadBase::systemReady()
1638{
1639 Mutex::Autolock _l(mLock);
1640 if (mSystemReady) {
1641 return;
1642 }
1643 mSystemReady = true;
1644
1645 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1646 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1647 }
1648 mPendingConfigEvents.clear();
1649}
1650
Eric Laurent83b88082014-06-20 18:31:16 -07001651
Eric Laurent81784c32012-11-19 14:55:58 -08001652// ----------------------------------------------------------------------------
1653// Playback
1654// ----------------------------------------------------------------------------
1655
1656AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1657 AudioStreamOut* output,
1658 audio_io_handle_t id,
1659 audio_devices_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07001660 type_t type,
Eric Laurente93cc032016-05-05 10:15:10 -07001661 bool systemReady)
Eric Laurent72e3f392015-05-20 14:43:50 -07001662 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001663 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001664 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001665 mMixerBuffer(NULL),
1666 mMixerBufferSize(0),
1667 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1668 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001669 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001670 mEffectBuffer(NULL),
1671 mEffectBufferSize(0),
1672 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1673 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001674 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001675 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07001676 mSuspendedFrames(0),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001677 mActiveTracksGeneration(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001678 // mStreamTypes[] initialized in constructor body
1679 mOutput(output),
Andy Hung69488c42016-05-16 18:43:33 -07001680 mLastWriteTime(-1), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001681 mMixerStatus(MIXER_IDLE),
1682 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001683 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001684 mBytesRemaining(0),
1685 mCurrentWriteLength(0),
1686 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001687 mWriteAckSequence(0),
1688 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001689 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001690 mScreenState(AudioFlinger::mScreenState),
1691 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001692 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Andy Hunge10393e2015-06-12 13:59:33 -07001693 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001694{
Glenn Kastend7dca052015-03-05 16:05:54 -08001695 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1696 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001697
1698 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1699 // it would be safer to explicitly pass initial masterVolume/masterMute as
1700 // parameter.
1701 //
1702 // If the HAL we are using has support for master volume or master mute,
1703 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1704 // and the mute set to false).
1705 mMasterVolume = audioFlinger->masterVolume_l();
1706 mMasterMute = audioFlinger->masterMute_l();
1707 if (mOutput && mOutput->audioHwDev) {
1708 if (mOutput->audioHwDev->canSetMasterVolume()) {
1709 mMasterVolume = 1.0;
1710 }
1711
1712 if (mOutput->audioHwDev->canSetMasterMute()) {
1713 mMasterMute = false;
1714 }
1715 }
1716
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001717 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001718
Eric Laurent223fd5c2014-11-11 13:43:36 -08001719 // ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001720 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001721 stream = (audio_stream_type_t) (stream + 1)) {
1722 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1723 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1724 }
Eric Laurent81784c32012-11-19 14:55:58 -08001725}
1726
1727AudioFlinger::PlaybackThread::~PlaybackThread()
1728{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001729 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001730 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001731 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001732 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001733}
1734
1735void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1736{
1737 dumpInternals(fd, args);
1738 dumpTracks(fd, args);
1739 dumpEffectChains(fd, args);
1740}
1741
Glenn Kasten0f11b512014-01-31 16:18:54 -08001742void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001743{
1744 const size_t SIZE = 256;
1745 char buffer[SIZE];
1746 String8 result;
1747
Marco Nelissenb2208842014-02-07 14:00:50 -08001748 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001749 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1750 const stream_type_t *st = &mStreamTypes[i];
1751 if (i > 0) {
1752 result.appendFormat(", ");
1753 }
1754 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1755 if (st->mute) {
1756 result.append("M");
1757 }
1758 }
1759 result.append("\n");
1760 write(fd, result.string(), result.length());
1761 result.clear();
1762
Eric Laurent81784c32012-11-19 14:55:58 -08001763 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1764 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001765 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001766 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001767
1768 size_t numtracks = mTracks.size();
1769 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001770 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001771 size_t numactiveseen = 0;
1772 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001773 dprintf(fd, " of which %zu are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001774 Track::appendDumpHeader(result);
1775 for (size_t i = 0; i < numtracks; ++i) {
1776 sp<Track> track = mTracks[i];
1777 if (track != 0) {
1778 bool active = mActiveTracks.indexOf(track) >= 0;
1779 if (active) {
1780 numactiveseen++;
1781 }
1782 track->dump(buffer, SIZE, active);
1783 result.append(buffer);
1784 }
1785 }
1786 } else {
1787 result.append("\n");
1788 }
1789 if (numactiveseen != numactive) {
1790 // some tracks in the active list were not in the tracks list
1791 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1792 " not in the track list\n");
1793 result.append(buffer);
1794 Track::appendDumpHeader(result);
1795 for (size_t i = 0; i < numactive; ++i) {
1796 sp<Track> track = mActiveTracks[i].promote();
1797 if (track != 0 && mTracks.indexOf(track) < 0) {
1798 track->dump(buffer, SIZE, true);
1799 result.append(buffer);
1800 }
1801 }
1802 }
1803
1804 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001805}
1806
1807void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1808{
Glenn Kasten97b7b752014-09-28 13:04:24 -07001809 dprintf(fd, "\nOutput thread %p type %d (%s):\n", this, type(), threadTypeToString(type()));
Glenn Kasten44182c22015-03-05 17:12:23 -08001810
1811 dumpBase(fd, args);
1812
Elliott Hughes87cebad2014-05-22 10:14:43 -07001813 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001814 dprintf(fd, " Last write occurred (msecs): %llu\n",
1815 (unsigned long long) ns2ms(systemTime() - mLastWriteTime));
Elliott Hughes87cebad2014-05-22 10:14:43 -07001816 dprintf(fd, " Total writes: %d\n", mNumWrites);
1817 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1818 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1819 dprintf(fd, " Suspend count: %d\n", mSuspended);
1820 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1821 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1822 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1823 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08001824 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001825 AudioStreamOut *output = mOutput;
1826 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
1827 String8 flagsAsString = outputFlagsToString(flags);
1828 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n", output, flags, flagsAsString.string());
Eric Laurent81784c32012-11-19 14:55:58 -08001829}
1830
1831// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001832
1833void AudioFlinger::PlaybackThread::onFirstRef()
1834{
Glenn Kastend7dca052015-03-05 16:05:54 -08001835 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001836}
1837
1838// ThreadBase virtuals
1839void AudioFlinger::PlaybackThread::preExit()
1840{
1841 ALOGV(" preExit()");
1842 // FIXME this is using hard-coded strings but in the future, this functionality will be
1843 // converted to use audio HAL extensions required to support tunneling
1844 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1845}
1846
1847// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1848sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1849 const sp<AudioFlinger::Client>& client,
1850 audio_stream_type_t streamType,
1851 uint32_t sampleRate,
1852 audio_format_t format,
1853 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001854 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001855 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08001856 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07001857 audio_output_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08001858 pid_t tid,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001859 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -08001860 status_t *status)
1861{
Glenn Kasten74935e42013-12-19 08:56:45 -08001862 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001863 sp<Track> track;
1864 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07001865 audio_output_flags_t outputFlags = mOutput->flags;
1866
1867 // special case for FAST flag considered OK if fast mixer is present
1868 if (hasFastMixer()) {
1869 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
1870 }
1871
1872 // Check if requested flags are compatible with output stream flags
1873 if ((*flags & outputFlags) != *flags) {
1874 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
1875 *flags, outputFlags);
1876 *flags = (audio_output_flags_t)(*flags & outputFlags);
1877 }
Eric Laurent81784c32012-11-19 14:55:58 -08001878
Eric Laurent81784c32012-11-19 14:55:58 -08001879 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07001880 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08001881 if (
Eric Laurent81784c32012-11-19 14:55:58 -08001882 // PCM data
1883 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001884 // TODO: extract as a data library function that checks that a computationally
1885 // expensive downmixer is not required: isFastOutputChannelConversion()
Andy Hung9a592762014-07-21 21:56:01 -07001886 (channelMask == mChannelMask ||
Andy Hung1f439e12015-05-19 12:57:41 -07001887 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1888 (channelMask == AUDIO_CHANNEL_OUT_MONO
1889 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001890 // hardware sample rate
1891 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001892 // normal mixer has an associated fast mixer
1893 hasFastMixer() &&
1894 // there are sufficient fast track slots available
1895 (mFastTrackAvailMask != 0)
1896 // FIXME test that MixerThread for this fast track has a capable output HAL
1897 // FIXME add a permission test also?
1898 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07001899 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
1900 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001901 // read the fast track multiplier property the first time it is needed
1902 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1903 if (ok != 0) {
1904 ALOGE("%s pthread_once failed: %d", __func__, ok);
1905 }
Andy Hunge0a269a2016-03-23 15:13:42 -07001906 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08001907 }
Eric Laurent4c415062016-06-17 16:14:16 -07001908
1909 // check compatibility with audio effects.
1910 { // scope for mLock
1911 Mutex::Autolock _l(mLock);
1912 // do not accept RAW flag if post processing are present. Note that post processing on
1913 // a fast mixer are necessarily hardware
1914 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE);
1915 if (chain != 0) {
Eric Laurent122f7e72016-06-29 11:53:29 -07001916 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_RAW) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07001917 "AUDIO_OUTPUT_FLAG_RAW denied: post processing effect present");
1918 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_RAW);
1919 }
1920 // Do not accept FAST flag if software global effects are present
1921 chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
1922 if (chain != 0) {
Eric Laurent122f7e72016-06-29 11:53:29 -07001923 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_RAW) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07001924 "AUDIO_OUTPUT_FLAG_RAW denied: global effect present");
1925 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_RAW);
1926 if (chain->hasSoftwareEffect()) {
1927 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: software global effect present");
1928 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
1929 }
1930 }
1931 // Do not accept FAST flag if the session has software effects
1932 chain = getEffectChain_l(sessionId);
1933 if (chain != 0) {
Eric Laurent122f7e72016-06-29 11:53:29 -07001934 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_RAW) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07001935 "AUDIO_OUTPUT_FLAG_RAW denied: effect present on session");
1936 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_RAW);
1937 if (chain->hasSoftwareEffect()) {
1938 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: software effect present on session");
1939 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
1940 }
1941 }
1942 }
Eric Laurent122f7e72016-06-29 11:53:29 -07001943 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07001944 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
1945 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08001946 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001947 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
1948 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07001949 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001950 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08001951 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001952 audio_is_linear_pcm(format),
1953 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07001954 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08001955 }
1956 }
1957 // For normal PCM streaming tracks, update minimum frame count.
1958 // For compatibility with AudioTrack calculation, buffer depth is forced
1959 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1960 // This is probably too conservative, but legacy application code may depend on it.
1961 // If you change this calculation, also review the start threshold which is related.
Eric Laurent05067782016-06-01 18:27:28 -07001962 if (!(*flags & AUDIO_OUTPUT_FLAG_FAST)
Phil Burkfdb3c072016-02-09 10:47:02 -08001963 && audio_has_proportional_frames(format) && sharedBuffer == 0) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001964 // this must match AudioTrack.cpp calculateMinFrameCount().
1965 // TODO: Move to a common library
Eric Laurent81784c32012-11-19 14:55:58 -08001966 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1967 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1968 if (minBufCount < 2) {
1969 minBufCount = 2;
1970 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07001971 // For normal mixing tracks, if speed is > 1.0f (normal), AudioTrack
1972 // or the client should compute and pass in a larger buffer request.
Andy Hung0e48d252015-01-26 11:43:15 -08001973 size_t minFrameCount =
Andy Hung8edb8dc2015-03-26 19:13:55 -07001974 minBufCount * sourceFramesNeededWithTimestretch(
1975 sampleRate, mNormalFrameCount,
1976 mSampleRate, AUDIO_TIMESTRETCH_SPEED_NORMAL /*speed*/);
Andy Hung0e48d252015-01-26 11:43:15 -08001977 if (frameCount < minFrameCount) { // including frameCount == 0
Eric Laurent81784c32012-11-19 14:55:58 -08001978 frameCount = minFrameCount;
1979 }
Eric Laurent81784c32012-11-19 14:55:58 -08001980 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001981 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001982
Glenn Kastenc3df8382014-03-13 15:05:25 -07001983 switch (mType) {
1984
1985 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08001986 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08001987 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001988 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1989 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001990 sampleRate, format, channelMask, mOutput, mFormat);
1991 lStatus = BAD_VALUE;
1992 goto Exit;
1993 }
1994 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001995 break;
1996
1997 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001998 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001999 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2000 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002001 sampleRate, format, channelMask, mOutput, mFormat);
2002 lStatus = BAD_VALUE;
2003 goto Exit;
2004 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002005 break;
2006
2007 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002008 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002009 ALOGE("createTrack_l() Bad parameter: format %#x \""
2010 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002011 format, mOutput, mFormat);
2012 lStatus = BAD_VALUE;
2013 goto Exit;
2014 }
Andy Hungcd044842014-08-07 11:04:34 -07002015 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002016 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2017 lStatus = BAD_VALUE;
2018 goto Exit;
2019 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002020 break;
2021
Eric Laurent81784c32012-11-19 14:55:58 -08002022 }
2023
2024 lStatus = initCheck();
2025 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002026 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002027 goto Exit;
2028 }
2029
2030 { // scope for mLock
2031 Mutex::Autolock _l(mLock);
2032
2033 // all tracks in same audio session must share the same routing strategy otherwise
2034 // conflicts will happen when tracks are moved from one output to another by audio policy
2035 // manager
2036 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
2037 for (size_t i = 0; i < mTracks.size(); ++i) {
2038 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002039 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002040 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
2041 if (sessionId == t->sessionId() && strategy != actual) {
2042 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2043 strategy, actual);
2044 lStatus = BAD_VALUE;
2045 goto Exit;
2046 }
2047 }
2048 }
2049
Glenn Kastend79072e2016-01-06 08:41:20 -08002050 track = new Track(this, client, streamType, sampleRate, format,
2051 channelMask, frameCount, NULL, sharedBuffer,
2052 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT);
Glenn Kasten03003332013-08-06 15:40:54 -07002053
Glenn Kasten03003332013-08-06 15:40:54 -07002054 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2055 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002056 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002057 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002058 goto Exit;
2059 }
2060 mTracks.add(track);
2061
2062 sp<EffectChain> chain = getEffectChain_l(sessionId);
2063 if (chain != 0) {
2064 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2065 track->setMainBuffer(chain->inBuffer());
2066 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
2067 chain->incTrackCnt();
2068 }
2069
Eric Laurent05067782016-06-01 18:27:28 -07002070 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002071 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2072 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2073 // so ask activity manager to do this on our behalf
2074 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
2075 }
2076 }
2077
2078 lStatus = NO_ERROR;
2079
2080Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002081 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002082 return track;
2083}
2084
2085uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2086{
2087 return latency;
2088}
2089
2090uint32_t AudioFlinger::PlaybackThread::latency() const
2091{
2092 Mutex::Autolock _l(mLock);
2093 return latency_l();
2094}
2095uint32_t AudioFlinger::PlaybackThread::latency_l() const
2096{
2097 if (initCheck() == NO_ERROR) {
2098 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
2099 } else {
2100 return 0;
2101 }
2102}
2103
2104void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2105{
2106 Mutex::Autolock _l(mLock);
2107 // Don't apply master volume in SW if our HAL can do it for us.
2108 if (mOutput && mOutput->audioHwDev &&
2109 mOutput->audioHwDev->canSetMasterVolume()) {
2110 mMasterVolume = 1.0;
2111 } else {
2112 mMasterVolume = value;
2113 }
2114}
2115
2116void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2117{
2118 Mutex::Autolock _l(mLock);
2119 // Don't apply master mute in SW if our HAL can do it for us.
2120 if (mOutput && mOutput->audioHwDev &&
2121 mOutput->audioHwDev->canSetMasterMute()) {
2122 mMasterMute = false;
2123 } else {
2124 mMasterMute = muted;
2125 }
2126}
2127
2128void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2129{
2130 Mutex::Autolock _l(mLock);
2131 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002132 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002133}
2134
2135void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2136{
2137 Mutex::Autolock _l(mLock);
2138 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002139 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002140}
2141
2142float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2143{
2144 Mutex::Autolock _l(mLock);
2145 return mStreamTypes[stream].volume;
2146}
2147
2148// addTrack_l() must be called with ThreadBase::mLock held
2149status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2150{
2151 status_t status = ALREADY_EXISTS;
2152
Eric Laurent81784c32012-11-19 14:55:58 -08002153 if (mActiveTracks.indexOf(track) < 0) {
2154 // the track is newly added, make sure it fills up all its
2155 // buffers before playing. This is to ensure the client will
2156 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002157 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002158 TrackBase::track_state state = track->mState;
2159 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002160 status = AudioSystem::startOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002161 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002162 mLock.lock();
2163 // abort track was stopped/paused while we released the lock
2164 if (state != track->mState) {
2165 if (status == NO_ERROR) {
2166 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002167 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002168 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002169 mLock.lock();
2170 }
2171 return INVALID_OPERATION;
2172 }
2173 // abort if start is rejected by audio policy manager
2174 if (status != NO_ERROR) {
2175 return PERMISSION_DENIED;
2176 }
2177#ifdef ADD_BATTERY_DATA
2178 // to track the speaker usage
2179 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2180#endif
2181 }
2182
Eric Laurent51716182016-02-29 18:00:56 -08002183 // set retry count for buffer fill
2184 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002185 if (track->isStopping_1()) {
2186 track->mRetryCount = kMaxTrackStopRetriesOffload;
2187 } else {
2188 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2189 }
2190 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002191 } else {
2192 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002193 track->mFillingUpStatus =
2194 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002195 }
2196
Eric Laurent81784c32012-11-19 14:55:58 -08002197 track->mResetDone = false;
2198 track->mPresentationCompleteFrames = 0;
2199 mActiveTracks.add(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002200 mWakeLockUids.add(track->uid());
2201 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07002202 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07002203 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2204 if (chain != 0) {
2205 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2206 track->sessionId());
2207 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002208 }
2209
2210 status = NO_ERROR;
2211 }
2212
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002213 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002214 return status;
2215}
2216
Eric Laurentbfb1b832013-01-07 09:53:42 -08002217bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002218{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002219 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002220 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002221 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2222 track->mState = TrackBase::STOPPED;
2223 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002224 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002225 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002226 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002227 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002228
2229 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002230}
2231
2232void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2233{
2234 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
2235 mTracks.remove(track);
2236 deleteTrackName_l(track->name());
2237 // redundant as track is about to be destroyed, for dumpsys only
2238 track->mName = -1;
2239 if (track->isFastTrack()) {
2240 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002241 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002242 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2243 mFastTrackAvailMask |= 1 << index;
2244 // redundant as track is about to be destroyed, for dumpsys only
2245 track->mFastIndex = -1;
2246 }
2247 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2248 if (chain != 0) {
2249 chain->decTrackCnt();
2250 }
2251}
2252
Eric Laurentede6c3b2013-09-19 14:37:46 -07002253void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002254{
2255 // Thread could be blocked waiting for async
2256 // so signal it to handle state changes immediately
2257 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
2258 // be lost so we also flag to prevent it blocking on mWaitWorkCV
2259 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002260 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002261}
2262
Eric Laurent81784c32012-11-19 14:55:58 -08002263String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2264{
Eric Laurent81784c32012-11-19 14:55:58 -08002265 Mutex::Autolock _l(mLock);
2266 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07002267 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002268 }
2269
Glenn Kastend8ea6992013-07-16 14:17:15 -07002270 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
2271 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08002272 free(s);
2273 return out_s8;
2274}
2275
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002276void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002277 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2278 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002279
Eric Laurent73e26b62015-04-27 16:55:58 -07002280 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002281
2282 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002283 case AUDIO_OUTPUT_OPENED:
2284 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002285 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002286 desc->mChannelMask = mChannelMask;
2287 desc->mSamplingRate = mSampleRate;
2288 desc->mFormat = mFormat;
2289 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002290 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002291 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002292 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002293 break;
2294
Eric Laurent73e26b62015-04-27 16:55:58 -07002295 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002296 default:
2297 break;
2298 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002299 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002300}
2301
Eric Laurentbfb1b832013-01-07 09:53:42 -08002302void AudioFlinger::PlaybackThread::writeCallback()
2303{
2304 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002305 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002306}
2307
2308void AudioFlinger::PlaybackThread::drainCallback()
2309{
2310 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002311 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002312}
2313
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002314void AudioFlinger::PlaybackThread::errorCallback()
2315{
2316 ALOG_ASSERT(mCallbackThread != 0);
2317 mCallbackThread->setAsyncError();
2318}
2319
Eric Laurent3b4529e2013-09-05 18:09:19 -07002320void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002321{
2322 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002323 // reject out of sequence requests
2324 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2325 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002326 mWaitWorkCV.signal();
2327 }
2328}
2329
Eric Laurent3b4529e2013-09-05 18:09:19 -07002330void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002331{
2332 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002333 // reject out of sequence requests
2334 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
2335 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002336 mWaitWorkCV.signal();
2337 }
2338}
2339
2340// static
2341int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
Glenn Kasten0f11b512014-01-31 16:18:54 -08002342 void *param __unused,
Eric Laurentbfb1b832013-01-07 09:53:42 -08002343 void *cookie)
2344{
2345 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
2346 ALOGV("asyncCallback() event %d", event);
2347 switch (event) {
2348 case STREAM_CBK_EVENT_WRITE_READY:
2349 me->writeCallback();
2350 break;
2351 case STREAM_CBK_EVENT_DRAIN_READY:
2352 me->drainCallback();
2353 break;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002354 case STREAM_CBK_EVENT_ERROR:
2355 me->errorCallback();
2356 break;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002357 default:
2358 ALOGW("asyncCallback() unknown event %d", event);
2359 break;
2360 }
2361 return 0;
2362}
2363
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002364void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002365{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002366 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002367 mSampleRate = mOutput->getSampleRate();
2368 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002369 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002370 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002371 }
Andy Hung9a592762014-07-21 21:56:01 -07002372 if ((mType == MIXER || mType == DUPLICATING)
2373 && !isValidPcmSinkChannelMask(mChannelMask)) {
2374 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2375 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002376 }
Andy Hunge5412692014-05-16 11:25:07 -07002377 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002378
2379 // Get actual HAL format.
Andy Hung463be252014-07-10 16:56:07 -07002380 mHALFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Phil Burkca5e6142015-07-14 09:42:29 -07002381 // Get format from the shim, which will be different than the HAL format
2382 // if playing compressed audio over HDMI passthrough.
2383 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002384 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002385 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002386 }
Andy Hung6146c082014-03-18 11:56:15 -07002387 if ((mType == MIXER || mType == DUPLICATING)
2388 && !isValidPcmSinkFormat(mFormat)) {
2389 LOG_FATAL("HAL format %#x not supported for mixed output",
2390 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002391 }
Phil Burk062e67a2015-02-11 13:40:50 -08002392 mFrameSize = mOutput->getFrameSize();
Glenn Kasten70949c42013-08-06 07:40:12 -07002393 mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
2394 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002395 if (mFrameCount & 15) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002396 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002397 mFrameCount);
2398 }
2399
Eric Laurentbfb1b832013-01-07 09:53:42 -08002400 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
2401 (mOutput->stream->set_callback != NULL)) {
2402 if (mOutput->stream->set_callback(mOutput->stream,
2403 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
2404 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002405 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002406 }
2407 }
2408
Eric Laurentd1f69b02014-12-15 14:33:13 -08002409 mHwSupportsPause = false;
2410 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
2411 if (mOutput->stream->pause != NULL) {
2412 if (mOutput->stream->resume != NULL) {
2413 mHwSupportsPause = true;
2414 } else {
2415 ALOGW("direct output implements pause but not resume");
2416 }
2417 } else if (mOutput->stream->resume != NULL) {
2418 ALOGW("direct output implements resume but not pause");
2419 }
2420 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002421 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2422 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2423 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002424
Andy Hungfbfc3952015-01-15 13:33:51 -08002425 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2426 // For best precision, we use float instead of the associated output
2427 // device format (typically PCM 16 bit).
2428
2429 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2430 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2431 mBufferSize = mFrameSize * mFrameCount;
2432
2433 // TODO: We currently use the associated output device channel mask and sample rate.
2434 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2435 // (if a valid mask) to avoid premature downmix.
2436 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2437 // instead of the output device sample rate to avoid loss of high frequency information.
2438 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2439 }
2440
Andy Hung09a50072014-02-27 14:30:47 -08002441 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002442 double multiplier = 1.0;
2443 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2444 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002445 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2446 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002447
Eric Laurent81784c32012-11-19 14:55:58 -08002448 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2449 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2450 maxNormalFrameCount = maxNormalFrameCount & ~15;
2451 if (maxNormalFrameCount < minNormalFrameCount) {
2452 maxNormalFrameCount = minNormalFrameCount;
2453 }
2454 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2455 if (multiplier <= 1.0) {
2456 multiplier = 1.0;
2457 } else if (multiplier <= 2.0) {
2458 if (2 * mFrameCount <= maxNormalFrameCount) {
2459 multiplier = 2.0;
2460 } else {
2461 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2462 }
2463 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002464 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002465 }
2466 }
2467 mNormalFrameCount = multiplier * mFrameCount;
2468 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002469 if (mType == MIXER || mType == DUPLICATING) {
2470 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2471 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002472 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002473 mNormalFrameCount);
2474
Andy Hung08fb1742015-05-31 23:22:10 -07002475 // Check if we want to throttle the processing to no more than 2x normal rate
2476 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002477 mThreadThrottleTimeMs = 0;
2478 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002479 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2480
Andy Hung010a1a12014-03-13 13:57:33 -07002481 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2482 // Originally this was int16_t[] array, need to remove legacy implications.
2483 free(mSinkBuffer);
2484 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002485 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2486 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2487 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002488 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002489
Andy Hung69aed5f2014-02-25 17:24:40 -08002490 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2491 // drives the output.
2492 free(mMixerBuffer);
2493 mMixerBuffer = NULL;
2494 if (mMixerBufferEnabled) {
2495 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2496 mMixerBufferSize = mNormalFrameCount * mChannelCount
2497 * audio_bytes_per_sample(mMixerBufferFormat);
2498 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2499 }
Andy Hung98ef9782014-03-04 14:46:50 -08002500 free(mEffectBuffer);
2501 mEffectBuffer = NULL;
2502 if (mEffectBufferEnabled) {
2503 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2504 mEffectBufferSize = mNormalFrameCount * mChannelCount
2505 * audio_bytes_per_sample(mEffectBufferFormat);
2506 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2507 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002508
Eric Laurent81784c32012-11-19 14:55:58 -08002509 // force reconfiguration of effect chains and engines to take new buffer size and audio
2510 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002511 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002512 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2513 // matter.
2514 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2515 Vector< sp<EffectChain> > effectChains = mEffectChains;
2516 for (size_t i = 0; i < effectChains.size(); i ++) {
2517 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2518 }
2519}
2520
2521
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002522status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002523{
2524 if (halFrames == NULL || dspFrames == NULL) {
2525 return BAD_VALUE;
2526 }
2527 Mutex::Autolock _l(mLock);
2528 if (initCheck() != NO_ERROR) {
2529 return INVALID_OPERATION;
2530 }
Andy Hung818e7a32016-02-16 18:08:07 -08002531 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002532 *halFrames = framesWritten;
2533
2534 if (isSuspended()) {
2535 // return an estimation of rendered frames when the output is suspended
2536 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002537 *dspFrames = (uint32_t)
2538 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002539 return NO_ERROR;
2540 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002541 status_t status;
2542 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002543 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002544 *dspFrames = (size_t)frames;
2545 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002546 }
2547}
2548
Eric Laurent4c415062016-06-17 16:14:16 -07002549// hasAudioSession_l() must be called with ThreadBase::mLock held
2550uint32_t AudioFlinger::PlaybackThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08002551{
Eric Laurent81784c32012-11-19 14:55:58 -08002552 uint32_t result = 0;
2553 if (getEffectChain_l(sessionId) != 0) {
2554 result = EFFECT_SESSION;
2555 }
2556
2557 for (size_t i = 0; i < mTracks.size(); ++i) {
2558 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002559 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002560 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07002561 if (track->isFastTrack()) {
2562 result |= FAST_SESSION;
2563 }
Eric Laurent81784c32012-11-19 14:55:58 -08002564 break;
2565 }
2566 }
2567
2568 return result;
2569}
2570
Glenn Kastend848eb42016-03-08 13:42:11 -08002571uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08002572{
2573 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2574 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2575 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2576 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2577 }
2578 for (size_t i = 0; i < mTracks.size(); i++) {
2579 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002580 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002581 return AudioSystem::getStrategyForStream(track->streamType());
2582 }
2583 }
2584 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2585}
2586
2587
Phil Burk062e67a2015-02-11 13:40:50 -08002588AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002589{
2590 Mutex::Autolock _l(mLock);
2591 return mOutput;
2592}
2593
Phil Burk062e67a2015-02-11 13:40:50 -08002594AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002595{
2596 Mutex::Autolock _l(mLock);
2597 AudioStreamOut *output = mOutput;
2598 mOutput = NULL;
2599 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2600 // must push a NULL and wait for ack
2601 mOutputSink.clear();
2602 mPipeSink.clear();
2603 mNormalSink.clear();
2604 return output;
2605}
2606
2607// this method must always be called either with ThreadBase mLock held or inside the thread loop
2608audio_stream_t* AudioFlinger::PlaybackThread::stream() const
2609{
2610 if (mOutput == NULL) {
2611 return NULL;
2612 }
2613 return &mOutput->stream->common;
2614}
2615
2616uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2617{
2618 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2619}
2620
2621status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2622{
2623 if (!isValidSyncEvent(event)) {
2624 return BAD_VALUE;
2625 }
2626
2627 Mutex::Autolock _l(mLock);
2628
2629 for (size_t i = 0; i < mTracks.size(); ++i) {
2630 sp<Track> track = mTracks[i];
2631 if (event->triggerSession() == track->sessionId()) {
2632 (void) track->setSyncEvent(event);
2633 return NO_ERROR;
2634 }
2635 }
2636
2637 return NAME_NOT_FOUND;
2638}
2639
2640bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2641{
2642 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2643}
2644
2645void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2646 const Vector< sp<Track> >& tracksToRemove)
2647{
2648 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002649 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002650 for (size_t i = 0 ; i < count ; i++) {
2651 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002652 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002653 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002654 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002655#ifdef ADD_BATTERY_DATA
2656 // to track the speaker usage
2657 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2658#endif
2659 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002660 AudioSystem::releaseOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002661 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002662 }
Eric Laurent81784c32012-11-19 14:55:58 -08002663 }
2664 }
2665 }
Eric Laurent81784c32012-11-19 14:55:58 -08002666}
2667
2668void AudioFlinger::PlaybackThread::checkSilentMode_l()
2669{
2670 if (!mMasterMute) {
2671 char value[PROPERTY_VALUE_MAX];
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07002672 if (mOutDevice == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) {
2673 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
2674 return;
2675 }
Eric Laurent81784c32012-11-19 14:55:58 -08002676 if (property_get("ro.audio.silent", value, "0") > 0) {
2677 char *endptr;
2678 unsigned long ul = strtoul(value, &endptr, 0);
2679 if (*endptr == '\0' && ul != 0) {
2680 ALOGD("Silence is golden");
2681 // The setprop command will not allow a property to be changed after
2682 // the first time it is set, so we don't have to worry about un-muting.
2683 setMasterMute_l(true);
2684 }
2685 }
2686 }
2687}
2688
2689// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002690ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002691{
Eric Laurent81784c32012-11-19 14:55:58 -08002692 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002693 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002694 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002695
2696 // If an NBAIO sink is present, use it to write the normal mixer's submix
2697 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002698
Andy Hung010a1a12014-03-13 13:57:33 -07002699 const size_t count = mBytesRemaining / mFrameSize;
2700
Simon Wilson2d590962012-11-29 15:18:50 -08002701 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002702 // update the setpoint when AudioFlinger::mScreenState changes
2703 uint32_t screenState = AudioFlinger::mScreenState;
2704 if (screenState != mScreenState) {
2705 mScreenState = screenState;
2706 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2707 if (pipe != NULL) {
2708 pipe->setAvgFrames((mScreenState & 1) ?
2709 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2710 }
2711 }
Andy Hung010a1a12014-03-13 13:57:33 -07002712 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002713 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002714 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002715 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002716 } else {
2717 bytesWritten = framesWritten;
2718 }
2719 // otherwise use the HAL / AudioStreamOut directly
2720 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002721 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002722
Eric Laurentbfb1b832013-01-07 09:53:42 -08002723 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002724 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2725 mWriteAckSequence += 2;
2726 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002727 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002728 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002729 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002730 // FIXME We should have an implementation of timestamps for direct output threads.
2731 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002732 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurent51716182016-02-29 18:00:56 -08002733
Eric Laurentbfb1b832013-01-07 09:53:42 -08002734 if (mUseAsyncWrite &&
2735 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2736 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002737 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002738 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002739 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002740 }
Eric Laurent81784c32012-11-19 14:55:58 -08002741 }
2742
Eric Laurent81784c32012-11-19 14:55:58 -08002743 mNumWrites++;
2744 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002745 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002746 return bytesWritten;
2747}
2748
2749void AudioFlinger::PlaybackThread::threadLoop_drain()
2750{
2751 if (mOutput->stream->drain) {
2752 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2753 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002754 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2755 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002756 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002757 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002758 }
2759 mOutput->stream->drain(mOutput->stream,
2760 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2761 : AUDIO_DRAIN_ALL);
2762 }
2763}
2764
2765void AudioFlinger::PlaybackThread::threadLoop_exit()
2766{
Eric Laurent275e8e92014-11-30 15:14:47 -08002767 {
2768 Mutex::Autolock _l(mLock);
2769 for (size_t i = 0; i < mTracks.size(); i++) {
2770 sp<Track> track = mTracks[i];
2771 track->invalidate();
2772 }
2773 }
Eric Laurent81784c32012-11-19 14:55:58 -08002774}
2775
2776/*
2777The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002778 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002779 - mActiveSleepTimeUs from activeSleepTimeUs()
2780 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08002781 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
2782 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08002783 - maxPeriod from frame count and sample rate (MIXER only)
2784
2785The parameters that affect these derived values are:
2786 - frame count
2787 - frame size
2788 - sample rate
2789 - device type: A2DP or not
2790 - device latency
2791 - format: PCM or not
2792 - active sleep time
2793 - idle sleep time
2794*/
2795
2796void AudioFlinger::PlaybackThread::cacheParameters_l()
2797{
Andy Hung25c2dac2014-02-27 14:56:00 -08002798 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002799 mActiveSleepTimeUs = activeSleepTimeUs();
2800 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08002801
2802 // make sure standby delay is not too short when connected to an A2DP sink to avoid
2803 // truncating audio when going to standby.
2804 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
2805 if ((mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != 0) {
2806 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
2807 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
2808 }
2809 }
Eric Laurent81784c32012-11-19 14:55:58 -08002810}
2811
Eric Laurent13084622016-05-17 10:51:49 -07002812bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08002813{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002814 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08002815 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07002816 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002817 size_t size = mTracks.size();
2818 for (size_t i = 0; i < size; i++) {
2819 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07002820 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002821 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07002822 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002823 }
2824 }
Eric Laurent13084622016-05-17 10:51:49 -07002825 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08002826}
2827
Haynes Mathew George05317d22016-05-03 16:34:26 -07002828void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2829{
2830 Mutex::Autolock _l(mLock);
2831 invalidateTracks_l(streamType);
2832}
2833
Eric Laurent81784c32012-11-19 14:55:58 -08002834status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2835{
Glenn Kastend848eb42016-03-08 13:42:11 -08002836 audio_session_t session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002837 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2838 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002839 bool ownsBuffer = false;
2840
2841 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Glenn Kastend848eb42016-03-08 13:42:11 -08002842 if (session > AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002843 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002844 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002845 if (mType != DIRECT) {
2846 size_t numSamples = mNormalFrameCount * mChannelCount;
2847 buffer = new int16_t[numSamples];
2848 memset(buffer, 0, numSamples * sizeof(int16_t));
2849 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2850 ownsBuffer = true;
2851 }
2852
2853 // Attach all tracks with same session ID to this chain.
2854 for (size_t i = 0; i < mTracks.size(); ++i) {
2855 sp<Track> track = mTracks[i];
2856 if (session == track->sessionId()) {
2857 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2858 buffer);
2859 track->setMainBuffer(buffer);
2860 chain->incTrackCnt();
2861 }
2862 }
2863
2864 // indicate all active tracks in the chain
2865 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2866 sp<Track> track = mActiveTracks[i].promote();
2867 if (track == 0) {
2868 continue;
2869 }
2870 if (session == track->sessionId()) {
2871 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2872 chain->incActiveTrackCnt();
2873 }
2874 }
2875 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002876 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08002877 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002878 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2879 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002880 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Glenn Kastend848eb42016-03-08 13:42:11 -08002881 // chains list in order to be processed last as it contains output stage effects.
Eric Laurent81784c32012-11-19 14:55:58 -08002882 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2883 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08002884 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08002885 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08002886 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08002887 // Effect chain for other sessions are inserted at beginning of effect
2888 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08002889 // sessions is not important.
2890 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
2891 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX,
2892 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08002893 size_t size = mEffectChains.size();
2894 size_t i = 0;
2895 for (i = 0; i < size; i++) {
2896 if (mEffectChains[i]->sessionId() < session) {
2897 break;
2898 }
2899 }
2900 mEffectChains.insertAt(chain, i);
2901 checkSuspendOnAddEffectChain_l(chain);
2902
2903 return NO_ERROR;
2904}
2905
2906size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2907{
Glenn Kastend848eb42016-03-08 13:42:11 -08002908 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08002909
2910 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2911
2912 for (size_t i = 0; i < mEffectChains.size(); i++) {
2913 if (chain == mEffectChains[i]) {
2914 mEffectChains.removeAt(i);
2915 // detach all active tracks from the chain
2916 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2917 sp<Track> track = mActiveTracks[i].promote();
2918 if (track == 0) {
2919 continue;
2920 }
2921 if (session == track->sessionId()) {
2922 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2923 chain.get(), session);
2924 chain->decActiveTrackCnt();
2925 }
2926 }
2927
2928 // detach all tracks with same session ID from this chain
2929 for (size_t i = 0; i < mTracks.size(); ++i) {
2930 sp<Track> track = mTracks[i];
2931 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002932 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002933 chain->decTrackCnt();
2934 }
2935 }
2936 break;
2937 }
2938 }
2939 return mEffectChains.size();
2940}
2941
2942status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2943 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2944{
2945 Mutex::Autolock _l(mLock);
2946 return attachAuxEffect_l(track, EffectId);
2947}
2948
2949status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2950 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2951{
2952 status_t status = NO_ERROR;
2953
2954 if (EffectId == 0) {
2955 track->setAuxBuffer(0, NULL);
2956 } else {
2957 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2958 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2959 if (effect != 0) {
2960 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2961 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2962 } else {
2963 status = INVALID_OPERATION;
2964 }
2965 } else {
2966 status = BAD_VALUE;
2967 }
2968 }
2969 return status;
2970}
2971
2972void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2973{
2974 for (size_t i = 0; i < mTracks.size(); ++i) {
2975 sp<Track> track = mTracks[i];
2976 if (track->auxEffectId() == effectId) {
2977 attachAuxEffect_l(track, 0);
2978 }
2979 }
2980}
2981
2982bool AudioFlinger::PlaybackThread::threadLoop()
2983{
2984 Vector< sp<Track> > tracksToRemove;
2985
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002986 mStandbyTimeNs = systemTime();
Andy Hung69488c42016-05-16 18:43:33 -07002987 nsecs_t lastWriteFinished = -1; // time last server write completed
2988 int64_t lastFramesWritten = -1; // track changes in timestamp server frames written
Eric Laurent81784c32012-11-19 14:55:58 -08002989
2990 // MIXER
2991 nsecs_t lastWarning = 0;
2992
2993 // DUPLICATING
2994 // FIXME could this be made local to while loop?
2995 writeFrames = 0;
2996
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002997 int lastGeneration = 0;
2998
Eric Laurent81784c32012-11-19 14:55:58 -08002999 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003000 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003001
3002 if (mType == MIXER) {
3003 sleepTimeShift = 0;
3004 }
3005
3006 CpuStats cpuStats;
3007 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3008
3009 acquireWakeLock();
3010
Glenn Kasten9e58b552013-01-18 15:09:48 -08003011 // mNBLogWriter->log can only be called while thread mutex mLock is held.
3012 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3013 // and then that string will be logged at the next convenient opportunity.
3014 const char *logString = NULL;
3015
Eric Laurent664539d2013-09-23 18:24:31 -07003016 checkSilentMode_l();
3017
Eric Laurent81784c32012-11-19 14:55:58 -08003018 while (!exitPending())
3019 {
3020 cpuStats.sample(myName);
3021
3022 Vector< sp<EffectChain> > effectChains;
3023
Eric Laurent81784c32012-11-19 14:55:58 -08003024 { // scope for mLock
3025
3026 Mutex::Autolock _l(mLock);
3027
Eric Laurent021cf962014-05-13 10:18:14 -07003028 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07003029
Glenn Kasten9e58b552013-01-18 15:09:48 -08003030 if (logString != NULL) {
3031 mNBLogWriter->logTimestamp();
3032 mNBLogWriter->log(logString);
3033 logString = NULL;
3034 }
3035
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003036 // Gather the framesReleased counters for all active tracks,
Andy Hunge10393e2015-06-12 13:59:33 -07003037 // and associate with the sink frames written out. We need
3038 // this to convert the sink timestamp to the track timestamp.
Andy Hung69488c42016-05-16 18:43:33 -07003039 bool kernelLocationUpdate = false;
Andy Hunge10393e2015-06-12 13:59:33 -07003040 if (mNormalSink != 0) {
Andy Hungc54b1ff2016-02-23 14:07:07 -08003041 // Note: The DuplicatingThread may not have a mNormalSink.
Andy Hung818e7a32016-02-16 18:08:07 -08003042 // We always fetch the timestamp here because often the downstream
Andy Hung69488c42016-05-16 18:43:33 -07003043 // sink will block while writing.
Andy Hung818e7a32016-02-16 18:08:07 -08003044 ExtendedTimestamp timestamp; // use private copy to fetch
3045 (void) mNormalSink->getTimestamp(timestamp);
Andy Hung6d7b1192016-05-07 22:59:48 -07003046
3047 // We keep track of the last valid kernel position in case we are in underrun
3048 // and the normal mixer period is the same as the fast mixer period, or there
3049 // is some error from the HAL.
3050 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3051 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3052 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
3053 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3054 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
3055
3056 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3057 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
3058 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3059 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
Andy Hung69488c42016-05-16 18:43:33 -07003060 }
3061
3062 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3063 kernelLocationUpdate = true;
Andy Hung6d7b1192016-05-07 22:59:48 -07003064 } else {
Eric Laurent122f7e72016-06-29 11:53:29 -07003065 ALOGVV("getTimestamp error - no valid kernel position");
Andy Hung6d7b1192016-05-07 22:59:48 -07003066 }
3067
Andy Hung818e7a32016-02-16 18:08:07 -08003068 // copy over kernel info
3069 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
Andy Hung238fa3d2016-07-28 10:53:22 -07003070 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3071 + mSuspendedFrames; // add frames discarded when suspended
Andy Hung818e7a32016-02-16 18:08:07 -08003072 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
3073 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hungc54b1ff2016-02-23 14:07:07 -08003074 }
3075 // mFramesWritten for non-offloaded tracks are contiguous
3076 // even after standby() is called. This is useful for the track frame
3077 // to sink frame mapping.
Andy Hung69488c42016-05-16 18:43:33 -07003078 bool serverLocationUpdate = false;
3079 if (mFramesWritten != lastFramesWritten) {
3080 serverLocationUpdate = true;
3081 lastFramesWritten = mFramesWritten;
3082 }
3083 // Only update timestamps if there is a meaningful change.
3084 // Either the kernel timestamp must be valid or we have written something.
3085 if (kernelLocationUpdate || serverLocationUpdate) {
3086 if (serverLocationUpdate) {
3087 // use the time before we called the HAL write - it is a bit more accurate
3088 // to when the server last read data than the current time here.
3089 //
3090 // If we haven't written anything, mLastWriteTime will be -1
3091 // and we use systemTime().
3092 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
3093 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastWriteTime == -1
3094 ? systemTime() : mLastWriteTime;
3095 }
3096 const size_t size = mActiveTracks.size();
3097 for (size_t i = 0; i < size; ++i) {
3098 sp<Track> t = mActiveTracks[i].promote();
3099 if (t != 0 && !t->isFastTrack()) {
3100 t->updateTrackFrameInfo(
3101 t->mAudioTrackServerProxy->framesReleased(),
3102 mFramesWritten,
3103 mTimestamp);
3104 }
Andy Hunge10393e2015-06-12 13:59:33 -07003105 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07003106 }
3107
Eric Laurent81784c32012-11-19 14:55:58 -08003108 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003109 if (mSignalPending) {
3110 // A signal was raised while we were unlocked
3111 mSignalPending = false;
3112 } else if (waitingAsyncCallback_l()) {
3113 if (exitPending()) {
3114 break;
3115 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003116 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003117 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003118 releaseWakeLock_l();
3119 released = true;
Mikhail Naganove94c27a2016-08-18 17:31:46 -07003120 mWakeLockUids.clear();
3121 mActiveTracksGeneration++;
Marco Nelissen078538c2015-05-12 09:17:57 -07003122 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003123 ALOGV("wait async completion");
3124 mWaitWorkCV.wait(mLock);
3125 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003126 if (released) {
3127 acquireWakeLock_l();
3128 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003129 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3130 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003131
3132 continue;
3133 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003134 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003135 isSuspended()) {
3136 // put audio hardware into standby after short delay
3137 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003138
3139 threadLoop_standby();
3140
3141 mStandby = true;
3142 }
3143
3144 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
3145 // we're about to wait, flush the binder command buffer
3146 IPCThreadState::self()->flushCommands();
3147
3148 clearOutputTracks();
3149
3150 if (exitPending()) {
3151 break;
3152 }
3153
3154 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003155 mWakeLockUids.clear();
3156 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08003157 // wait until we have something to do...
3158 ALOGV("%s going to sleep", myName.string());
3159 mWaitWorkCV.wait(mLock);
3160 ALOGV("%s waking up", myName.string());
3161 acquireWakeLock_l();
3162
3163 mMixerStatus = MIXER_IDLE;
3164 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3165 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003166 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003167 checkSilentMode_l();
3168
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003169 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3170 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003171 if (mType == MIXER) {
3172 sleepTimeShift = 0;
3173 }
3174
3175 continue;
3176 }
3177 }
Eric Laurent81784c32012-11-19 14:55:58 -08003178 // mMixerStatusIgnoringFastTracks is also updated internally
3179 mMixerStatus = prepareTracks_l(&tracksToRemove);
3180
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003181 // compare with previously applied list
3182 if (lastGeneration != mActiveTracksGeneration) {
3183 // update wakelock
3184 updateWakeLockUids_l(mWakeLockUids);
3185 lastGeneration = mActiveTracksGeneration;
3186 }
3187
Eric Laurent81784c32012-11-19 14:55:58 -08003188 // prevent any changes in effect chain list and in each effect chain
3189 // during mixing and effect process as the audio buffers could be deleted
3190 // or modified if an effect is created or deleted
3191 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003192 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003193
Eric Laurentbfb1b832013-01-07 09:53:42 -08003194 if (mBytesRemaining == 0) {
3195 mCurrentWriteLength = 0;
3196 if (mMixerStatus == MIXER_TRACKS_READY) {
3197 // threadLoop_mix() sets mCurrentWriteLength
3198 threadLoop_mix();
3199 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3200 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003201 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003202 // must be written to HAL
3203 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003204 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003205 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003206 }
3207 }
Andy Hung98ef9782014-03-04 14:46:50 -08003208 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003209 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003210 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3211 // or mSinkBuffer (if there are no effects).
3212 //
3213 // This is done pre-effects computation; if effects change to
3214 // support higher precision, this needs to move.
3215 //
3216 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003217 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003218 if (mMixerBufferValid) {
3219 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3220 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3221
Andy Hung2ddee192015-12-18 17:34:44 -08003222 // mono blend occurs for mixer threads only (not direct or offloaded)
3223 // and is handled here if we're going directly to the sink.
3224 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003225 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3226 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003227 }
3228
Andy Hung98ef9782014-03-04 14:46:50 -08003229 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
3230 mNormalFrameCount * mChannelCount);
3231 }
3232
Eric Laurentbfb1b832013-01-07 09:53:42 -08003233 mBytesRemaining = mCurrentWriteLength;
3234 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003235 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3236 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3237 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3238 mBytesWritten += mBytesRemaining;
3239 mFramesWritten += framesRemaining;
3240 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003241 mBytesRemaining = 0;
3242 }
Eric Laurent81784c32012-11-19 14:55:58 -08003243
Eric Laurentbfb1b832013-01-07 09:53:42 -08003244 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003245 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003246 for (size_t i = 0; i < effectChains.size(); i ++) {
3247 effectChains[i]->process_l();
3248 }
Eric Laurent81784c32012-11-19 14:55:58 -08003249 }
3250 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003251 // Process effect chains for offloaded thread even if no audio
3252 // was read from audio track: process only updates effect state
3253 // and thus does have to be synchronized with audio writes but may have
3254 // to be called while waiting for async write callback
3255 if (mType == OFFLOAD) {
3256 for (size_t i = 0; i < effectChains.size(); i ++) {
3257 effectChains[i]->process_l();
3258 }
3259 }
Eric Laurent81784c32012-11-19 14:55:58 -08003260
Andy Hung98ef9782014-03-04 14:46:50 -08003261 // Only if the Effects buffer is enabled and there is data in the
3262 // Effects buffer (buffer valid), we need to
3263 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003264 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003265 if (mEffectBufferValid) {
3266 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003267
3268 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003269 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3270 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003271 }
3272
Andy Hung98ef9782014-03-04 14:46:50 -08003273 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
3274 mNormalFrameCount * mChannelCount);
3275 }
3276
Eric Laurent81784c32012-11-19 14:55:58 -08003277 // enable changes in effect chain
3278 unlockEffectChains(effectChains);
3279
Eric Laurentbfb1b832013-01-07 09:53:42 -08003280 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003281 // mSleepTimeUs == 0 means we must write to audio hardware
3282 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003283 ssize_t ret = 0;
Andy Hung69488c42016-05-16 18:43:33 -07003284 // We save lastWriteFinished here, as previousLastWriteFinished,
3285 // for throttling. On thread start, previousLastWriteFinished will be
3286 // set to -1, which properly results in no throttling after the first write.
3287 nsecs_t previousLastWriteFinished = lastWriteFinished;
3288 nsecs_t delta = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003289 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003290 // FIXME rewrite to reduce number of system calls
3291 mLastWriteTime = systemTime(); // also used for dumpsys
Andy Hung08fb1742015-05-31 23:22:10 -07003292 ret = threadLoop_write();
Andy Hung69488c42016-05-16 18:43:33 -07003293 lastWriteFinished = systemTime();
3294 delta = lastWriteFinished - mLastWriteTime;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003295 if (ret < 0) {
3296 mBytesRemaining = 0;
3297 } else {
3298 mBytesWritten += ret;
3299 mBytesRemaining -= ret;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003300 mFramesWritten += ret / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003301 }
3302 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3303 (mMixerStatus == MIXER_DRAIN_ALL)) {
3304 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003305 }
Andy Hung08fb1742015-05-31 23:22:10 -07003306 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003307 // write blocked detection
Andy Hung08fb1742015-05-31 23:22:10 -07003308 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003309 mNumDelayedWrites++;
Andy Hung69488c42016-05-16 18:43:33 -07003310 if ((lastWriteFinished - lastWarning) > kWarningThrottleNs) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003311 ATRACE_NAME("underrun");
3312 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003313 (unsigned long long) ns2ms(delta), mNumDelayedWrites, this);
Andy Hung69488c42016-05-16 18:43:33 -07003314 lastWarning = lastWriteFinished;
Glenn Kasten4944acb2013-08-19 08:39:20 -07003315 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003316 }
Andy Hung08fb1742015-05-31 23:22:10 -07003317
3318 if (mThreadThrottle
3319 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
3320 && ret > 0) { // we wrote something
3321 // Limit MixerThread data processing to no more than twice the
3322 // expected processing rate.
3323 //
3324 // This helps prevent underruns with NuPlayer and other applications
3325 // which may set up buffers that are close to the minimum size, or use
3326 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3327 //
3328 // The throttle smooths out sudden large data drains from the device,
3329 // e.g. when it comes out of standby, which often causes problems with
3330 // (1) mixer threads without a fast mixer (which has its own warm-up)
3331 // (2) minimum buffer sized tracks (even if the track is full,
3332 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07003333 //
3334 // Total time spent in last processing cycle equals time spent in
3335 // 1. threadLoop_write, as well as time spent in
3336 // 2. threadLoop_mix (significant for heavy mixing, especially
3337 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07003338
Andy Hung69488c42016-05-16 18:43:33 -07003339 // it's OK if deltaMs is an overestimate.
3340 const int32_t deltaMs =
3341 (lastWriteFinished - previousLastWriteFinished) / 1000000;
Andy Hung08fb1742015-05-31 23:22:10 -07003342 const int32_t throttleMs = mHalfBufferMs - deltaMs;
3343 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3344 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003345 // notify of throttle start on verbose log
3346 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3347 "mixer(%p) throttle begin:"
3348 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003349 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003350 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07003351 // Throttle must be attributed to the previous mixer loop's write time
3352 // to allow back-to-back throttling.
3353 lastWriteFinished += throttleMs * 1000000;
Andy Hung40eb1a12015-06-18 13:42:02 -07003354 } else {
3355 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3356 if (diff > 0) {
3357 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07003358 // but prevent spamming for bluetooth
3359 ALOGD_IF(!audio_is_a2dp_out_device(outDevice()),
3360 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07003361 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3362 }
Andy Hung08fb1742015-05-31 23:22:10 -07003363 }
3364 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003365 }
Eric Laurent81784c32012-11-19 14:55:58 -08003366
Eric Laurentbfb1b832013-01-07 09:53:42 -08003367 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003368 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07003369 Mutex::Autolock _l(mLock);
3370 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
3371 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08003372 }
Glenn Kastene7754022014-10-31 12:11:26 -07003373 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003374 }
Eric Laurent81784c32012-11-19 14:55:58 -08003375 }
3376
3377 // Finally let go of removed track(s), without the lock held
3378 // since we can't guarantee the destructors won't acquire that
3379 // same lock. This will also mutate and push a new fast mixer state.
3380 threadLoop_removeTracks(tracksToRemove);
3381 tracksToRemove.clear();
3382
3383 // FIXME I don't understand the need for this here;
3384 // it was in the original code but maybe the
3385 // assignment in saveOutputTracks() makes this unnecessary?
3386 clearOutputTracks();
3387
3388 // Effect chains will be actually deleted here if they were removed from
3389 // mEffectChains list during mixing or effects processing
3390 effectChains.clear();
3391
3392 // FIXME Note that the above .clear() is no longer necessary since effectChains
3393 // is now local to this block, but will keep it for now (at least until merge done).
3394 }
3395
Eric Laurentbfb1b832013-01-07 09:53:42 -08003396 threadLoop_exit();
3397
Eric Laurentcf817a22014-08-04 20:36:31 -07003398 if (!mStandby) {
3399 threadLoop_standby();
3400 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003401 }
3402
3403 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003404 mWakeLockUids.clear();
3405 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08003406
3407 ALOGV("Thread %p type %d exiting", this, mType);
3408 return false;
3409}
3410
Eric Laurentbfb1b832013-01-07 09:53:42 -08003411// removeTracks_l() must be called with ThreadBase::mLock held
3412void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3413{
3414 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003415 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003416 for (size_t i=0 ; i<count ; i++) {
3417 const sp<Track>& track = tracksToRemove.itemAt(i);
3418 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003419 mWakeLockUids.remove(track->uid());
3420 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003421 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3422 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3423 if (chain != 0) {
3424 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3425 track->sessionId());
3426 chain->decActiveTrackCnt();
3427 }
3428 if (track->isTerminated()) {
3429 removeTrack_l(track);
3430 }
3431 }
3432 }
3433
3434}
Eric Laurent81784c32012-11-19 14:55:58 -08003435
Eric Laurentaccc1472013-09-20 09:36:34 -07003436status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3437{
3438 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08003439 ExtendedTimestamp ets;
3440 status_t status = mNormalSink->getTimestamp(ets);
3441 if (status == NO_ERROR) {
3442 status = ets.getBestTimestamp(&timestamp);
3443 }
3444 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07003445 }
Andy Hung9a1c8892014-12-03 11:37:42 -08003446 if ((mType == OFFLOAD || mType == DIRECT)
3447 && mOutput != NULL && mOutput->stream->get_presentation_position) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003448 uint64_t position64;
Phil Burk062e67a2015-02-11 13:40:50 -08003449 int ret = mOutput->getPresentationPosition(&position64, &timestamp.mTime);
Eric Laurentaccc1472013-09-20 09:36:34 -07003450 if (ret == 0) {
3451 timestamp.mPosition = (uint32_t)position64;
3452 return NO_ERROR;
3453 }
3454 }
3455 return INVALID_OPERATION;
3456}
Eric Laurent1c333e22014-05-20 10:48:17 -07003457
Eric Laurent054d9d32015-04-24 08:48:48 -07003458status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3459 audio_patch_handle_t *handle)
3460{
Andy Hungf60abce2016-08-26 11:37:54 -07003461 status_t status;
3462 if (property_get_bool("af.patch_park", false /* default_value */)) {
3463 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3464 // or if HAL does not properly lock against access.
3465 AutoPark<FastMixer> park(mFastMixer);
3466 status = PlaybackThread::createAudioPatch_l(patch, handle);
3467 } else {
3468 status = PlaybackThread::createAudioPatch_l(patch, handle);
3469 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003470 return status;
3471}
3472
Eric Laurent1c333e22014-05-20 10:48:17 -07003473status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3474 audio_patch_handle_t *handle)
3475{
3476 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003477
3478 // store new device and send to effects
3479 audio_devices_t type = AUDIO_DEVICE_NONE;
3480 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3481 type |= patch->sinks[i].ext.device.type;
3482 }
3483
3484#ifdef ADD_BATTERY_DATA
3485 // when changing the audio output device, call addBatteryData to notify
3486 // the change
3487 if (mOutDevice != type) {
3488 uint32_t params = 0;
3489 // check whether speaker is on
3490 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3491 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003492 }
3493
Eric Laurent054d9d32015-04-24 08:48:48 -07003494 audio_devices_t deviceWithoutSpeaker
3495 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3496 // check if any other device (except speaker) is on
3497 if (type & deviceWithoutSpeaker) {
3498 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3499 }
3500
3501 if (params != 0) {
3502 addBatteryData(params);
3503 }
3504 }
3505#endif
3506
3507 for (size_t i = 0; i < mEffectChains.size(); i++) {
3508 mEffectChains[i]->setDevice_l(type);
3509 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003510
3511 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3512 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3513 bool configChanged = mPrevOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003514 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003515 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003516
3517 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003518 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3519 status = hwDevice->create_audio_patch(hwDevice,
3520 patch->num_sources,
3521 patch->sources,
3522 patch->num_sinks,
3523 patch->sinks,
3524 handle);
3525 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003526 char *address;
3527 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3528 //FIXME: we only support address on first sink with HAL version < 3.0
3529 address = audio_device_address_to_parameter(
3530 patch->sinks[0].ext.device.type,
3531 patch->sinks[0].ext.device.address);
3532 } else {
3533 address = (char *)calloc(1, 1);
3534 }
3535 AudioParameter param = AudioParameter(String8(address));
3536 free(address);
3537 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), (int)type);
3538 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3539 param.toString().string());
3540 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003541 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003542 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003543 mPrevOutDevice = type;
Eric Laurente8726fe2015-06-26 09:39:24 -07003544 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3545 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003546 return status;
3547}
3548
Eric Laurent054d9d32015-04-24 08:48:48 -07003549status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3550{
Andy Hungf60abce2016-08-26 11:37:54 -07003551 status_t status;
3552 if (property_get_bool("af.patch_park", false /* default_value */)) {
3553 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3554 // or if HAL does not properly lock against access.
3555 AutoPark<FastMixer> park(mFastMixer);
3556 status = PlaybackThread::releaseAudioPatch_l(handle);
3557 } else {
3558 status = PlaybackThread::releaseAudioPatch_l(handle);
3559 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003560 return status;
3561}
3562
Eric Laurent1c333e22014-05-20 10:48:17 -07003563status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3564{
3565 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003566
3567 mOutDevice = AUDIO_DEVICE_NONE;
3568
Eric Laurent1c333e22014-05-20 10:48:17 -07003569 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
3570 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3571 status = hwDevice->release_audio_patch(hwDevice, handle);
3572 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003573 AudioParameter param;
3574 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
3575 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3576 param.toString().string());
Eric Laurent1c333e22014-05-20 10:48:17 -07003577 }
3578 return status;
3579}
3580
Eric Laurent83b88082014-06-20 18:31:16 -07003581void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3582{
3583 Mutex::Autolock _l(mLock);
3584 mTracks.add(track);
3585}
3586
3587void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3588{
3589 Mutex::Autolock _l(mLock);
3590 destroyTrack_l(track);
3591}
3592
3593void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3594{
3595 ThreadBase::getAudioPortConfig(config);
3596 config->role = AUDIO_PORT_ROLE_SOURCE;
3597 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3598 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3599}
3600
Eric Laurent81784c32012-11-19 14:55:58 -08003601// ----------------------------------------------------------------------------
3602
3603AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003604 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3605 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003606 // mAudioMixer below
3607 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08003608 mFastMixerFutex(0),
3609 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08003610 // mOutputSink below
3611 // mPipeSink below
3612 // mNormalSink below
3613{
3614 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003615 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%zu, "
3616 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003617 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3618 mNormalFrameCount);
3619 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3620
Andy Hungfbfc3952015-01-15 13:33:51 -08003621 if (type == DUPLICATING) {
3622 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3623 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3624 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3625 return;
3626 }
Eric Laurent81784c32012-11-19 14:55:58 -08003627 // create an NBAIO sink for the HAL output stream, and negotiate
3628 mOutputSink = new AudioStreamOutSink(output->stream);
3629 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003630 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003631#if !LOG_NDEBUG
3632 ssize_t index =
3633#else
3634 (void)
3635#endif
3636 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003637 ALOG_ASSERT(index == 0);
3638
3639 // initialize fast mixer depending on configuration
3640 bool initFastMixer;
3641 switch (kUseFastMixer) {
3642 case FastMixer_Never:
3643 initFastMixer = false;
3644 break;
3645 case FastMixer_Always:
3646 initFastMixer = true;
3647 break;
3648 case FastMixer_Static:
3649 case FastMixer_Dynamic:
3650 initFastMixer = mFrameCount < mNormalFrameCount;
3651 break;
3652 }
3653 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003654 audio_format_t fastMixerFormat;
3655 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3656 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3657 } else {
3658 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3659 }
3660 if (mFormat != fastMixerFormat) {
3661 // change our Sink format to accept our intermediate precision
3662 mFormat = fastMixerFormat;
3663 free(mSinkBuffer);
3664 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3665 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3666 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3667 }
Eric Laurent81784c32012-11-19 14:55:58 -08003668
3669 // create a MonoPipe to connect our submix to FastMixer
3670 NBAIO_Format format = mOutputSink->format();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003671#ifdef TEE_SINK
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003672 NBAIO_Format origformat = format;
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003673#endif
Andy Hung1258c1a2014-05-23 21:22:17 -07003674 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07003675 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003676 format.mFormat = fastMixerFormat;
3677 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3678
Eric Laurent81784c32012-11-19 14:55:58 -08003679 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3680 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3681 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3682 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3683 const NBAIO_Format offers[1] = {format};
3684 size_t numCounterOffers = 0;
Glenn Kastenfc302fd2016-04-11 14:11:26 -07003685#if !LOG_NDEBUG || defined(TEE_SINK)
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003686 ssize_t index =
3687#else
3688 (void)
3689#endif
3690 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003691 ALOG_ASSERT(index == 0);
3692 monoPipe->setAvgFrames((mScreenState & 1) ?
3693 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3694 mPipeSink = monoPipe;
3695
Glenn Kasten46909e72013-02-26 09:20:22 -08003696#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003697 if (mTeeSinkOutputEnabled) {
3698 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003699 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3700 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003701 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003702 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003703 ALOG_ASSERT(index == 0);
3704 mTeeSink = teeSink;
3705 PipeReader *teeSource = new PipeReader(*teeSink);
3706 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003707 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003708 ALOG_ASSERT(index == 0);
3709 mTeeSource = teeSource;
3710 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003711#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003712
3713 // create fast mixer and configure it initially with just one fast track for our submix
3714 mFastMixer = new FastMixer();
3715 FastMixerStateQueue *sq = mFastMixer->sq();
3716#ifdef STATE_QUEUE_DUMP
3717 sq->setObserverDump(&mStateQueueObserverDump);
3718 sq->setMutatorDump(&mStateQueueMutatorDump);
3719#endif
3720 FastMixerState *state = sq->begin();
3721 FastTrack *fastTrack = &state->mFastTracks[0];
3722 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3723 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3724 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003725 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3726 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003727 fastTrack->mGeneration++;
3728 state->mFastTracksGen++;
3729 state->mTrackMask = 1;
3730 // fast mixer will use the HAL output sink
3731 state->mOutputSink = mOutputSink.get();
3732 state->mOutputSinkGen++;
3733 state->mFrameCount = mFrameCount;
3734 state->mCommand = FastMixerState::COLD_IDLE;
3735 // already done in constructor initialization list
3736 //mFastMixerFutex = 0;
3737 state->mColdFutexAddr = &mFastMixerFutex;
3738 state->mColdGen++;
3739 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003740#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003741 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003742#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003743 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3744 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003745 sq->end();
3746 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3747
3748 // start the fast mixer
3749 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3750 pid_t tid = mFastMixer->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003751 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003752
3753#ifdef AUDIO_WATCHDOG
3754 // create and start the watchdog
3755 mAudioWatchdog = new AudioWatchdog();
3756 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3757 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3758 tid = mAudioWatchdog->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003759 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003760#endif
3761
Eric Laurent81784c32012-11-19 14:55:58 -08003762 }
3763
3764 switch (kUseFastMixer) {
3765 case FastMixer_Never:
3766 case FastMixer_Dynamic:
3767 mNormalSink = mOutputSink;
3768 break;
3769 case FastMixer_Always:
3770 mNormalSink = mPipeSink;
3771 break;
3772 case FastMixer_Static:
3773 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3774 break;
3775 }
3776}
3777
3778AudioFlinger::MixerThread::~MixerThread()
3779{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003780 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003781 FastMixerStateQueue *sq = mFastMixer->sq();
3782 FastMixerState *state = sq->begin();
3783 if (state->mCommand == FastMixerState::COLD_IDLE) {
3784 int32_t old = android_atomic_inc(&mFastMixerFutex);
3785 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003786 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003787 }
3788 }
3789 state->mCommand = FastMixerState::EXIT;
3790 sq->end();
3791 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3792 mFastMixer->join();
3793 // Though the fast mixer thread has exited, it's state queue is still valid.
3794 // We'll use that extract the final state which contains one remaining fast track
3795 // corresponding to our sub-mix.
3796 state = sq->begin();
3797 ALOG_ASSERT(state->mTrackMask == 1);
3798 FastTrack *fastTrack = &state->mFastTracks[0];
3799 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3800 delete fastTrack->mBufferProvider;
3801 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003802 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003803#ifdef AUDIO_WATCHDOG
3804 if (mAudioWatchdog != 0) {
3805 mAudioWatchdog->requestExit();
3806 mAudioWatchdog->requestExitAndWait();
3807 mAudioWatchdog.clear();
3808 }
3809#endif
3810 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003811 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003812 delete mAudioMixer;
3813}
3814
3815
3816uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3817{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003818 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003819 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3820 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3821 }
3822 return latency;
3823}
3824
3825
3826void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3827{
3828 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3829}
3830
Eric Laurentbfb1b832013-01-07 09:53:42 -08003831ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003832{
3833 // FIXME we should only do one push per cycle; confirm this is true
3834 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003835 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003836 FastMixerStateQueue *sq = mFastMixer->sq();
3837 FastMixerState *state = sq->begin();
3838 if (state->mCommand != FastMixerState::MIX_WRITE &&
3839 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3840 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07003841
3842 // FIXME workaround for first HAL write being CPU bound on some devices
3843 ATRACE_BEGIN("write");
3844 mOutput->write((char *)mSinkBuffer, 0);
3845 ATRACE_END();
3846
Eric Laurent81784c32012-11-19 14:55:58 -08003847 int32_t old = android_atomic_inc(&mFastMixerFutex);
3848 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003849 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003850 }
3851#ifdef AUDIO_WATCHDOG
3852 if (mAudioWatchdog != 0) {
3853 mAudioWatchdog->resume();
3854 }
3855#endif
3856 }
3857 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003858#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003859 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003860 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003861#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003862 sq->end();
3863 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3864 if (kUseFastMixer == FastMixer_Dynamic) {
3865 mNormalSink = mPipeSink;
3866 }
3867 } else {
3868 sq->end(false /*didModify*/);
3869 }
3870 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003871 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003872}
3873
3874void AudioFlinger::MixerThread::threadLoop_standby()
3875{
3876 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003877 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003878 FastMixerStateQueue *sq = mFastMixer->sq();
3879 FastMixerState *state = sq->begin();
3880 if (!(state->mCommand & FastMixerState::IDLE)) {
3881 state->mCommand = FastMixerState::COLD_IDLE;
3882 state->mColdFutexAddr = &mFastMixerFutex;
3883 state->mColdGen++;
3884 mFastMixerFutex = 0;
3885 sq->end();
3886 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3887 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3888 if (kUseFastMixer == FastMixer_Dynamic) {
3889 mNormalSink = mOutputSink;
3890 }
3891#ifdef AUDIO_WATCHDOG
3892 if (mAudioWatchdog != 0) {
3893 mAudioWatchdog->pause();
3894 }
3895#endif
3896 } else {
3897 sq->end(false /*didModify*/);
3898 }
3899 }
3900 PlaybackThread::threadLoop_standby();
3901}
3902
Eric Laurentbfb1b832013-01-07 09:53:42 -08003903bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3904{
3905 return false;
3906}
3907
3908bool AudioFlinger::PlaybackThread::shouldStandby_l()
3909{
3910 return !mStandby;
3911}
3912
3913bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3914{
3915 Mutex::Autolock _l(mLock);
3916 return waitingAsyncCallback_l();
3917}
3918
Eric Laurent81784c32012-11-19 14:55:58 -08003919// shared by MIXER and DIRECT, overridden by DUPLICATING
3920void AudioFlinger::PlaybackThread::threadLoop_standby()
3921{
3922 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08003923 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003924 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003925 // discard any pending drain or write ack by incrementing sequence
3926 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3927 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003928 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003929 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3930 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003931 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003932 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003933}
3934
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003935void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3936{
3937 ALOGV("signal playback thread");
3938 broadcast_l();
3939}
3940
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003941void AudioFlinger::PlaybackThread::onAsyncError()
3942{
3943 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
3944 invalidateTracks((audio_stream_type_t)i);
3945 }
3946}
3947
Eric Laurent81784c32012-11-19 14:55:58 -08003948void AudioFlinger::MixerThread::threadLoop_mix()
3949{
Eric Laurent81784c32012-11-19 14:55:58 -08003950 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08003951 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08003952 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003953 // increase sleep time progressively when application underrun condition clears.
3954 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3955 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3956 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003957 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003958 sleepTimeShift--;
3959 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003960 mSleepTimeUs = 0;
3961 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08003962 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003963
Eric Laurent81784c32012-11-19 14:55:58 -08003964}
3965
3966void AudioFlinger::MixerThread::threadLoop_sleepTime()
3967{
3968 // If no tracks are ready, sleep once for the duration of an output
3969 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003970 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003971 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003972 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
3973 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
3974 mSleepTimeUs = kMinThreadSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003975 }
3976 // reduce sleep time in case of consecutive application underruns to avoid
3977 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3978 // duration we would end up writing less data than needed by the audio HAL if
3979 // the condition persists.
3980 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3981 sleepTimeShift++;
3982 }
3983 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003984 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003985 }
3986 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003987 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3988 // before effects processing or output.
3989 if (mMixerBufferValid) {
3990 memset(mMixerBuffer, 0, mMixerBufferSize);
3991 } else {
3992 memset(mSinkBuffer, 0, mSinkBufferSize);
3993 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003994 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003995 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3996 "anticipated start");
3997 }
3998 // TODO add standby time extension fct of effect tail
3999}
4000
4001// prepareTracks_l() must be called with ThreadBase::mLock held
4002AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
4003 Vector< sp<Track> > *tracksToRemove)
4004{
4005
4006 mixer_state mixerStatus = MIXER_IDLE;
4007 // find out which tracks need to be processed
4008 size_t count = mActiveTracks.size();
4009 size_t mixedTracks = 0;
4010 size_t tracksWithEffect = 0;
4011 // counts only _active_ fast tracks
4012 size_t fastTracks = 0;
4013 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
4014
4015 float masterVolume = mMasterVolume;
4016 bool masterMute = mMasterMute;
4017
4018 if (masterMute) {
4019 masterVolume = 0;
4020 }
4021 // Delegate master volume control to effect in output mix effect chain if needed
4022 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4023 if (chain != 0) {
4024 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
4025 chain->setVolume_l(&v, &v);
4026 masterVolume = (float)((v + (1 << 23)) >> 24);
4027 chain.clear();
4028 }
4029
4030 // prepare a new state to push
4031 FastMixerStateQueue *sq = NULL;
4032 FastMixerState *state = NULL;
4033 bool didModify = false;
4034 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004035 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004036 sq = mFastMixer->sq();
4037 state = sq->begin();
4038 }
4039
Andy Hung69aed5f2014-02-25 17:24:40 -08004040 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08004041 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08004042
Eric Laurent81784c32012-11-19 14:55:58 -08004043 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07004044 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08004045 if (t == 0) {
4046 continue;
4047 }
4048
4049 // this const just means the local variable doesn't change
4050 Track* const track = t.get();
4051
4052 // process fast tracks
4053 if (track->isFastTrack()) {
4054
4055 // It's theoretically possible (though unlikely) for a fast track to be created
4056 // and then removed within the same normal mix cycle. This is not a problem, as
4057 // the track never becomes active so it's fast mixer slot is never touched.
4058 // The converse, of removing an (active) track and then creating a new track
4059 // at the identical fast mixer slot within the same normal mix cycle,
4060 // is impossible because the slot isn't marked available until the end of each cycle.
4061 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07004062 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08004063 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
4064 FastTrack *fastTrack = &state->mFastTracks[j];
4065
4066 // Determine whether the track is currently in underrun condition,
4067 // and whether it had a recent underrun.
4068 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
4069 FastTrackUnderruns underruns = ftDump->mUnderruns;
4070 uint32_t recentFull = (underruns.mBitFields.mFull -
4071 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
4072 uint32_t recentPartial = (underruns.mBitFields.mPartial -
4073 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
4074 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
4075 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
4076 uint32_t recentUnderruns = recentPartial + recentEmpty;
4077 track->mObservedUnderruns = underruns;
4078 // don't count underruns that occur while stopping or pausing
4079 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07004080 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
4081 recentUnderruns > 0) {
4082 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
4083 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Phil Burk2812d9e2016-01-04 10:34:30 -08004084 } else {
4085 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Eric Laurent81784c32012-11-19 14:55:58 -08004086 }
4087
4088 // This is similar to the state machine for normal tracks,
4089 // with a few modifications for fast tracks.
4090 bool isActive = true;
4091 switch (track->mState) {
4092 case TrackBase::STOPPING_1:
4093 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08004094 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004095 track->mState = TrackBase::STOPPING_2;
4096 }
4097 break;
4098 case TrackBase::PAUSING:
4099 // ramp down is not yet implemented
4100 track->setPaused();
4101 break;
4102 case TrackBase::RESUMING:
4103 // ramp up is not yet implemented
4104 track->mState = TrackBase::ACTIVE;
4105 break;
4106 case TrackBase::ACTIVE:
4107 if (recentFull > 0 || recentPartial > 0) {
4108 // track has provided at least some frames recently: reset retry count
4109 track->mRetryCount = kMaxTrackRetries;
4110 }
4111 if (recentUnderruns == 0) {
4112 // no recent underruns: stay active
4113 break;
4114 }
4115 // there has recently been an underrun of some kind
4116 if (track->sharedBuffer() == 0) {
4117 // were any of the recent underruns "empty" (no frames available)?
4118 if (recentEmpty == 0) {
4119 // no, then ignore the partial underruns as they are allowed indefinitely
4120 break;
4121 }
4122 // there has recently been an "empty" underrun: decrement the retry counter
4123 if (--(track->mRetryCount) > 0) {
4124 break;
4125 }
4126 // indicate to client process that the track was disabled because of underrun;
4127 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004128 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004129 // remove from active list, but state remains ACTIVE [confusing but true]
4130 isActive = false;
4131 break;
4132 }
4133 // fall through
4134 case TrackBase::STOPPING_2:
4135 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08004136 case TrackBase::STOPPED:
4137 case TrackBase::FLUSHED: // flush() while active
4138 // Check for presentation complete if track is inactive
4139 // We have consumed all the buffers of this track.
4140 // This would be incomplete if we auto-paused on underrun
4141 {
4142 size_t audioHALFrames =
4143 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004144 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004145 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
4146 // track stays in active list until presentation is complete
4147 break;
4148 }
4149 }
4150 if (track->isStopping_2()) {
4151 track->mState = TrackBase::STOPPED;
4152 }
4153 if (track->isStopped()) {
4154 // Can't reset directly, as fast mixer is still polling this track
4155 // track->reset();
4156 // So instead mark this track as needing to be reset after push with ack
4157 resetMask |= 1 << i;
4158 }
4159 isActive = false;
4160 break;
4161 case TrackBase::IDLE:
4162 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08004163 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08004164 }
4165
4166 if (isActive) {
4167 // was it previously inactive?
4168 if (!(state->mTrackMask & (1 << j))) {
4169 ExtendedAudioBufferProvider *eabp = track;
4170 VolumeProvider *vp = track;
4171 fastTrack->mBufferProvider = eabp;
4172 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08004173 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07004174 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08004175 fastTrack->mGeneration++;
4176 state->mTrackMask |= 1 << j;
4177 didModify = true;
4178 // no acknowledgement required for newly active tracks
4179 }
4180 // cache the combined master volume and stream type volume for fast mixer; this
4181 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08004182 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08004183 ++fastTracks;
4184 } else {
4185 // was it previously active?
4186 if (state->mTrackMask & (1 << j)) {
4187 fastTrack->mBufferProvider = NULL;
4188 fastTrack->mGeneration++;
4189 state->mTrackMask &= ~(1 << j);
4190 didModify = true;
4191 // If any fast tracks were removed, we must wait for acknowledgement
4192 // because we're about to decrement the last sp<> on those tracks.
4193 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4194 } else {
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08004195 LOG_ALWAYS_FATAL("fast track %d should have been active; "
4196 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
4197 j, track->mState, state->mTrackMask, recentUnderruns,
4198 track->sharedBuffer() != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004199 }
4200 tracksToRemove->add(track);
4201 // Avoids a misleading display in dumpsys
4202 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
4203 }
4204 continue;
4205 }
4206
4207 { // local variable scope to avoid goto warning
4208
4209 audio_track_cblk_t* cblk = track->cblk();
4210
4211 // The first time a track is added we wait
4212 // for all its buffers to be filled before processing it
4213 int name = track->name();
4214 // make sure that we have enough frames to mix one full buffer.
4215 // enforce this condition only once to enable draining the buffer in case the client
4216 // app does not call stop() and relies on underrun to stop:
4217 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
4218 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004219 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07004220 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004221 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004222
4223 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004224 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004225 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
4226 // add frames already consumed but not yet released by the resampler
4227 // because mAudioTrackServerProxy->framesReady() will include these frames
4228 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
4229
Eric Laurent81784c32012-11-19 14:55:58 -08004230 uint32_t minFrames = 1;
4231 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
4232 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004233 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08004234 }
Eric Laurent13e4c962013-12-20 17:36:01 -08004235
4236 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07004237 if (ATRACE_ENABLED()) {
4238 // I wish we had formatted trace names
4239 char traceName[16];
4240 strcpy(traceName, "nRdy");
4241 int name = track->name();
4242 if (AudioMixer::TRACK0 <= name &&
4243 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
4244 name -= AudioMixer::TRACK0;
4245 traceName[4] = (name / 10) + '0';
4246 traceName[5] = (name % 10) + '0';
4247 } else {
4248 traceName[4] = '?';
4249 traceName[5] = '?';
4250 }
4251 traceName[6] = '\0';
4252 ATRACE_INT(traceName, framesReady);
4253 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004254 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08004255 !track->isPaused() && !track->isTerminated())
4256 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004257 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004258
4259 mixedTracks++;
4260
Andy Hung69aed5f2014-02-25 17:24:40 -08004261 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
4262 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08004263 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08004264 if (track->mainBuffer() != mSinkBuffer &&
4265 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004266 if (mEffectBufferEnabled) {
4267 mEffectBufferValid = true; // Later can set directly.
4268 }
Eric Laurent81784c32012-11-19 14:55:58 -08004269 chain = getEffectChain_l(track->sessionId());
4270 // Delegate volume control to effect in track effect chain if needed
4271 if (chain != 0) {
4272 tracksWithEffect++;
4273 } else {
4274 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
4275 "session %d",
4276 name, track->sessionId());
4277 }
4278 }
4279
4280
4281 int param = AudioMixer::VOLUME;
4282 if (track->mFillingUpStatus == Track::FS_FILLED) {
4283 // no ramp for the first volume setting
4284 track->mFillingUpStatus = Track::FS_ACTIVE;
4285 if (track->mState == TrackBase::RESUMING) {
4286 track->mState = TrackBase::ACTIVE;
4287 param = AudioMixer::RAMP_VOLUME;
4288 }
4289 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004290 // FIXME should not make a decision based on mServer
4291 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004292 // If the track is stopped before the first frame was mixed,
4293 // do not apply ramp
4294 param = AudioMixer::RAMP_VOLUME;
4295 }
4296
4297 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07004298 uint32_t vl, vr; // in U8.24 integer format
4299 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08004300 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07004301 vl = vr = 0;
4302 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08004303 if (track->isPausing()) {
4304 track->setPaused();
4305 }
4306 } else {
4307
4308 // read original volumes with volume control
4309 float typeVolume = mStreamTypes[track->streamType()].volume;
4310 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004311 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004312 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07004313 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
4314 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08004315 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07004316 if (vlf > GAIN_FLOAT_UNITY) {
4317 ALOGV("Track left volume out of range: %.3g", vlf);
4318 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004319 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07004320 if (vrf > GAIN_FLOAT_UNITY) {
4321 ALOGV("Track right volume out of range: %.3g", vrf);
4322 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004323 }
4324 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07004325 vlf *= v;
4326 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08004327 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07004328 // then derive vl and vr as U8.24 versions for the effect chain
4329 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
4330 vl = (uint32_t) (scaleto8_24 * vlf);
4331 vr = (uint32_t) (scaleto8_24 * vrf);
4332 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08004333 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08004334 // send level comes from shared memory and so may be corrupt
4335 if (sendLevel > MAX_GAIN_INT) {
4336 ALOGV("Track send level out of range: %04X", sendLevel);
4337 sendLevel = MAX_GAIN_INT;
4338 }
Andy Hung6be49402014-05-30 10:42:03 -07004339 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4340 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08004341 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004342
Eric Laurent81784c32012-11-19 14:55:58 -08004343 // Delegate volume control to effect in track effect chain if needed
4344 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4345 // Do not ramp volume if volume is controlled by effect
4346 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08004347 // Update remaining floating point volume levels
4348 vlf = (float)vl / (1 << 24);
4349 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004350 track->mHasVolumeController = true;
4351 } else {
4352 // force no volume ramp when volume controller was just disabled or removed
4353 // from effect chain to avoid volume spike
4354 if (track->mHasVolumeController) {
4355 param = AudioMixer::VOLUME;
4356 }
4357 track->mHasVolumeController = false;
4358 }
4359
Eric Laurent81784c32012-11-19 14:55:58 -08004360 // XXX: these things DON'T need to be done each time
4361 mAudioMixer->setBufferProvider(name, track);
4362 mAudioMixer->enable(name);
4363
Andy Hung6be49402014-05-30 10:42:03 -07004364 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
4365 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
4366 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004367 mAudioMixer->setParameter(
4368 name,
4369 AudioMixer::TRACK,
4370 AudioMixer::FORMAT, (void *)track->format());
4371 mAudioMixer->setParameter(
4372 name,
4373 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004374 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004375 mAudioMixer->setParameter(
4376 name,
4377 AudioMixer::TRACK,
4378 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004379 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004380 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004381 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004382 if (reqSampleRate == 0) {
4383 reqSampleRate = mSampleRate;
4384 } else if (reqSampleRate > maxSampleRate) {
4385 reqSampleRate = maxSampleRate;
4386 }
Eric Laurent81784c32012-11-19 14:55:58 -08004387 mAudioMixer->setParameter(
4388 name,
4389 AudioMixer::RESAMPLE,
4390 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004391 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004392
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004393 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004394 mAudioMixer->setParameter(
4395 name,
4396 AudioMixer::TIMESTRETCH,
4397 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004398 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004399
Andy Hung69aed5f2014-02-25 17:24:40 -08004400 /*
4401 * Select the appropriate output buffer for the track.
4402 *
Andy Hung98ef9782014-03-04 14:46:50 -08004403 * Tracks with effects go into their own effects chain buffer
4404 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004405 *
4406 * Other tracks can use mMixerBuffer for higher precision
4407 * channel accumulation. If this buffer is enabled
4408 * (mMixerBufferEnabled true), then selected tracks will accumulate
4409 * into it.
4410 *
4411 */
4412 if (mMixerBufferEnabled
4413 && (track->mainBuffer() == mSinkBuffer
4414 || track->mainBuffer() == mMixerBuffer)) {
4415 mAudioMixer->setParameter(
4416 name,
4417 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004418 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004419 mAudioMixer->setParameter(
4420 name,
4421 AudioMixer::TRACK,
4422 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4423 // TODO: override track->mainBuffer()?
4424 mMixerBufferValid = true;
4425 } else {
4426 mAudioMixer->setParameter(
4427 name,
4428 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004429 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004430 mAudioMixer->setParameter(
4431 name,
4432 AudioMixer::TRACK,
4433 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4434 }
Eric Laurent81784c32012-11-19 14:55:58 -08004435 mAudioMixer->setParameter(
4436 name,
4437 AudioMixer::TRACK,
4438 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4439
4440 // reset retry count
4441 track->mRetryCount = kMaxTrackRetries;
4442
4443 // If one track is ready, set the mixer ready if:
4444 // - the mixer was not ready during previous round OR
4445 // - no other track is not ready
4446 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4447 mixerStatus != MIXER_TRACKS_ENABLED) {
4448 mixerStatus = MIXER_TRACKS_READY;
4449 }
4450 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004451 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hung08fb1742015-05-31 23:22:10 -07004452 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)",
4453 track, framesReady, desiredFrames);
Glenn Kasten82aaf942013-07-17 16:05:07 -07004454 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08004455 } else {
4456 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004457 }
Phil Burk2812d9e2016-01-04 10:34:30 -08004458
Eric Laurent81784c32012-11-19 14:55:58 -08004459 // clear effect chain input buffer if an active track underruns to avoid sending
4460 // previous audio buffer again to effects
4461 chain = getEffectChain_l(track->sessionId());
4462 if (chain != 0) {
4463 chain->clearInputBuffer();
4464 }
4465
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004466 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004467 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4468 track->isStopped() || track->isPaused()) {
4469 // We have consumed all the buffers of this track.
4470 // Remove it from the list of active tracks.
4471 // TODO: use actual buffer filling status instead of latency when available from
4472 // audio HAL
4473 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004474 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004475 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4476 if (track->isStopped()) {
4477 track->reset();
4478 }
4479 tracksToRemove->add(track);
4480 }
4481 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004482 // No buffers for this track. Give it a few chances to
4483 // fill a buffer, then remove it from active list.
4484 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004485 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004486 tracksToRemove->add(track);
4487 // indicate to client process that the track was disabled because of underrun;
4488 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004489 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004490 // If one track is not ready, mark the mixer also not ready if:
4491 // - the mixer was ready during previous round OR
4492 // - no other track is ready
4493 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4494 mixerStatus != MIXER_TRACKS_READY) {
4495 mixerStatus = MIXER_TRACKS_ENABLED;
4496 }
4497 }
4498 mAudioMixer->disable(name);
4499 }
4500
4501 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08004502
4503 }
4504
4505 // Push the new FastMixer state if necessary
4506 bool pauseAudioWatchdog = false;
4507 if (didModify) {
4508 state->mFastTracksGen++;
4509 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4510 if (kUseFastMixer == FastMixer_Dynamic &&
4511 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4512 state->mCommand = FastMixerState::COLD_IDLE;
4513 state->mColdFutexAddr = &mFastMixerFutex;
4514 state->mColdGen++;
4515 mFastMixerFutex = 0;
4516 if (kUseFastMixer == FastMixer_Dynamic) {
4517 mNormalSink = mOutputSink;
4518 }
4519 // If we go into cold idle, need to wait for acknowledgement
4520 // so that fast mixer stops doing I/O.
4521 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4522 pauseAudioWatchdog = true;
4523 }
Eric Laurent81784c32012-11-19 14:55:58 -08004524 }
4525 if (sq != NULL) {
4526 sq->end(didModify);
4527 sq->push(block);
4528 }
4529#ifdef AUDIO_WATCHDOG
4530 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4531 mAudioWatchdog->pause();
4532 }
4533#endif
4534
4535 // Now perform the deferred reset on fast tracks that have stopped
4536 while (resetMask != 0) {
4537 size_t i = __builtin_ctz(resetMask);
4538 ALOG_ASSERT(i < count);
4539 resetMask &= ~(1 << i);
4540 sp<Track> t = mActiveTracks[i].promote();
4541 if (t == 0) {
4542 continue;
4543 }
4544 Track* track = t.get();
4545 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4546 track->reset();
4547 }
4548
4549 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004550 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004551
Eric Laurent97d547d2014-09-02 14:45:53 -07004552 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4553 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004554 }
4555
4556 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004557 // as long as there are effects we should clear the effects buffer, to avoid
4558 // passing a non-clean buffer to the effect chain
4559 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004560 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004561 // sink or mix buffer must be cleared if all tracks are connected to an
4562 // effect chain as in this case the mixer will not write to the sink or mix buffer
4563 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004564 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4565 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004566 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004567 if (mMixerBufferValid) {
4568 memset(mMixerBuffer, 0, mMixerBufferSize);
4569 // TODO: In testing, mSinkBuffer below need not be cleared because
4570 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4571 // after mixing.
4572 //
4573 // To enforce this guarantee:
4574 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4575 // (mixedTracks == 0 && fastTracks > 0))
4576 // must imply MIXER_TRACKS_READY.
4577 // Later, we may clear buffers regardless, and skip much of this logic.
4578 }
Andy Hung98ef9782014-03-04 14:46:50 -08004579 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004580 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004581 }
4582
4583 // if any fast tracks, then status is ready
4584 mMixerStatusIgnoringFastTracks = mixerStatus;
4585 if (fastTracks > 0) {
4586 mixerStatus = MIXER_TRACKS_READY;
4587 }
4588 return mixerStatus;
4589}
4590
Eric Laurentad7dd962016-09-22 12:38:37 -07004591// trackCountForUid_l() must be called with ThreadBase::mLock held
4592uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid)
4593{
4594 uint32_t trackCount = 0;
4595 for (size_t i = 0; i < mTracks.size() ; i++) {
4596 if (mTracks[i]->uid() == (int)uid) {
4597 trackCount++;
4598 }
4599 }
4600 return trackCount;
4601}
4602
Eric Laurent81784c32012-11-19 14:55:58 -08004603// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07004604int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
Eric Laurentad7dd962016-09-22 12:38:37 -07004605 audio_format_t format, audio_session_t sessionId, uid_t uid)
Eric Laurent81784c32012-11-19 14:55:58 -08004606{
Eric Laurentad7dd962016-09-22 12:38:37 -07004607 if (trackCountForUid_l(uid) > (PlaybackThread::kMaxTracksPerUid - 1)) {
4608 return -1;
4609 }
Andy Hunge8a1ced2014-05-09 15:02:21 -07004610 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08004611}
4612
4613// deleteTrackName_l() must be called with ThreadBase::mLock held
4614void AudioFlinger::MixerThread::deleteTrackName_l(int name)
4615{
4616 ALOGV("remove track (%d) and delete from mixer", name);
4617 mAudioMixer->deleteTrackName(name);
4618}
4619
Eric Laurent10351942014-05-08 18:49:52 -07004620// checkForNewParameter_l() must be called with ThreadBase::mLock held
4621bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4622 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004623{
Eric Laurent81784c32012-11-19 14:55:58 -08004624 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08004625 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004626
Eric Laurent10351942014-05-08 18:49:52 -07004627 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004628
Glenn Kastenc05b8d72016-03-24 09:48:17 -07004629 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004630
Eric Laurent10351942014-05-08 18:49:52 -07004631 AudioParameter param = AudioParameter(keyValuePair);
4632 int value;
4633 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4634 reconfig = true;
4635 }
4636 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004637 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004638 status = BAD_VALUE;
4639 } else {
4640 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004641 reconfig = true;
4642 }
Eric Laurent10351942014-05-08 18:49:52 -07004643 }
4644 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004645 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004646 status = BAD_VALUE;
4647 } else {
4648 // no need to save value, since it's constant
4649 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004650 }
Eric Laurent10351942014-05-08 18:49:52 -07004651 }
4652 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4653 // do not accept frame count changes if tracks are open as the track buffer
4654 // size depends on frame count and correct behavior would not be guaranteed
4655 // if frame count is changed after track creation
4656 if (!mTracks.isEmpty()) {
4657 status = INVALID_OPERATION;
4658 } else {
4659 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004660 }
Eric Laurent10351942014-05-08 18:49:52 -07004661 }
4662 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004663#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004664 // when changing the audio output device, call addBatteryData to notify
4665 // the change
4666 if (mOutDevice != value) {
4667 uint32_t params = 0;
4668 // check whether speaker is on
4669 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4670 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004671 }
Eric Laurent10351942014-05-08 18:49:52 -07004672
4673 audio_devices_t deviceWithoutSpeaker
4674 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4675 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07004676 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07004677 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4678 }
4679
4680 if (params != 0) {
4681 addBatteryData(params);
4682 }
4683 }
Eric Laurent81784c32012-11-19 14:55:58 -08004684#endif
4685
Eric Laurent10351942014-05-08 18:49:52 -07004686 // forward device change to effects that have requested to be
4687 // aware of attached audio device.
4688 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08004689 a2dpDeviceChanged =
4690 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07004691 mOutDevice = value;
4692 for (size_t i = 0; i < mEffectChains.size(); i++) {
4693 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004694 }
4695 }
Eric Laurent10351942014-05-08 18:49:52 -07004696 }
Eric Laurent81784c32012-11-19 14:55:58 -08004697
Eric Laurent10351942014-05-08 18:49:52 -07004698 if (status == NO_ERROR) {
4699 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4700 keyValuePair.string());
4701 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004702 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004703 mStandby = true;
4704 mBytesWritten = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004705 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Eric Laurent10351942014-05-08 18:49:52 -07004706 keyValuePair.string());
Eric Laurent81784c32012-11-19 14:55:58 -08004707 }
Eric Laurent10351942014-05-08 18:49:52 -07004708 if (status == NO_ERROR && reconfig) {
4709 readOutputParameters_l();
4710 delete mAudioMixer;
4711 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4712 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004713 int name = getTrackName_l(mTracks[i]->mChannelMask,
Eric Laurentad7dd962016-09-22 12:38:37 -07004714 mTracks[i]->mFormat, mTracks[i]->mSessionId, mTracks[i]->uid());
Eric Laurent10351942014-05-08 18:49:52 -07004715 if (name < 0) {
4716 break;
4717 }
4718 mTracks[i]->mName = name;
4719 }
Eric Laurent73e26b62015-04-27 16:55:58 -07004720 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004721 }
Eric Laurent81784c32012-11-19 14:55:58 -08004722 }
4723
Eric Laurent42537be2016-01-08 17:16:42 -08004724 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08004725}
4726
4727
4728void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4729{
Eric Laurent81784c32012-11-19 14:55:58 -08004730 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07004731 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Elliott Hughes87cebad2014-05-22 10:14:43 -07004732 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Andy Hung2ddee192015-12-18 17:34:44 -08004733 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent81784c32012-11-19 14:55:58 -08004734
4735 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten2f90c512015-12-02 11:40:09 -08004736 // while we are dumping it. It may be inconsistent, but it won't mutate!
4737 // This is a large object so we place it on the heap.
4738 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
4739 const FastMixerDumpState *copy = new FastMixerDumpState(mFastMixerDumpState);
4740 copy->dump(fd);
4741 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08004742
4743#ifdef STATE_QUEUE_DUMP
4744 // Similar for state queue
4745 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4746 observerCopy.dump(fd);
4747 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4748 mutatorCopy.dump(fd);
4749#endif
4750
Glenn Kasten46909e72013-02-26 09:20:22 -08004751#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004752 // Write the tee output to a .wav file
4753 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08004754#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004755
4756#ifdef AUDIO_WATCHDOG
4757 if (mAudioWatchdog != 0) {
4758 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4759 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4760 wdCopy.dump(fd);
4761 }
4762#endif
4763}
4764
4765uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4766{
4767 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4768}
4769
4770uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4771{
4772 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4773}
4774
4775void AudioFlinger::MixerThread::cacheParameters_l()
4776{
4777 PlaybackThread::cacheParameters_l();
4778
4779 // FIXME: Relaxed timing because of a certain device that can't meet latency
4780 // Should be reduced to 2x after the vendor fixes the driver issue
4781 // increase threshold again due to low power audio mode. The way this warning
4782 // threshold is calculated and its usefulness should be reconsidered anyway.
4783 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4784}
4785
4786// ----------------------------------------------------------------------------
4787
4788AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07004789 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady)
4790 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08004791 // mLeftVolFloat, mRightVolFloat
4792{
4793}
4794
Eric Laurentbfb1b832013-01-07 09:53:42 -08004795AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4796 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurente93cc032016-05-05 10:15:10 -07004797 ThreadBase::type_t type, bool systemReady)
4798 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004799 // mLeftVolFloat, mRightVolFloat
4800{
4801}
4802
Eric Laurent81784c32012-11-19 14:55:58 -08004803AudioFlinger::DirectOutputThread::~DirectOutputThread()
4804{
4805}
4806
Eric Laurentbfb1b832013-01-07 09:53:42 -08004807void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
4808{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004809 float left, right;
4810
4811 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4812 left = right = 0;
4813 } else {
4814 float typeVolume = mStreamTypes[track->streamType()].volume;
4815 float v = mMasterVolume * typeVolume;
4816 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004817 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4818 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4819 if (left > GAIN_FLOAT_UNITY) {
4820 left = GAIN_FLOAT_UNITY;
4821 }
4822 left *= v;
4823 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4824 if (right > GAIN_FLOAT_UNITY) {
4825 right = GAIN_FLOAT_UNITY;
4826 }
4827 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004828 }
4829
4830 if (lastTrack) {
4831 if (left != mLeftVolFloat || right != mRightVolFloat) {
4832 mLeftVolFloat = left;
4833 mRightVolFloat = right;
4834
4835 // Convert volumes from float to 8.24
4836 uint32_t vl = (uint32_t)(left * (1 << 24));
4837 uint32_t vr = (uint32_t)(right * (1 << 24));
4838
4839 // Delegate volume control to effect in track effect chain if needed
4840 // only one effect chain can be present on DirectOutputThread, so if
4841 // there is one, the track is connected to it
4842 if (!mEffectChains.isEmpty()) {
4843 mEffectChains[0]->setVolume_l(&vl, &vr);
4844 left = (float)vl / (1 << 24);
4845 right = (float)vr / (1 << 24);
4846 }
4847 if (mOutput->stream->set_volume) {
4848 mOutput->stream->set_volume(mOutput->stream, left, right);
4849 }
4850 }
4851 }
4852}
4853
Phil Burk43b4dcc2015-06-09 16:53:44 -07004854void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
4855{
4856 sp<Track> previousTrack = mPreviousTrack.promote();
4857 sp<Track> latestTrack = mLatestActiveTrack.promote();
4858
Eric Laurent0f0631e2015-07-06 18:01:25 -07004859 if (previousTrack != 0 && latestTrack != 0) {
4860 if (mType == DIRECT) {
4861 if (previousTrack.get() != latestTrack.get()) {
4862 mFlushPending = true;
4863 }
4864 } else /* mType == OFFLOAD */ {
4865 if (previousTrack->sessionId() != latestTrack->sessionId()) {
4866 mFlushPending = true;
4867 }
4868 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004869 }
4870 PlaybackThread::onAddNewTrack_l();
4871}
Eric Laurentbfb1b832013-01-07 09:53:42 -08004872
Eric Laurent81784c32012-11-19 14:55:58 -08004873AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4874 Vector< sp<Track> > *tracksToRemove
4875)
4876{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004877 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004878 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004879 bool doHwPause = false;
4880 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004881
4882 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07004883 for (size_t i = 0; i < count; i++) {
4884 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08004885 // The track died recently
4886 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004887 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08004888 }
4889
Phil Burk43b4dcc2015-06-09 16:53:44 -07004890 if (t->isInvalid()) {
4891 ALOGW("An invalidated track shouldn't be in active list");
4892 tracksToRemove->add(t);
4893 continue;
4894 }
4895
Eric Laurent81784c32012-11-19 14:55:58 -08004896 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004897#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08004898 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004899#endif
Eric Laurentfd477972013-10-25 18:10:40 -07004900 // Only consider last track started for volume and mixer state control.
4901 // In theory an older track could underrun and restart after the new one starts
4902 // but as we only care about the transition phase between two tracks on a
4903 // direct output, it is not a problem to ignore the underrun case.
4904 sp<Track> l = mLatestActiveTrack.promote();
4905 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004906
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004907 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004908 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004909 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004910 doHwPause = true;
4911 mHwPaused = true;
4912 }
4913 tracksToRemove->add(track);
4914 } else if (track->isFlushPending()) {
4915 track->flushAck();
4916 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004917 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004918 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004919 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004920 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07004921 if (last) {
4922 mLeftVolFloat = mRightVolFloat = -1.0;
4923 if (mHwPaused) {
4924 doHwResume = true;
4925 mHwPaused = false;
4926 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004927 }
4928 }
4929
Eric Laurent81784c32012-11-19 14:55:58 -08004930 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004931 // for all its buffers to be filled before processing it.
4932 // Allow draining the buffer in case the client
4933 // app does not call stop() and relies on underrun to stop:
4934 // hence the test on (track->mRetryCount > 1).
4935 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07004936 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08004937 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004938 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08004939 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004940 minFrames = mNormalFrameCount;
4941 } else {
4942 minFrames = 1;
4943 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004944
Eric Laurentab5cdba2014-06-09 17:22:27 -07004945 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4946 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004947 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004948 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004949
4950 if (track->mFillingUpStatus == Track::FS_FILLED) {
4951 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07004952 if (last) {
4953 // make sure processVolume_l() will apply new volume even if 0
4954 mLeftVolFloat = mRightVolFloat = -1.0;
4955 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004956 if (!mHwSupportsPause) {
4957 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004958 }
4959 }
4960
4961 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004962 processVolume_l(track, last);
4963 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004964 sp<Track> previousTrack = mPreviousTrack.promote();
4965 if (previousTrack != 0) {
4966 if (track != previousTrack.get()) {
4967 // Flush any data still being written from last track
4968 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07004969 // Invalidate previous track to force a seek when resuming.
4970 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004971 }
4972 }
4973 mPreviousTrack = track;
4974
Eric Laurentd595b7c2013-04-03 17:27:56 -07004975 // reset retry count
4976 track->mRetryCount = kMaxTrackRetriesDirect;
4977 mActiveTrack = t;
4978 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07004979 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004980 doHwResume = true;
4981 mHwPaused = false;
4982 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004983 }
Eric Laurent81784c32012-11-19 14:55:58 -08004984 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004985 // clear effect chain input buffer if the last active track started underruns
4986 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004987 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004988 mEffectChains[0]->clearInputBuffer();
4989 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004990 if (track->isStopping_1()) {
4991 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07004992 if (last && mHwPaused) {
4993 doHwResume = true;
4994 mHwPaused = false;
4995 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004996 }
4997 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4998 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004999 // We have consumed all the buffers of this track.
5000 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07005001 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08005002 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005003 audioHALFrames = (latency_l() * mSampleRate) / 1000;
5004 } else {
5005 audioHALFrames = 0;
5006 }
5007
Andy Hung818e7a32016-02-16 18:08:07 -08005008 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07005009 if (mStandby || !last ||
5010 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005011 if (track->isStopping_2()) {
5012 track->mState = TrackBase::STOPPED;
5013 }
Eric Laurent81784c32012-11-19 14:55:58 -08005014 if (track->isStopped()) {
5015 track->reset();
5016 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005017 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08005018 }
5019 } else {
5020 // No buffers for this track. Give it a few chances to
5021 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07005022 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08005023 if (--(track->mRetryCount) <= 0) {
5024 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07005025 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005026 // indicate to client process that the track was disabled because of underrun;
5027 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005028 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005029 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07005030 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
5031 "minFrames = %u, mFormat = %#x",
5032 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08005033 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07005034 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005035 doHwPause = true;
5036 mHwPaused = true;
5037 }
Eric Laurent81784c32012-11-19 14:55:58 -08005038 }
5039 }
5040 }
5041 }
5042
Eric Laurentd1f69b02014-12-15 14:33:13 -08005043 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07005044 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005045 for (size_t i = 0; i < mTracks.size(); i++) {
5046 if (mTracks[i]->isFlushPending()) {
5047 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005048 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005049 }
5050 }
5051 }
5052
5053 // make sure the pause/flush/resume sequence is executed in the right order.
5054 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5055 // before flush and then resume HW. This can happen in case of pause/flush/resume
5056 // if resume is received before pause is executed.
5057 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07005058 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005059 mOutput->stream->pause(mOutput->stream);
5060 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005061 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005062 flushHw_l();
5063 }
5064 if (mHwSupportsPause && !mStandby && doHwResume) {
5065 mOutput->stream->resume(mOutput->stream);
5066 }
Eric Laurent81784c32012-11-19 14:55:58 -08005067 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005068 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005069
5070 return mixerStatus;
5071}
5072
5073void AudioFlinger::DirectOutputThread::threadLoop_mix()
5074{
Eric Laurent81784c32012-11-19 14:55:58 -08005075 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08005076 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005077 // output audio to hardware
5078 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07005079 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005080 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08005081 status_t status = mActiveTrack->getNextBuffer(&buffer);
5082 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08005083 // no need to pad with 0 for compressed audio
5084 if (audio_has_proportional_frames(mFormat)) {
5085 memset(curBuf, 0, frameCount * mFrameSize);
5086 }
Eric Laurent81784c32012-11-19 14:55:58 -08005087 break;
5088 }
5089 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
5090 frameCount -= buffer.frameCount;
5091 curBuf += buffer.frameCount * mFrameSize;
5092 mActiveTrack->releaseBuffer(&buffer);
5093 }
Andy Hung2098f272014-02-27 14:00:06 -08005094 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005095 mSleepTimeUs = 0;
5096 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005097 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005098}
5099
5100void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
5101{
Eric Laurentd1f69b02014-12-15 14:33:13 -08005102 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005103 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005104 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005105 return;
5106 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005107 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005108 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurente93cc032016-05-05 10:15:10 -07005109 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005110 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005111 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005112 }
Phil Burkfdb3c072016-02-09 10:47:02 -08005113 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08005114 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005115 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005116 }
5117}
5118
Eric Laurentd1f69b02014-12-15 14:33:13 -08005119void AudioFlinger::DirectOutputThread::threadLoop_exit()
5120{
5121 {
5122 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005123 for (size_t i = 0; i < mTracks.size(); i++) {
5124 if (mTracks[i]->isFlushPending()) {
5125 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005126 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005127 }
5128 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005129 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005130 flushHw_l();
5131 }
5132 }
5133 PlaybackThread::threadLoop_exit();
5134}
5135
5136// must be called with thread mutex locked
5137bool AudioFlinger::DirectOutputThread::shouldStandby_l()
5138{
5139 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07005140 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005141
vivek mehta9cd7ad12016-03-17 00:18:29 -07005142 if ((mType == DIRECT) && audio_is_linear_pcm(mFormat) && !usesHwAvSync()) {
5143 return !mStandby;
5144 }
5145
Eric Laurentd1f69b02014-12-15 14:33:13 -08005146 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
5147 // after a timeout and we will enter standby then.
5148 if (mTracks.size() > 0) {
5149 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07005150 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
5151 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005152 }
5153
Eric Laurent5cff4032015-05-26 13:49:58 -07005154 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08005155}
5156
Eric Laurent81784c32012-11-19 14:55:58 -08005157// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005158int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Eric Laurentad7dd962016-09-22 12:38:37 -07005159 audio_format_t format __unused, audio_session_t sessionId __unused, uid_t uid)
Eric Laurent81784c32012-11-19 14:55:58 -08005160{
Eric Laurentad7dd962016-09-22 12:38:37 -07005161 if (trackCountForUid_l(uid) > (PlaybackThread::kMaxTracksPerUid - 1)) {
5162 return -1;
5163 }
Eric Laurent81784c32012-11-19 14:55:58 -08005164 return 0;
5165}
5166
5167// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005168void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005169{
5170}
5171
Eric Laurent10351942014-05-08 18:49:52 -07005172// checkForNewParameter_l() must be called with ThreadBase::mLock held
5173bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
5174 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005175{
5176 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005177 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005178
Eric Laurent10351942014-05-08 18:49:52 -07005179 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005180
Eric Laurent10351942014-05-08 18:49:52 -07005181 AudioParameter param = AudioParameter(keyValuePair);
5182 int value;
5183 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5184 // forward device change to effects that have requested to be
5185 // aware of attached audio device.
5186 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005187 a2dpDeviceChanged =
5188 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005189 mOutDevice = value;
5190 for (size_t i = 0; i < mEffectChains.size(); i++) {
5191 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07005192 }
5193 }
Eric Laurent81784c32012-11-19 14:55:58 -08005194 }
Eric Laurent10351942014-05-08 18:49:52 -07005195 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5196 // do not accept frame count changes if tracks are open as the track buffer
5197 // size depends on frame count and correct behavior would not be garantied
5198 // if frame count is changed after track creation
5199 if (!mTracks.isEmpty()) {
5200 status = INVALID_OPERATION;
5201 } else {
5202 reconfig = true;
5203 }
5204 }
5205 if (status == NO_ERROR) {
5206 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
5207 keyValuePair.string());
5208 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005209 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005210 mStandby = true;
5211 mBytesWritten = 0;
5212 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
5213 keyValuePair.string());
5214 }
5215 if (status == NO_ERROR && reconfig) {
5216 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07005217 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005218 }
5219 }
5220
Eric Laurent42537be2016-01-08 17:16:42 -08005221 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005222}
5223
5224uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
5225{
5226 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005227 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005228 time = PlaybackThread::activeSleepTimeUs();
5229 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005230 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005231 }
5232 return time;
5233}
5234
5235uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
5236{
5237 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005238 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005239 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
5240 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005241 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005242 }
5243 return time;
5244}
5245
5246uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
5247{
5248 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005249 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005250 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
5251 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005252 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005253 }
5254 return time;
5255}
5256
5257void AudioFlinger::DirectOutputThread::cacheParameters_l()
5258{
5259 PlaybackThread::cacheParameters_l();
5260
5261 // use shorter standby delay as on normal output to release
5262 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07005263 // no delay on outputs with HW A/V sync
5264 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005265 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08005266 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005267 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07005268 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005269 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07005270 }
Eric Laurent81784c32012-11-19 14:55:58 -08005271}
5272
Eric Laurente659ef42014-09-29 13:06:46 -07005273void AudioFlinger::DirectOutputThread::flushHw_l()
5274{
Phil Burk062e67a2015-02-11 13:40:50 -08005275 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08005276 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005277 mFlushPending = false;
Eric Laurente659ef42014-09-29 13:06:46 -07005278}
5279
Eric Laurent81784c32012-11-19 14:55:58 -08005280// ----------------------------------------------------------------------------
5281
Eric Laurentbfb1b832013-01-07 09:53:42 -08005282AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07005283 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005284 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07005285 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07005286 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005287 mDrainSequence(0),
5288 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005289{
5290}
5291
5292AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
5293{
5294}
5295
5296void AudioFlinger::AsyncCallbackThread::onFirstRef()
5297{
5298 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
5299}
5300
5301bool AudioFlinger::AsyncCallbackThread::threadLoop()
5302{
5303 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005304 uint32_t writeAckSequence;
5305 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005306 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005307
5308 {
5309 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005310 while (!((mWriteAckSequence & 1) ||
5311 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005312 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005313 exitPending())) {
5314 mWaitWorkCV.wait(mLock);
5315 }
5316
Eric Laurentbfb1b832013-01-07 09:53:42 -08005317 if (exitPending()) {
5318 break;
5319 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005320 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
5321 mWriteAckSequence, mDrainSequence);
5322 writeAckSequence = mWriteAckSequence;
5323 mWriteAckSequence &= ~1;
5324 drainSequence = mDrainSequence;
5325 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005326 asyncError = mAsyncError;
5327 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005328 }
5329 {
Eric Laurent4de95592013-09-26 15:28:21 -07005330 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
5331 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005332 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005333 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005334 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005335 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005336 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005337 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005338 if (asyncError) {
5339 playbackThread->onAsyncError();
5340 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005341 }
5342 }
5343 }
5344 return false;
5345}
5346
5347void AudioFlinger::AsyncCallbackThread::exit()
5348{
5349 ALOGV("AsyncCallbackThread::exit");
5350 Mutex::Autolock _l(mLock);
5351 requestExit();
5352 mWaitWorkCV.broadcast();
5353}
5354
Eric Laurent3b4529e2013-09-05 18:09:19 -07005355void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005356{
5357 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005358 // bit 0 is cleared
5359 mWriteAckSequence = sequence << 1;
5360}
5361
5362void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5363{
5364 Mutex::Autolock _l(mLock);
5365 // ignore unexpected callbacks
5366 if (mWriteAckSequence & 2) {
5367 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005368 mWaitWorkCV.signal();
5369 }
5370}
5371
Eric Laurent3b4529e2013-09-05 18:09:19 -07005372void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005373{
5374 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005375 // bit 0 is cleared
5376 mDrainSequence = sequence << 1;
5377}
5378
5379void AudioFlinger::AsyncCallbackThread::resetDraining()
5380{
5381 Mutex::Autolock _l(mLock);
5382 // ignore unexpected callbacks
5383 if (mDrainSequence & 2) {
5384 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005385 mWaitWorkCV.signal();
5386 }
5387}
5388
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005389void AudioFlinger::AsyncCallbackThread::setAsyncError()
5390{
5391 Mutex::Autolock _l(mLock);
5392 mAsyncError = true;
5393 mWaitWorkCV.signal();
5394}
5395
Eric Laurentbfb1b832013-01-07 09:53:42 -08005396
5397// ----------------------------------------------------------------------------
5398AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07005399 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
5400 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07005401 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
5402 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005403{
Eric Laurentfd477972013-10-25 18:10:40 -07005404 //FIXME: mStandby should be set to true by ThreadBase constructor
5405 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07005406 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005407}
5408
Eric Laurentbfb1b832013-01-07 09:53:42 -08005409void AudioFlinger::OffloadThread::threadLoop_exit()
5410{
5411 if (mFlushPending || mHwPaused) {
5412 // If a flush is pending or track was paused, just discard buffered data
5413 flushHw_l();
5414 } else {
5415 mMixerStatus = MIXER_DRAIN_ALL;
5416 threadLoop_drain();
5417 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005418 if (mUseAsyncWrite) {
5419 ALOG_ASSERT(mCallbackThread != 0);
5420 mCallbackThread->exit();
5421 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005422 PlaybackThread::threadLoop_exit();
5423}
5424
5425AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5426 Vector< sp<Track> > *tracksToRemove
5427)
5428{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005429 size_t count = mActiveTracks.size();
5430
5431 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005432 bool doHwPause = false;
5433 bool doHwResume = false;
5434
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005435 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07005436
Eric Laurentbfb1b832013-01-07 09:53:42 -08005437 // find out which tracks need to be processed
5438 for (size_t i = 0; i < count; i++) {
5439 sp<Track> t = mActiveTracks[i].promote();
5440 // The track died recently
5441 if (t == 0) {
5442 continue;
5443 }
5444 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005445#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08005446 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005447#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005448 // Only consider last track started for volume and mixer state control.
5449 // In theory an older track could underrun and restart after the new one starts
5450 // but as we only care about the transition phase between two tracks on a
5451 // direct output, it is not a problem to ignore the underrun case.
5452 sp<Track> l = mLatestActiveTrack.promote();
5453 bool last = l.get() == track;
5454
Haynes Mathew George7844f672014-01-15 12:32:55 -08005455 if (track->isInvalid()) {
5456 ALOGW("An invalidated track shouldn't be in active list");
5457 tracksToRemove->add(track);
5458 continue;
5459 }
5460
5461 if (track->mState == TrackBase::IDLE) {
5462 ALOGW("An idle track shouldn't be in active list");
5463 continue;
5464 }
5465
Eric Laurentbfb1b832013-01-07 09:53:42 -08005466 if (track->isPausing()) {
5467 track->setPaused();
5468 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005469 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005470 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005471 mHwPaused = true;
5472 }
5473 // If we were part way through writing the mixbuffer to
5474 // the HAL we must save this until we resume
5475 // BUG - this will be wrong if a different track is made active,
5476 // in that case we want to discard the pending data in the
5477 // mixbuffer and tell the client to present it again when the
5478 // track is resumed
5479 mPausedWriteLength = mCurrentWriteLength;
5480 mPausedBytesRemaining = mBytesRemaining;
5481 mBytesRemaining = 0; // stop writing
5482 }
5483 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005484 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005485 if (track->isStopping_1()) {
5486 track->mRetryCount = kMaxTrackStopRetriesOffload;
5487 } else {
5488 track->mRetryCount = kMaxTrackRetriesOffload;
5489 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08005490 track->flushAck();
5491 if (last) {
5492 mFlushPending = true;
5493 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005494 } else if (track->isResumePending()){
5495 track->resumeAck();
5496 if (last) {
5497 if (mPausedBytesRemaining) {
5498 // Need to continue write that was interrupted
5499 mCurrentWriteLength = mPausedWriteLength;
5500 mBytesRemaining = mPausedBytesRemaining;
5501 mPausedBytesRemaining = 0;
5502 }
5503 if (mHwPaused) {
5504 doHwResume = true;
5505 mHwPaused = false;
5506 // threadLoop_mix() will handle the case that we need to
5507 // resume an interrupted write
5508 }
5509 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005510 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005511
Eric Laurent3df841a2016-07-15 15:15:40 -07005512 mLeftVolFloat = mRightVolFloat = -1.0;
5513
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005514 // Do not handle new data in this iteration even if track->framesReady()
5515 mixerStatus = MIXER_TRACKS_ENABLED;
5516 }
5517 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005518 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005519 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005520 if (track->mFillingUpStatus == Track::FS_FILLED) {
5521 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005522 if (last) {
5523 // make sure processVolume_l() will apply new volume even if 0
5524 mLeftVolFloat = mRightVolFloat = -1.0;
5525 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005526 }
5527
5528 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005529 sp<Track> previousTrack = mPreviousTrack.promote();
5530 if (previousTrack != 0) {
5531 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005532 // Flush any data still being written from last track
5533 mBytesRemaining = 0;
5534 if (mPausedBytesRemaining) {
5535 // Last track was paused so we also need to flush saved
5536 // mixbuffer state and invalidate track so that it will
5537 // re-submit that unwritten data when it is next resumed
5538 mPausedBytesRemaining = 0;
5539 // Invalidate is a bit drastic - would be more efficient
5540 // to have a flag to tell client that some of the
5541 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005542 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005543 }
5544 // flush data already sent to the DSP if changing audio session as audio
5545 // comes from a different source. Also invalidate previous track to force a
5546 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005547 if (previousTrack->sessionId() != track->sessionId()) {
5548 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005549 }
5550 }
5551 }
5552 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005553 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07005554 if (track->isStopping_1()) {
5555 track->mRetryCount = kMaxTrackStopRetriesOffload;
5556 } else {
5557 track->mRetryCount = kMaxTrackRetriesOffload;
5558 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005559 mActiveTrack = t;
5560 mixerStatus = MIXER_TRACKS_READY;
5561 }
5562 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005563 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005564 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005565 if (--(track->mRetryCount) <= 0) {
5566 // Hardware buffer can hold a large amount of audio so we must
5567 // wait for all current track's data to drain before we say
5568 // that the track is stopped.
5569 if (mBytesRemaining == 0) {
5570 // Only start draining when all data in mixbuffer
5571 // has been written
5572 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5573 track->mState = TrackBase::STOPPING_2; // so presentation completes after
5574 // drain do not drain if no data was ever sent to HAL (mStandby == true)
5575 if (last && !mStandby) {
5576 // do not modify drain sequence if we are already draining. This happens
5577 // when resuming from pause after drain.
5578 if ((mDrainSequence & 1) == 0) {
5579 mSleepTimeUs = 0;
5580 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
5581 mixerStatus = MIXER_DRAIN_TRACK;
5582 mDrainSequence += 2;
5583 }
5584 if (mHwPaused) {
5585 // It is possible to move from PAUSED to STOPPING_1 without
5586 // a resume so we must ensure hardware is running
5587 doHwResume = true;
5588 mHwPaused = false;
5589 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005590 }
5591 }
Eric Laurente93cc032016-05-05 10:15:10 -07005592 } else if (last) {
5593 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
5594 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005595 }
5596 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005597 // Drain has completed or we are in standby, signal presentation complete
5598 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005599 track->mState = TrackBase::STOPPED;
5600 size_t audioHALFrames =
5601 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005602 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005603 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005604 track->presentationComplete(framesWritten, audioHALFrames);
5605 track->reset();
5606 tracksToRemove->add(track);
5607 }
5608 } else {
5609 // No buffers for this track. Give it a few chances to
5610 // fill a buffer, then remove it from active list.
5611 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07005612 bool running = false;
5613 if (mOutput->stream->get_presentation_position != nullptr) {
5614 uint64_t position = 0;
5615 struct timespec unused;
5616 // The running check restarts the retry counter at least once.
5617 int ret = mOutput->stream->get_presentation_position(
5618 mOutput->stream, &position, &unused);
5619 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
5620 running = true;
5621 mOffloadUnderrunPosition = position;
5622 }
5623 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
5624 (long long)position, (long long)mOffloadUnderrunPosition);
5625 }
5626 if (running) { // still running, give us more time.
5627 track->mRetryCount = kMaxTrackRetriesOffload;
5628 } else {
5629 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5630 track->name());
5631 tracksToRemove->add(track);
5632 // indicate to client process that the track was disabled because of underrun;
5633 // it will then automatically call start() when data is available
5634 track->disable();
5635 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005636 } else if (last){
5637 mixerStatus = MIXER_TRACKS_ENABLED;
5638 }
5639 }
5640 }
5641 // compute volume for this track
5642 processVolume_l(track, last);
5643 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005644
Eric Laurentea0fade2013-10-04 16:23:48 -07005645 // make sure the pause/flush/resume sequence is executed in the right order.
5646 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5647 // before flush and then resume HW. This can happen in case of pause/flush/resume
5648 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07005649 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07005650 mOutput->stream->pause(mOutput->stream);
5651 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005652 if (mFlushPending) {
5653 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005654 }
Eric Laurentfd477972013-10-25 18:10:40 -07005655 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07005656 mOutput->stream->resume(mOutput->stream);
5657 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005658
Eric Laurentbfb1b832013-01-07 09:53:42 -08005659 // remove all the tracks that need to be...
5660 removeTracks_l(*tracksToRemove);
5661
5662 return mixerStatus;
5663}
5664
Eric Laurentbfb1b832013-01-07 09:53:42 -08005665// must be called with thread mutex locked
5666bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5667{
Eric Laurent3b4529e2013-09-05 18:09:19 -07005668 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5669 mWriteAckSequence, mDrainSequence);
5670 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005671 return true;
5672 }
5673 return false;
5674}
5675
Eric Laurentbfb1b832013-01-07 09:53:42 -08005676bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5677{
5678 Mutex::Autolock _l(mLock);
5679 return waitingAsyncCallback_l();
5680}
5681
5682void AudioFlinger::OffloadThread::flushHw_l()
5683{
Eric Laurente659ef42014-09-29 13:06:46 -07005684 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005685 // Flush anything still waiting in the mixbuffer
5686 mCurrentWriteLength = 0;
5687 mBytesRemaining = 0;
5688 mPausedWriteLength = 0;
5689 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07005690 // reset bytes written count to reflect that DSP buffers are empty after flush.
5691 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07005692 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08005693
Eric Laurentbfb1b832013-01-07 09:53:42 -08005694 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005695 // discard any pending drain or write ack by incrementing sequence
5696 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5697 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005698 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005699 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5700 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005701 }
5702}
5703
Haynes Mathew George05317d22016-05-03 16:34:26 -07005704void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
5705{
5706 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07005707 if (PlaybackThread::invalidateTracks_l(streamType)) {
5708 mFlushPending = true;
5709 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07005710}
5711
Eric Laurentbfb1b832013-01-07 09:53:42 -08005712// ----------------------------------------------------------------------------
5713
Eric Laurent81784c32012-11-19 14:55:58 -08005714AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005715 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005716 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07005717 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08005718 mWaitTimeMs(UINT_MAX)
5719{
5720 addOutputTrack(mainThread);
5721}
5722
5723AudioFlinger::DuplicatingThread::~DuplicatingThread()
5724{
5725 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5726 mOutputTracks[i]->destroy();
5727 }
5728}
5729
5730void AudioFlinger::DuplicatingThread::threadLoop_mix()
5731{
5732 // mix buffers...
5733 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08005734 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08005735 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005736 if (mMixerBufferValid) {
5737 memset(mMixerBuffer, 0, mMixerBufferSize);
5738 } else {
5739 memset(mSinkBuffer, 0, mSinkBufferSize);
5740 }
Eric Laurent81784c32012-11-19 14:55:58 -08005741 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005742 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005743 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005744 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005745 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005746}
5747
5748void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5749{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005750 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005751 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005752 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005753 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005754 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005755 }
5756 } else if (mBytesWritten != 0) {
5757 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5758 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005759 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005760 } else {
5761 // flush remaining overflow buffers in output tracks
5762 writeFrames = 0;
5763 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005764 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005765 }
5766}
5767
Eric Laurentbfb1b832013-01-07 09:53:42 -08005768ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005769{
5770 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005771 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005772 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005773 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005774 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005775}
5776
5777void AudioFlinger::DuplicatingThread::threadLoop_standby()
5778{
5779 // DuplicatingThread implements standby by stopping all tracks
5780 for (size_t i = 0; i < outputTracks.size(); i++) {
5781 outputTracks[i]->stop();
5782 }
5783}
5784
5785void AudioFlinger::DuplicatingThread::saveOutputTracks()
5786{
5787 outputTracks = mOutputTracks;
5788}
5789
5790void AudioFlinger::DuplicatingThread::clearOutputTracks()
5791{
5792 outputTracks.clear();
5793}
5794
5795void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5796{
5797 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005798 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5799 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5800 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5801 const size_t frameCount =
5802 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5803 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5804 // from different OutputTracks and their associated MixerThreads (e.g. one may
5805 // nearly empty and the other may be dropping data).
5806
5807 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005808 this,
5809 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005810 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005811 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005812 frameCount,
5813 IPCThreadState::self()->getCallingUid());
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07005814 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
5815 if (status != NO_ERROR) {
5816 ALOGE("addOutputTrack() initCheck failed %d", status);
5817 return;
Eric Laurent81784c32012-11-19 14:55:58 -08005818 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07005819 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
5820 mOutputTracks.add(outputTrack);
5821 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
5822 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005823}
5824
5825void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5826{
5827 Mutex::Autolock _l(mLock);
5828 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5829 if (mOutputTracks[i]->thread() == thread) {
5830 mOutputTracks[i]->destroy();
5831 mOutputTracks.removeAt(i);
5832 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07005833 if (thread->getOutput() == mOutput) {
5834 mOutput = NULL;
5835 }
Eric Laurent81784c32012-11-19 14:55:58 -08005836 return;
5837 }
5838 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07005839 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005840}
5841
5842// caller must hold mLock
5843void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5844{
5845 mWaitTimeMs = UINT_MAX;
5846 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5847 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5848 if (strong != 0) {
5849 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5850 if (waitTimeMs < mWaitTimeMs) {
5851 mWaitTimeMs = waitTimeMs;
5852 }
5853 }
5854 }
5855}
5856
5857
5858bool AudioFlinger::DuplicatingThread::outputsReady(
5859 const SortedVector< sp<OutputTrack> > &outputTracks)
5860{
5861 for (size_t i = 0; i < outputTracks.size(); i++) {
5862 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5863 if (thread == 0) {
5864 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5865 outputTracks[i].get());
5866 return false;
5867 }
5868 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5869 // see note at standby() declaration
5870 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5871 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5872 thread.get());
5873 return false;
5874 }
5875 }
5876 return true;
5877}
5878
5879uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5880{
5881 return (mWaitTimeMs * 1000) / 2;
5882}
5883
5884void AudioFlinger::DuplicatingThread::cacheParameters_l()
5885{
5886 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5887 updateWaitTime_l();
5888
5889 MixerThread::cacheParameters_l();
5890}
5891
5892// ----------------------------------------------------------------------------
5893// Record
5894// ----------------------------------------------------------------------------
5895
5896AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5897 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005898 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005899 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07005900 audio_devices_t inDevice,
5901 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08005902#ifdef TEE_SINK
5903 , const sp<NBAIO_Sink>& teeSink
5904#endif
5905 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07005906 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005907 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005908 // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005909 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005910#ifdef TEE_SINK
5911 , mTeeSink(teeSink)
5912#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005913 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5914 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005915 // mFastCapture below
5916 , mFastCaptureFutex(0)
5917 // mInputSource
5918 // mPipeSink
5919 // mPipeSource
5920 , mPipeFramesP2(0)
5921 // mPipeMemory
5922 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005923 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005924{
Glenn Kastend7dca052015-03-05 16:05:54 -08005925 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5926 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08005927
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005928 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005929
5930 // create an NBAIO source for the HAL input stream, and negotiate
5931 mInputSource = new AudioStreamInSource(input->stream);
5932 size_t numCounterOffers = 0;
5933 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005934#if !LOG_NDEBUG
5935 ssize_t index =
5936#else
5937 (void)
5938#endif
5939 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005940 ALOG_ASSERT(index == 0);
5941
5942 // initialize fast capture depending on configuration
5943 bool initFastCapture;
5944 switch (kUseFastCapture) {
5945 case FastCapture_Never:
5946 initFastCapture = false;
5947 break;
5948 case FastCapture_Always:
5949 initFastCapture = true;
5950 break;
5951 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07005952 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005953 break;
5954 // case FastCapture_Dynamic:
5955 }
5956
5957 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07005958 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005959 NBAIO_Format format = mInputSource->format();
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005960 size_t pipeFramesP2 = roundup(mSampleRate / 25); // double-buffering of 20 ms each
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005961 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5962 void *pipeBuffer;
5963 const sp<MemoryDealer> roHeap(readOnlyHeap());
5964 sp<IMemory> pipeMemory;
5965 if ((roHeap == 0) ||
5966 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5967 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5968 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5969 goto failed;
5970 }
5971 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5972 memset(pipeBuffer, 0, pipeSize);
5973 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5974 const NBAIO_Format offers[1] = {format};
5975 size_t numCounterOffers = 0;
5976 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5977 ALOG_ASSERT(index == 0);
5978 mPipeSink = pipe;
5979 PipeReader *pipeReader = new PipeReader(*pipe);
5980 numCounterOffers = 0;
5981 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5982 ALOG_ASSERT(index == 0);
5983 mPipeSource = pipeReader;
5984 mPipeFramesP2 = pipeFramesP2;
5985 mPipeMemory = pipeMemory;
5986
5987 // create fast capture
5988 mFastCapture = new FastCapture();
5989 FastCaptureStateQueue *sq = mFastCapture->sq();
5990#ifdef STATE_QUEUE_DUMP
5991 // FIXME
5992#endif
5993 FastCaptureState *state = sq->begin();
5994 state->mCblk = NULL;
5995 state->mInputSource = mInputSource.get();
5996 state->mInputSourceGen++;
5997 state->mPipeSink = pipe;
5998 state->mPipeSinkGen++;
5999 state->mFrameCount = mFrameCount;
6000 state->mCommand = FastCaptureState::COLD_IDLE;
6001 // already done in constructor initialization list
6002 //mFastCaptureFutex = 0;
6003 state->mColdFutexAddr = &mFastCaptureFutex;
6004 state->mColdGen++;
6005 state->mDumpState = &mFastCaptureDumpState;
6006#ifdef TEE_SINK
6007 // FIXME
6008#endif
6009 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
6010 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
6011 sq->end();
6012 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6013
6014 // start the fast capture
6015 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
6016 pid_t tid = mFastCapture->getTid();
Glenn Kasten8379b722016-03-18 14:54:17 -07006017 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006018#ifdef AUDIO_WATCHDOG
6019 // FIXME
6020#endif
6021
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006022 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006023 }
6024failed: ;
6025
6026 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08006027}
6028
Eric Laurent81784c32012-11-19 14:55:58 -08006029AudioFlinger::RecordThread::~RecordThread()
6030{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006031 if (mFastCapture != 0) {
6032 FastCaptureStateQueue *sq = mFastCapture->sq();
6033 FastCaptureState *state = sq->begin();
6034 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6035 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6036 if (old == -1) {
6037 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6038 }
6039 }
6040 state->mCommand = FastCaptureState::EXIT;
6041 sq->end();
6042 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6043 mFastCapture->join();
6044 mFastCapture.clear();
6045 }
6046 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07006047 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07006048 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08006049}
6050
6051void AudioFlinger::RecordThread::onFirstRef()
6052{
Glenn Kastend7dca052015-03-05 16:05:54 -08006053 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08006054}
6055
Eric Laurent81784c32012-11-19 14:55:58 -08006056bool AudioFlinger::RecordThread::threadLoop()
6057{
Eric Laurent81784c32012-11-19 14:55:58 -08006058 nsecs_t lastWarning = 0;
6059
6060 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006061
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006062reacquire_wakelock:
6063 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08006064 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006065 {
6066 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006067 size_t size = mActiveTracks.size();
6068 activeTracksGen = mActiveTracksGen;
6069 if (size > 0) {
6070 // FIXME an arbitrary choice
6071 activeTrack = mActiveTracks[0];
6072 acquireWakeLock_l(activeTrack->uid());
6073 if (size > 1) {
6074 SortedVector<int> tmp;
6075 for (size_t i = 0; i < size; i++) {
6076 tmp.add(mActiveTracks[i]->uid());
6077 }
6078 updateWakeLockUids_l(tmp);
6079 }
6080 } else {
6081 acquireWakeLock_l(-1);
6082 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006083 }
6084
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006085 // used to request a deferred sleep, to be executed later while mutex is unlocked
6086 uint32_t sleepUs = 0;
6087
6088 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006089 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006090 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07006091
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006092 // activeTracks accumulates a copy of a subset of mActiveTracks
6093 Vector< sp<RecordTrack> > activeTracks;
6094
Glenn Kasten735f45f2014-08-18 15:51:59 -07006095 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006096 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07006097
Glenn Kasten735f45f2014-08-18 15:51:59 -07006098 // reference to a fast track which is about to be removed
6099 sp<RecordTrack> fastTrackToRemove;
6100
Eric Laurent81784c32012-11-19 14:55:58 -08006101 { // scope for mLock
6102 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08006103
Eric Laurent021cf962014-05-13 10:18:14 -07006104 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006105
Eric Laurent000a4192014-01-29 15:17:32 -08006106 // check exitPending here because checkForNewParameters_l() and
6107 // checkForNewParameters_l() can temporarily release mLock
6108 if (exitPending()) {
6109 break;
6110 }
6111
Eric Laurent5c25d562016-07-13 17:17:45 -07006112 // sleep with mutex unlocked
6113 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07006114 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07006115 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
6116 ATRACE_END();
6117 sleepUs = 0;
6118 continue;
6119 }
6120
Glenn Kasten2b806402013-11-20 16:37:38 -08006121 // if no active track(s), then standby and release wakelock
6122 size_t size = mActiveTracks.size();
6123 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07006124 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006125 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08006126 releaseWakeLock_l();
6127 ALOGV("RecordThread: loop stopping");
6128 // go to sleep
6129 mWaitWorkCV.wait(mLock);
6130 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006131 goto reacquire_wakelock;
6132 }
6133
Glenn Kasten2b806402013-11-20 16:37:38 -08006134 if (mActiveTracksGen != activeTracksGen) {
6135 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006136 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08006137 for (size_t i = 0; i < size; i++) {
6138 tmp.add(mActiveTracks[i]->uid());
6139 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006140 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08006141 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006142
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006143 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07006144 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006145 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07006146
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006147 activeTrack = mActiveTracks[i];
6148 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07006149 if (activeTrack->isFastTrack()) {
6150 ALOG_ASSERT(fastTrackToRemove == 0);
6151 fastTrackToRemove = activeTrack;
6152 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006153 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08006154 mActiveTracks.remove(activeTrack);
6155 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006156 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07006157 continue;
6158 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006159
6160 TrackBase::track_state activeTrackState = activeTrack->mState;
6161 switch (activeTrackState) {
6162
6163 case TrackBase::PAUSING:
6164 mActiveTracks.remove(activeTrack);
6165 mActiveTracksGen++;
6166 doBroadcast = true;
6167 size--;
6168 continue;
6169
6170 case TrackBase::STARTING_1:
6171 sleepUs = 10000;
6172 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07006173 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006174 continue;
6175
6176 case TrackBase::STARTING_2:
6177 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006178 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07006179 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07006180 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006181 break;
6182
6183 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07006184 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006185 break;
6186
6187 case TrackBase::IDLE:
6188 i++;
6189 continue;
6190
6191 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08006192 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07006193 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006194
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006195 activeTracks.add(activeTrack);
6196 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07006197
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006198 if (activeTrack->isFastTrack()) {
6199 ALOG_ASSERT(!mFastTrackAvail);
6200 ALOG_ASSERT(fastTrack == 0);
6201 fastTrack = activeTrack;
6202 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006203 }
Eric Laurent5c25d562016-07-13 17:17:45 -07006204
6205 if (allStopped) {
6206 standbyIfNotAlreadyInStandby();
6207 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006208 if (doBroadcast) {
6209 mStartStopCond.broadcast();
6210 }
6211
6212 // sleep if there are no active tracks to process
6213 if (activeTracks.size() == 0) {
6214 if (sleepUs == 0) {
6215 sleepUs = kRecordThreadSleepUs;
6216 }
6217 continue;
6218 }
6219 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07006220
Eric Laurent81784c32012-11-19 14:55:58 -08006221 lockEffectChains_l(effectChains);
6222 }
6223
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006224 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07006225
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006226 size_t size = effectChains.size();
6227 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006228 // thread mutex is not locked, but effect chain is locked
6229 effectChains[i]->process_l();
6230 }
6231
Glenn Kasten735f45f2014-08-18 15:51:59 -07006232 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006233 if (mFastCapture != 0) {
6234 FastCaptureStateQueue *sq = mFastCapture->sq();
6235 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07006236 bool didModify = false;
6237 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006238 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
6239 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
6240 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6241 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6242 if (old == -1) {
6243 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6244 }
6245 }
6246 state->mCommand = FastCaptureState::READ_WRITE;
6247#if 0 // FIXME
6248 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08006249 FastThreadDumpState::kSamplingNforLowRamDevice :
6250 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006251#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07006252 didModify = true;
6253 }
6254 audio_track_cblk_t *cblkOld = state->mCblk;
6255 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
6256 if (cblkNew != cblkOld) {
6257 state->mCblk = cblkNew;
6258 // block until acked if removing a fast track
6259 if (cblkOld != NULL) {
6260 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
6261 }
6262 didModify = true;
6263 }
6264 sq->end(didModify);
6265 if (didModify) {
6266 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006267#if 0
6268 if (kUseFastCapture == FastCapture_Dynamic) {
6269 mNormalSource = mPipeSource;
6270 }
6271#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006272 }
6273 }
6274
Glenn Kasten735f45f2014-08-18 15:51:59 -07006275 // now run the fast track destructor with thread mutex unlocked
6276 fastTrackToRemove.clear();
6277
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006278 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
6279 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
6280 // slow, then this RecordThread will overrun by not calling HAL read often enough.
6281 // If destination is non-contiguous, first read past the nominal end of buffer, then
6282 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006283
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006284 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006285 ssize_t framesRead;
6286
6287 // If an NBAIO source is present, use it to read the normal capture's data
6288 if (mPipeSource != 0) {
6289 size_t framesToRead = mBufferSize / mFrameSize;
Andy Hung57446612015-04-19 23:56:46 -07006290 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
Glenn Kastend79072e2016-01-06 08:41:20 -08006291 framesToRead);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006292 if (framesRead == 0) {
6293 // since pipe is non-blocking, simulate blocking input
6294 sleepUs = (framesToRead * 1000000LL) / mSampleRate;
6295 }
6296 // otherwise use the HAL / AudioStreamIn directly
6297 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07006298 ATRACE_BEGIN("read");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006299 ssize_t bytesRead = mInput->stream->read(mInput->stream,
Andy Hung57446612015-04-19 23:56:46 -07006300 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize);
Glenn Kastenec6a7032016-03-14 07:40:23 -07006301 ATRACE_END();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006302 if (bytesRead < 0) {
6303 framesRead = bytesRead;
6304 } else {
6305 framesRead = bytesRead / mFrameSize;
6306 }
6307 }
6308
Andy Hung3f0c9022016-01-15 17:49:46 -08006309 // Update server timestamp with server stats
6310 // systemTime() is optional if the hardware supports timestamps.
6311 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
6312 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6313
6314 // Update server timestamp with kernel stats
Andy Hung69ce44d2016-07-18 12:14:25 -07006315 if (mInput->stream->get_capture_position != nullptr
6316 && mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08006317 int64_t position, time;
6318 int ret = mInput->stream->get_capture_position(mInput->stream, &position, &time);
6319 if (ret == NO_ERROR) {
6320 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
6321 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
6322 // Note: In general record buffers should tend to be empty in
6323 // a properly running pipeline.
6324 //
6325 // Also, it is not advantageous to call get_presentation_position during the read
6326 // as the read obtains a lock, preventing the timestamp call from executing.
6327 }
6328 }
6329 // Use this to track timestamp information
6330 // ALOGD("%s", mTimestamp.toString().c_str());
6331
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006332 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006333 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006334 // Force input into standby so that it tries to recover at next read attempt
6335 inputStandBy();
6336 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006337 }
6338 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006339 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006340 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006341 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006342
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006343 if (mTeeSink != 0) {
Andy Hung57446612015-04-19 23:56:46 -07006344 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006345 }
6346 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006347 {
6348 size_t part1 = mRsmpInFramesP2 - rear;
6349 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07006350 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006351 (framesRead - part1) * mFrameSize);
6352 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006353 }
6354 rear = mRsmpInRear += framesRead;
6355
6356 size = activeTracks.size();
6357 // loop over each active track
6358 for (size_t i = 0; i < size; i++) {
6359 activeTrack = activeTracks[i];
6360
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006361 // skip fast tracks, as those are handled directly by FastCapture
6362 if (activeTrack->isFastTrack()) {
6363 continue;
6364 }
6365
Andy Hung73c02e42015-03-29 01:13:58 -07006366 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07006367 // TODO: Update the activeTrack buffer converter in case of reconfigure.
6368
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006369 enum {
6370 OVERRUN_UNKNOWN,
6371 OVERRUN_TRUE,
6372 OVERRUN_FALSE
6373 } overrun = OVERRUN_UNKNOWN;
6374
6375 // loop over getNextBuffer to handle circular sink
6376 for (;;) {
6377
6378 activeTrack->mSink.frameCount = ~0;
6379 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
6380 size_t framesOut = activeTrack->mSink.frameCount;
6381 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
6382
Andy Hung73c02e42015-03-29 01:13:58 -07006383 // check available frames and handle overrun conditions
6384 // if the record track isn't draining fast enough.
6385 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006386 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07006387 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
6388 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006389 overrun = OVERRUN_TRUE;
6390 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006391 if (framesOut == 0 || framesIn == 0) {
6392 break;
6393 }
6394
Andy Hung6770c6f2015-04-07 13:43:36 -07006395 // Don't allow framesOut to be larger than what is possible with resampling
6396 // from framesIn.
6397 // This isn't strictly necessary but helps limit buffer resizing in
6398 // RecordBufferConverter. TODO: remove when no longer needed.
6399 framesOut = min(framesOut,
6400 destinationFramesPossible(
6401 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07006402 // process frames from the RecordThread buffer provider to the RecordTrack buffer
6403 framesOut = activeTrack->mRecordBufferConverter->convert(
6404 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006405
6406 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
6407 overrun = OVERRUN_FALSE;
6408 }
6409
6410 if (activeTrack->mFramesToDrop == 0) {
6411 if (framesOut > 0) {
6412 activeTrack->mSink.frameCount = framesOut;
6413 activeTrack->releaseBuffer(&activeTrack->mSink);
6414 }
6415 } else {
6416 // FIXME could do a partial drop of framesOut
6417 if (activeTrack->mFramesToDrop > 0) {
6418 activeTrack->mFramesToDrop -= framesOut;
6419 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006420 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006421 }
6422 } else {
6423 activeTrack->mFramesToDrop += framesOut;
6424 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
6425 activeTrack->mSyncStartEvent->isCancelled()) {
6426 ALOGW("Synced record %s, session %d, trigger session %d",
6427 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
6428 activeTrack->sessionId(),
6429 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08006430 activeTrack->mSyncStartEvent->triggerSession() :
6431 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006432 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006433 }
6434 }
6435 }
6436
6437 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006438 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006439 }
6440 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006441
6442 switch (overrun) {
6443 case OVERRUN_TRUE:
6444 // client isn't retrieving buffers fast enough
6445 if (!activeTrack->setOverflow()) {
6446 nsecs_t now = systemTime();
6447 // FIXME should lastWarning per track?
6448 if ((now - lastWarning) > kWarningThrottleNs) {
6449 ALOGW("RecordThread: buffer overflow");
6450 lastWarning = now;
6451 }
6452 }
6453 break;
6454 case OVERRUN_FALSE:
6455 activeTrack->clearOverflow();
6456 break;
6457 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006458 break;
6459 }
6460
Andy Hung3f0c9022016-01-15 17:49:46 -08006461 // update frame information and push timestamp out
6462 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08006463 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08006464 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
6465 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006466 }
6467
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006468unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08006469 // enable changes in effect chain
6470 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006471 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08006472 }
6473
Glenn Kasten93e471f2013-08-19 08:40:07 -07006474 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08006475
6476 {
6477 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07006478 for (size_t i = 0; i < mTracks.size(); i++) {
6479 sp<RecordTrack> track = mTracks[i];
6480 track->invalidate();
6481 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006482 mActiveTracks.clear();
6483 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08006484 mStartStopCond.broadcast();
6485 }
6486
6487 releaseWakeLock();
6488
6489 ALOGV("RecordThread %p exiting", this);
6490 return false;
6491}
6492
Glenn Kasten93e471f2013-08-19 08:40:07 -07006493void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08006494{
6495 if (!mStandby) {
6496 inputStandBy();
6497 mStandby = true;
6498 }
6499}
6500
6501void AudioFlinger::RecordThread::inputStandBy()
6502{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006503 // Idle the fast capture if it's currently running
6504 if (mFastCapture != 0) {
6505 FastCaptureStateQueue *sq = mFastCapture->sq();
6506 FastCaptureState *state = sq->begin();
6507 if (!(state->mCommand & FastCaptureState::IDLE)) {
6508 state->mCommand = FastCaptureState::COLD_IDLE;
6509 state->mColdFutexAddr = &mFastCaptureFutex;
6510 state->mColdGen++;
6511 mFastCaptureFutex = 0;
6512 sq->end();
6513 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
6514 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
6515#if 0
6516 if (kUseFastCapture == FastCapture_Dynamic) {
6517 // FIXME
6518 }
6519#endif
6520#ifdef AUDIO_WATCHDOG
6521 // FIXME
6522#endif
6523 } else {
6524 sq->end(false /*didModify*/);
6525 }
6526 }
Eric Laurent81784c32012-11-19 14:55:58 -08006527 mInput->stream->common.standby(&mInput->stream->common);
6528}
6529
Glenn Kasten05997e22014-03-13 15:08:33 -07006530// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07006531sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08006532 const sp<AudioFlinger::Client>& client,
6533 uint32_t sampleRate,
6534 audio_format_t format,
6535 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08006536 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08006537 audio_session_t sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07006538 size_t *notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006539 int uid,
Eric Laurent05067782016-06-01 18:27:28 -07006540 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08006541 pid_t tid,
6542 status_t *status)
6543{
Glenn Kasten74935e42013-12-19 08:56:45 -08006544 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08006545 sp<RecordTrack> track;
6546 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07006547 audio_input_flags_t inputFlags = mInput->flags;
6548
6549 // special case for FAST flag considered OK if fast capture is present
6550 if (hasFastCapture()) {
6551 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
6552 }
6553
6554 // Check if requested flags are compatible with output stream flags
6555 if ((*flags & inputFlags) != *flags) {
6556 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
6557 " input flags (%08x)",
6558 *flags, inputFlags);
6559 *flags = (audio_input_flags_t)(*flags & inputFlags);
6560 }
Eric Laurent81784c32012-11-19 14:55:58 -08006561
Glenn Kasten90e58b12013-07-31 16:16:02 -07006562 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07006563 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006564 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07006565 // we formerly checked for a callback handler (non-0 tid),
6566 // but that is no longer required for TRANSFER_OBTAIN mode
6567 //
Glenn Kasten74105912014-07-03 12:28:53 -07006568 // frame count is not specified, or is exactly the pipe depth
6569 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006570 // PCM data
6571 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006572 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006573 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006574 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006575 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006576 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07006577 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006578 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006579 hasFastCapture() &&
6580 // there are sufficient fast track slots available
6581 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07006582 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07006583 // check compatibility with audio effects.
6584 Mutex::Autolock _l(mLock);
6585 // Do not accept FAST flag if the session has software effects
6586 sp<EffectChain> chain = getEffectChain_l(sessionId);
6587 if (chain != 0) {
Eric Laurent122f7e72016-06-29 11:53:29 -07006588 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_RAW) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07006589 "AUDIO_INPUT_FLAG_RAW denied: effect present on session");
6590 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_RAW);
6591 if (chain->hasSoftwareEffect()) {
6592 ALOGV("AUDIO_INPUT_FLAG_FAST denied: software effect present on session");
6593 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
6594 }
6595 }
Eric Laurent122f7e72016-06-29 11:53:29 -07006596 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07006597 "AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
6598 frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006599 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006600 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
Glenn Kasten74105912014-07-03 12:28:53 -07006601 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006602 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07006603 frameCount, mFrameCount, mPipeFramesP2,
6604 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
6605 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07006606 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07006607 }
6608 }
6609
6610 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07006611 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07006612 // fast track: frame count is exactly the pipe depth
6613 frameCount = mPipeFramesP2;
6614 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
6615 *notificationFrames = mFrameCount;
6616 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006617 // not fast track: max notification period is resampled equivalent of one HAL buffer time
6618 // or 20 ms if there is a fast capture
6619 // TODO This could be a roundupRatio inline, and const
6620 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
6621 * sampleRate + mSampleRate - 1) / mSampleRate;
6622 // minimum number of notification periods is at least kMinNotifications,
6623 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
6624 static const size_t kMinNotifications = 3;
6625 static const uint32_t kMinMs = 30;
6626 // TODO This could be a roundupRatio inline
6627 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
6628 // TODO This could be a roundupRatio inline
6629 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
6630 maxNotificationFrames;
6631 const size_t minFrameCount = maxNotificationFrames *
6632 max(kMinNotifications, minNotificationsByMs);
6633 frameCount = max(frameCount, minFrameCount);
6634 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
6635 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07006636 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07006637 }
Glenn Kasten74935e42013-12-19 08:56:45 -08006638 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07006639
Glenn Kasten15e57982013-09-24 11:52:37 -07006640 lStatus = initCheck();
6641 if (lStatus != NO_ERROR) {
6642 ALOGE("createRecordTrack_l() audio driver not initialized");
6643 goto Exit;
6644 }
Eric Laurent81784c32012-11-19 14:55:58 -08006645
6646 { // scope for mLock
6647 Mutex::Autolock _l(mLock);
6648
6649 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07006650 format, channelMask, frameCount, NULL, sessionId, uid,
6651 *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08006652
Glenn Kasten03003332013-08-06 15:40:54 -07006653 lStatus = track->initCheck();
6654 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07006655 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08006656 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08006657 goto Exit;
6658 }
6659 mTracks.add(track);
6660
6661 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6662 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6663 mAudioFlinger->btNrecIsOff();
6664 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6665 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006666
Eric Laurent05067782016-06-01 18:27:28 -07006667 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006668 pid_t callingPid = IPCThreadState::self()->getCallingPid();
6669 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
6670 // so ask activity manager to do this on our behalf
6671 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
6672 }
Eric Laurent81784c32012-11-19 14:55:58 -08006673 }
Glenn Kasten05997e22014-03-13 15:08:33 -07006674
Eric Laurent81784c32012-11-19 14:55:58 -08006675 lStatus = NO_ERROR;
6676
6677Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07006678 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08006679 return track;
6680}
6681
6682status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6683 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08006684 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08006685{
6686 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6687 sp<ThreadBase> strongMe = this;
6688 status_t status = NO_ERROR;
6689
6690 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006691 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006692 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006693 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08006694 triggerSession,
6695 recordTrack->sessionId(),
6696 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006697 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08006698 // Sync event can be cancelled by the trigger session if the track is not in a
6699 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006700 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006701 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006702 } else {
6703 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006704 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006705 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08006706 }
6707 }
6708
6709 {
Glenn Kasten47c20702013-08-13 15:37:35 -07006710 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08006711 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006712 if (mActiveTracks.indexOf(recordTrack) >= 0) {
6713 if (recordTrack->mState == TrackBase::PAUSING) {
6714 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006715 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006716 } else {
6717 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08006718 }
6719 return status;
6720 }
6721
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006722 // TODO consider other ways of handling this, such as changing the state to :STARTING and
6723 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6724 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006725 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08006726 mActiveTracks.add(recordTrack);
6727 mActiveTracksGen++;
Eric Laurent83b88082014-06-20 18:31:16 -07006728 status_t status = NO_ERROR;
6729 if (recordTrack->isExternalTrack()) {
6730 mLock.unlock();
Glenn Kastend848eb42016-03-08 13:42:11 -08006731 status = AudioSystem::startInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006732 mLock.lock();
6733 // FIXME should verify that recordTrack is still in mActiveTracks
6734 if (status != NO_ERROR) {
6735 mActiveTracks.remove(recordTrack);
6736 mActiveTracksGen++;
6737 recordTrack->clearSyncStartEvent();
6738 ALOGV("RecordThread::start error %d", status);
6739 return status;
6740 }
Eric Laurent81784c32012-11-19 14:55:58 -08006741 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006742 // Catch up with current buffer indices if thread is already running.
6743 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
6744 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6745 // see previously buffered data before it called start(), but with greater risk of overrun.
6746
Andy Hung73c02e42015-03-29 01:13:58 -07006747 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07006748 // clear any converter state as new data will be discontinuous
6749 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006750 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08006751 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08006752 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08006753 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006754 ALOGV("Record failed to start");
6755 status = BAD_VALUE;
6756 goto startError;
6757 }
Eric Laurent81784c32012-11-19 14:55:58 -08006758 return status;
6759 }
Glenn Kasten7c027242012-12-26 14:43:16 -08006760
Eric Laurent81784c32012-11-19 14:55:58 -08006761startError:
Eric Laurent83b88082014-06-20 18:31:16 -07006762 if (recordTrack->isExternalTrack()) {
Glenn Kastend848eb42016-03-08 13:42:11 -08006763 AudioSystem::stopInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006764 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006765 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006766 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08006767 return status;
6768}
6769
Eric Laurent81784c32012-11-19 14:55:58 -08006770void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6771{
6772 sp<SyncEvent> strongEvent = event.promote();
6773
6774 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08006775 sp<RefBase> ptr = strongEvent->cookie().promote();
6776 if (ptr != 0) {
6777 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6778 recordTrack->handleSyncStartEvent(strongEvent);
6779 }
Eric Laurent81784c32012-11-19 14:55:58 -08006780 }
6781}
6782
Glenn Kastena8356f62013-07-25 14:37:52 -07006783bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08006784 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07006785 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006786 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08006787 return false;
6788 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006789 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006790 recordTrack->mState = TrackBase::PAUSING;
Eric Laurent5c25d562016-07-13 17:17:45 -07006791 // signal thread to stop
6792 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08006793 // do not wait for mStartStopCond if exiting
6794 if (exitPending()) {
6795 return true;
6796 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006797 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08006798 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006799 // if we have been restarted, recordTrack is in mActiveTracks here
6800 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006801 ALOGV("Record stopped OK");
6802 return true;
6803 }
6804 return false;
6805}
6806
Glenn Kasten0f11b512014-01-31 16:18:54 -08006807bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08006808{
6809 return false;
6810}
6811
Glenn Kasten0f11b512014-01-31 16:18:54 -08006812status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006813{
6814#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6815 if (!isValidSyncEvent(event)) {
6816 return BAD_VALUE;
6817 }
6818
Glenn Kastend848eb42016-03-08 13:42:11 -08006819 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08006820 status_t ret = NAME_NOT_FOUND;
6821
6822 Mutex::Autolock _l(mLock);
6823
6824 for (size_t i = 0; i < mTracks.size(); i++) {
6825 sp<RecordTrack> track = mTracks[i];
6826 if (eventSession == track->sessionId()) {
6827 (void) track->setSyncEvent(event);
6828 ret = NO_ERROR;
6829 }
6830 }
6831 return ret;
6832#else
6833 return BAD_VALUE;
6834#endif
6835}
6836
6837// destroyTrack_l() must be called with ThreadBase::mLock held
6838void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6839{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006840 track->terminate();
6841 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006842 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006843 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006844 removeTrack_l(track);
6845 }
6846}
6847
6848void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6849{
6850 mTracks.remove(track);
6851 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006852 if (track->isFastTrack()) {
6853 ALOG_ASSERT(!mFastTrackAvail);
6854 mFastTrackAvail = true;
6855 }
Eric Laurent81784c32012-11-19 14:55:58 -08006856}
6857
6858void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6859{
6860 dumpInternals(fd, args);
6861 dumpTracks(fd, args);
6862 dumpEffectChains(fd, args);
6863}
6864
6865void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6866{
Elliott Hughes87cebad2014-05-22 10:14:43 -07006867 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08006868
Glenn Kasten44182c22015-03-05 17:12:23 -08006869 dumpBase(fd, args);
6870
6871 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006872 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006873 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006874 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006875 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08006876
Glenn Kasten2f90c512015-12-02 11:40:09 -08006877 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
6878 // while we are dumping it. It may be inconsistent, but it won't mutate!
6879 // This is a large object so we place it on the heap.
6880 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
6881 const FastCaptureDumpState *copy = new FastCaptureDumpState(mFastCaptureDumpState);
6882 copy->dump(fd);
6883 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08006884}
6885
Glenn Kasten0f11b512014-01-31 16:18:54 -08006886void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006887{
6888 const size_t SIZE = 256;
6889 char buffer[SIZE];
6890 String8 result;
6891
Marco Nelissenb2208842014-02-07 14:00:50 -08006892 size_t numtracks = mTracks.size();
6893 size_t numactive = mActiveTracks.size();
6894 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006895 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006896 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006897 dprintf(fd, " of which %zu are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006898 RecordTrack::appendDumpHeader(result);
6899 for (size_t i = 0; i < numtracks ; ++i) {
6900 sp<RecordTrack> track = mTracks[i];
6901 if (track != 0) {
6902 bool active = mActiveTracks.indexOf(track) >= 0;
6903 if (active) {
6904 numactiveseen++;
6905 }
6906 track->dump(buffer, SIZE, active);
6907 result.append(buffer);
6908 }
Eric Laurent81784c32012-11-19 14:55:58 -08006909 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006910 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006911 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006912 }
6913
Marco Nelissenb2208842014-02-07 14:00:50 -08006914 if (numactiveseen != numactive) {
6915 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6916 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006917 result.append(buffer);
6918 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006919 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006920 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006921 if (mTracks.indexOf(track) < 0) {
6922 track->dump(buffer, SIZE, true);
6923 result.append(buffer);
6924 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006925 }
Eric Laurent81784c32012-11-19 14:55:58 -08006926
6927 }
6928 write(fd, result.string(), result.size());
6929}
6930
Andy Hung73c02e42015-03-29 01:13:58 -07006931
6932void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
6933{
6934 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6935 RecordThread *recordThread = (RecordThread *) threadBase.get();
6936 mRsmpInFront = recordThread->mRsmpInRear;
6937 mRsmpInUnrel = 0;
6938}
6939
6940void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
6941 size_t *framesAvailable, bool *hasOverrun)
6942{
6943 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6944 RecordThread *recordThread = (RecordThread *) threadBase.get();
6945 const int32_t rear = recordThread->mRsmpInRear;
6946 const int32_t front = mRsmpInFront;
6947 const ssize_t filled = rear - front;
6948
6949 size_t framesIn;
6950 bool overrun = false;
6951 if (filled < 0) {
6952 // should not happen, but treat like a massive overrun and re-sync
6953 framesIn = 0;
6954 mRsmpInFront = rear;
6955 overrun = true;
6956 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
6957 framesIn = (size_t) filled;
6958 } else {
6959 // client is not keeping up with server, but give it latest data
6960 framesIn = recordThread->mRsmpInFrames;
6961 mRsmpInFront = /* front = */ rear - framesIn;
6962 overrun = true;
6963 }
6964 if (framesAvailable != NULL) {
6965 *framesAvailable = framesIn;
6966 }
6967 if (hasOverrun != NULL) {
6968 *hasOverrun = overrun;
6969 }
6970}
6971
Eric Laurent81784c32012-11-19 14:55:58 -08006972// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006973status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08006974 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006975{
Andy Hung73c02e42015-03-29 01:13:58 -07006976 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006977 if (threadBase == 0) {
6978 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006979 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006980 return NOT_ENOUGH_DATA;
6981 }
6982 RecordThread *recordThread = (RecordThread *) threadBase.get();
6983 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07006984 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07006985 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006986 // FIXME should not be P2 (don't want to increase latency)
6987 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006988 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07006989 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006990 front &= recordThread->mRsmpInFramesP2 - 1;
6991 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07006992 if (part1 > (size_t) filled) {
6993 part1 = filled;
6994 }
6995 size_t ask = buffer->frameCount;
6996 ALOG_ASSERT(ask > 0);
6997 if (part1 > ask) {
6998 part1 = ask;
6999 }
7000 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07007001 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07007002 buffer->raw = NULL;
7003 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07007004 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07007005 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08007006 }
7007
Andy Hung57446612015-04-19 23:56:46 -07007008 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07007009 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07007010 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08007011 return NO_ERROR;
7012}
7013
7014// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007015void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
7016 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08007017{
Glenn Kasten85948432013-08-19 12:09:05 -07007018 size_t stepCount = buffer->frameCount;
7019 if (stepCount == 0) {
7020 return;
7021 }
Andy Hung73c02e42015-03-29 01:13:58 -07007022 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
7023 mRsmpInUnrel -= stepCount;
7024 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07007025 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08007026 buffer->frameCount = 0;
7027}
7028
Andy Hung97a893e2015-03-29 01:03:07 -07007029AudioFlinger::RecordThread::RecordBufferConverter::RecordBufferConverter(
7030 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
7031 uint32_t srcSampleRate,
7032 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
7033 uint32_t dstSampleRate) :
7034 mSrcChannelMask(AUDIO_CHANNEL_INVALID), // updateParameters will set following vars
7035 // mSrcFormat
7036 // mSrcSampleRate
7037 // mDstChannelMask
7038 // mDstFormat
7039 // mDstSampleRate
7040 // mSrcChannelCount
7041 // mDstChannelCount
7042 // mDstFrameSize
7043 mBuf(NULL), mBufFrames(0), mBufFrameSize(0),
Andy Hungd330ee42015-04-20 13:23:41 -07007044 mResampler(NULL),
7045 mIsLegacyDownmix(false),
7046 mIsLegacyUpmix(false),
7047 mRequiresFloat(false),
7048 mInputConverterProvider(NULL)
Andy Hung97a893e2015-03-29 01:03:07 -07007049{
7050 (void)updateParameters(srcChannelMask, srcFormat, srcSampleRate,
7051 dstChannelMask, dstFormat, dstSampleRate);
7052}
7053
7054AudioFlinger::RecordThread::RecordBufferConverter::~RecordBufferConverter() {
7055 free(mBuf);
7056 delete mResampler;
Andy Hungd330ee42015-04-20 13:23:41 -07007057 delete mInputConverterProvider;
Andy Hung97a893e2015-03-29 01:03:07 -07007058}
7059
7060size_t AudioFlinger::RecordThread::RecordBufferConverter::convert(void *dst,
7061 AudioBufferProvider *provider, size_t frames)
7062{
Andy Hungd330ee42015-04-20 13:23:41 -07007063 if (mInputConverterProvider != NULL) {
7064 mInputConverterProvider->setBufferProvider(provider);
7065 provider = mInputConverterProvider;
7066 }
7067
7068 if (mResampler == NULL) {
Andy Hung97a893e2015-03-29 01:03:07 -07007069 ALOGVV("NO RESAMPLING sampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
7070 mSrcSampleRate, mSrcFormat, mDstFormat);
7071
7072 AudioBufferProvider::Buffer buffer;
7073 for (size_t i = frames; i > 0; ) {
7074 buffer.frameCount = i;
Glenn Kastend79072e2016-01-06 08:41:20 -08007075 status_t status = provider->getNextBuffer(&buffer);
Andy Hung97a893e2015-03-29 01:03:07 -07007076 if (status != OK || buffer.frameCount == 0) {
7077 frames -= i; // cannot fill request.
7078 break;
7079 }
Andy Hungd330ee42015-04-20 13:23:41 -07007080 // format convert to destination buffer
7081 convertNoResampler(dst, buffer.raw, buffer.frameCount);
Andy Hung97a893e2015-03-29 01:03:07 -07007082
7083 dst = (int8_t*)dst + buffer.frameCount * mDstFrameSize;
7084 i -= buffer.frameCount;
7085 provider->releaseBuffer(&buffer);
7086 }
7087 } else {
7088 ALOGVV("RESAMPLING mSrcSampleRate:%u mDstSampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
7089 mSrcSampleRate, mDstSampleRate, mSrcFormat, mDstFormat);
7090
Andy Hungd330ee42015-04-20 13:23:41 -07007091 // reallocate buffer if needed
7092 if (mBufFrameSize != 0 && mBufFrames < frames) {
7093 free(mBuf);
7094 mBufFrames = frames;
7095 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
7096 }
Andy Hung97a893e2015-03-29 01:03:07 -07007097 // resampler accumulates, but we only have one source track
Andy Hungd330ee42015-04-20 13:23:41 -07007098 memset(mBuf, 0, frames * mBufFrameSize);
7099 frames = mResampler->resample((int32_t*)mBuf, frames, provider);
7100 // format convert to destination buffer
7101 convertResampler(dst, mBuf, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07007102 }
7103 return frames;
7104}
7105
7106status_t AudioFlinger::RecordThread::RecordBufferConverter::updateParameters(
7107 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
7108 uint32_t srcSampleRate,
7109 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
7110 uint32_t dstSampleRate)
7111{
7112 // quick evaluation if there is any change.
7113 if (mSrcFormat == srcFormat
7114 && mSrcChannelMask == srcChannelMask
7115 && mSrcSampleRate == srcSampleRate
7116 && mDstFormat == dstFormat
7117 && mDstChannelMask == dstChannelMask
7118 && mDstSampleRate == dstSampleRate) {
7119 return NO_ERROR;
7120 }
7121
Andy Hungdb4c0312015-05-06 08:46:52 -07007122 ALOGV("RecordBufferConverter updateParameters srcMask:%#x dstMask:%#x"
7123 " srcFormat:%#x dstFormat:%#x srcRate:%u dstRate:%u",
7124 srcChannelMask, dstChannelMask, srcFormat, dstFormat, srcSampleRate, dstSampleRate);
Andy Hung97a893e2015-03-29 01:03:07 -07007125 const bool valid =
7126 audio_is_input_channel(srcChannelMask)
7127 && audio_is_input_channel(dstChannelMask)
7128 && audio_is_valid_format(srcFormat) && audio_is_linear_pcm(srcFormat)
7129 && audio_is_valid_format(dstFormat) && audio_is_linear_pcm(dstFormat)
7130 && (srcSampleRate <= dstSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX)
7131 ; // no upsampling checks for now
7132 if (!valid) {
7133 return BAD_VALUE;
7134 }
7135
7136 mSrcFormat = srcFormat;
7137 mSrcChannelMask = srcChannelMask;
7138 mSrcSampleRate = srcSampleRate;
7139 mDstFormat = dstFormat;
7140 mDstChannelMask = dstChannelMask;
7141 mDstSampleRate = dstSampleRate;
7142
7143 // compute derived parameters
7144 mSrcChannelCount = audio_channel_count_from_in_mask(srcChannelMask);
7145 mDstChannelCount = audio_channel_count_from_in_mask(dstChannelMask);
7146 mDstFrameSize = mDstChannelCount * audio_bytes_per_sample(mDstFormat);
7147
Andy Hungd330ee42015-04-20 13:23:41 -07007148 // do we need to resample?
7149 delete mResampler;
7150 mResampler = NULL;
7151 if (mSrcSampleRate != mDstSampleRate) {
7152 mResampler = AudioResampler::create(AUDIO_FORMAT_PCM_FLOAT,
7153 mSrcChannelCount, mDstSampleRate);
7154 mResampler->setSampleRate(mSrcSampleRate);
7155 mResampler->setVolume(AudioMixer::UNITY_GAIN_FLOAT, AudioMixer::UNITY_GAIN_FLOAT);
7156 }
7157
7158 // are we running legacy channel conversion modes?
7159 mIsLegacyDownmix = (mSrcChannelMask == AUDIO_CHANNEL_IN_STEREO
7160 || mSrcChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK)
7161 && mDstChannelMask == AUDIO_CHANNEL_IN_MONO;
7162 mIsLegacyUpmix = mSrcChannelMask == AUDIO_CHANNEL_IN_MONO
7163 && (mDstChannelMask == AUDIO_CHANNEL_IN_STEREO
7164 || mDstChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK);
7165
7166 // do we need to process in float?
7167 mRequiresFloat = mResampler != NULL || mIsLegacyDownmix || mIsLegacyUpmix;
7168
7169 // do we need a staging buffer to convert for destination (we can still optimize this)?
7170 // we use mBufFrameSize > 0 to indicate both frame size as well as buffer necessity
7171 if (mResampler != NULL) {
7172 mBufFrameSize = max(mSrcChannelCount, FCC_2)
7173 * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
Andy Hunga97630b2015-07-22 23:27:24 -07007174 } else if (mIsLegacyUpmix || mIsLegacyDownmix) { // legacy modes always float
Andy Hungd330ee42015-04-20 13:23:41 -07007175 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
7176 } else if (mSrcChannelMask != mDstChannelMask && mDstFormat != mSrcFormat) {
Andy Hung97a893e2015-03-29 01:03:07 -07007177 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(mSrcFormat);
7178 } else {
7179 mBufFrameSize = 0;
7180 }
7181 mBufFrames = 0; // force the buffer to be resized.
7182
Andy Hungd330ee42015-04-20 13:23:41 -07007183 // do we need an input converter buffer provider to give us float?
7184 delete mInputConverterProvider;
7185 mInputConverterProvider = NULL;
7186 if (mRequiresFloat && mSrcFormat != AUDIO_FORMAT_PCM_FLOAT) {
7187 mInputConverterProvider = new ReformatBufferProvider(
7188 audio_channel_count_from_in_mask(mSrcChannelMask),
7189 mSrcFormat,
7190 AUDIO_FORMAT_PCM_FLOAT,
7191 256 /* provider buffer frame count */);
7192 }
7193
7194 // do we need a remixer to do channel mask conversion
7195 if (!mIsLegacyDownmix && !mIsLegacyUpmix && mSrcChannelMask != mDstChannelMask) {
7196 (void) memcpy_by_index_array_initialization_from_channel_mask(
7197 mIdxAry, ARRAY_SIZE(mIdxAry), mDstChannelMask, mSrcChannelMask);
Andy Hung97a893e2015-03-29 01:03:07 -07007198 }
7199 return NO_ERROR;
7200}
7201
Andy Hungd330ee42015-04-20 13:23:41 -07007202void AudioFlinger::RecordThread::RecordBufferConverter::convertNoResampler(
7203 void *dst, const void *src, size_t frames)
Andy Hung97a893e2015-03-29 01:03:07 -07007204{
Andy Hungd330ee42015-04-20 13:23:41 -07007205 // src is native type unless there is legacy upmix or downmix, whereupon it is float.
Andy Hung97a893e2015-03-29 01:03:07 -07007206 if (mBufFrameSize != 0 && mBufFrames < frames) {
7207 free(mBuf);
7208 mBufFrames = frames;
7209 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
7210 }
Andy Hungd330ee42015-04-20 13:23:41 -07007211 // do we need to do legacy upmix and downmix?
7212 if (mIsLegacyUpmix || mIsLegacyDownmix) {
Andy Hung97a893e2015-03-29 01:03:07 -07007213 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07007214 if (mIsLegacyUpmix) {
7215 upmix_to_stereo_float_from_mono_float((float *)dstBuf,
7216 (const float *)src, frames);
7217 } else /*mIsLegacyDownmix */ {
7218 downmix_to_mono_float_from_stereo_float((float *)dstBuf,
7219 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07007220 }
Andy Hungd330ee42015-04-20 13:23:41 -07007221 if (mBuf != NULL) {
7222 memcpy_by_audio_format(dst, mDstFormat, mBuf, AUDIO_FORMAT_PCM_FLOAT,
7223 frames * mDstChannelCount);
7224 }
7225 return;
7226 }
7227 // do we need to do channel mask conversion?
7228 if (mSrcChannelMask != mDstChannelMask) {
Andy Hung97a893e2015-03-29 01:03:07 -07007229 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07007230 memcpy_by_index_array(dstBuf, mDstChannelCount,
7231 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mSrcFormat), frames);
7232 if (dstBuf == dst) {
7233 return; // format is the same
7234 }
7235 }
7236 // convert to destination buffer
7237 const void *convertBuf = mBuf != NULL ? mBuf : src;
7238 memcpy_by_audio_format(dst, mDstFormat, convertBuf, mSrcFormat,
7239 frames * mDstChannelCount);
7240}
7241
7242void AudioFlinger::RecordThread::RecordBufferConverter::convertResampler(
7243 void *dst, /*not-a-const*/ void *src, size_t frames)
7244{
7245 // src buffer format is ALWAYS float when entering this routine
7246 if (mIsLegacyUpmix) {
7247 ; // mono to stereo already handled by resampler
7248 } else if (mIsLegacyDownmix
7249 || (mSrcChannelMask == mDstChannelMask && mSrcChannelCount == 1)) {
7250 // the resampler outputs stereo for mono input channel (a feature?)
7251 // must convert to mono
7252 downmix_to_mono_float_from_stereo_float((float *)src,
7253 (const float *)src, frames);
7254 } else if (mSrcChannelMask != mDstChannelMask) {
7255 // convert to mono channel again for channel mask conversion (could be skipped
7256 // with further optimization).
Andy Hung97a893e2015-03-29 01:03:07 -07007257 if (mSrcChannelCount == 1) {
Andy Hungd330ee42015-04-20 13:23:41 -07007258 downmix_to_mono_float_from_stereo_float((float *)src,
7259 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07007260 }
Andy Hungd330ee42015-04-20 13:23:41 -07007261 // convert to destination format (in place, OK as float is larger than other types)
7262 if (mDstFormat != AUDIO_FORMAT_PCM_FLOAT) {
7263 memcpy_by_audio_format(src, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
7264 frames * mSrcChannelCount);
7265 }
7266 // channel convert and save to dst
7267 memcpy_by_index_array(dst, mDstChannelCount,
7268 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mDstFormat), frames);
7269 return;
Andy Hung97a893e2015-03-29 01:03:07 -07007270 }
Andy Hungd330ee42015-04-20 13:23:41 -07007271 // convert to destination format and save to dst
7272 memcpy_by_audio_format(dst, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
7273 frames * mDstChannelCount);
Andy Hung97a893e2015-03-29 01:03:07 -07007274}
7275
Eric Laurent10351942014-05-08 18:49:52 -07007276bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
7277 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007278{
7279 bool reconfig = false;
7280
Eric Laurent10351942014-05-08 18:49:52 -07007281 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007282
Eric Laurent10351942014-05-08 18:49:52 -07007283 audio_format_t reqFormat = mFormat;
7284 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07007285 // 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 -07007286 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
7287
7288 AudioParameter param = AudioParameter(keyValuePair);
7289 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07007290
7291 // scope for AutoPark extends to end of method
7292 AutoPark<FastCapture> park(mFastCapture);
7293
Eric Laurent10351942014-05-08 18:49:52 -07007294 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
7295 // channel count change can be requested. Do we mandate the first client defines the
7296 // HAL sampling rate and channel count or do we allow changes on the fly?
7297 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
7298 samplingRate = value;
7299 reconfig = true;
7300 }
7301 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07007302 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07007303 status = BAD_VALUE;
7304 } else {
7305 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08007306 reconfig = true;
7307 }
Eric Laurent10351942014-05-08 18:49:52 -07007308 }
7309 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
7310 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07007311 if (!audio_is_input_channel(mask) ||
7312 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007313 status = BAD_VALUE;
7314 } else {
7315 channelMask = mask;
7316 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007317 }
Eric Laurent10351942014-05-08 18:49:52 -07007318 }
7319 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7320 // do not accept frame count changes if tracks are open as the track buffer
7321 // size depends on frame count and correct behavior would not be guaranteed
7322 // if frame count is changed after track creation
7323 if (mActiveTracks.size() > 0) {
7324 status = INVALID_OPERATION;
7325 } else {
7326 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007327 }
Eric Laurent10351942014-05-08 18:49:52 -07007328 }
7329 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7330 // forward device change to effects that have requested to be
7331 // aware of attached audio device.
7332 for (size_t i = 0; i < mEffectChains.size(); i++) {
7333 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08007334 }
Eric Laurent81784c32012-11-19 14:55:58 -08007335
Eric Laurent10351942014-05-08 18:49:52 -07007336 // store input device and output device but do not forward output device to audio HAL.
7337 // Note that status is ignored by the caller for output device
7338 // (see AudioFlinger::setParameters()
7339 if (audio_is_output_devices(value)) {
7340 mOutDevice = value;
7341 status = BAD_VALUE;
7342 } else {
7343 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07007344 if (value != AUDIO_DEVICE_NONE) {
7345 mPrevInDevice = value;
7346 }
Eric Laurent10351942014-05-08 18:49:52 -07007347 // disable AEC and NS if the device is a BT SCO headset supporting those
7348 // pre processings
7349 if (mTracks.size() > 0) {
7350 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7351 mAudioFlinger->btNrecIsOff();
7352 for (size_t i = 0; i < mTracks.size(); i++) {
7353 sp<RecordTrack> track = mTracks[i];
7354 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7355 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08007356 }
7357 }
7358 }
Eric Laurent10351942014-05-08 18:49:52 -07007359 }
7360 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
7361 mAudioSource != (audio_source_t)value) {
7362 // forward device change to effects that have requested to be
7363 // aware of attached audio device.
7364 for (size_t i = 0; i < mEffectChains.size(); i++) {
7365 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08007366 }
Eric Laurent10351942014-05-08 18:49:52 -07007367 mAudioSource = (audio_source_t)value;
7368 }
Glenn Kastene198c362013-08-13 09:13:36 -07007369
Eric Laurent10351942014-05-08 18:49:52 -07007370 if (status == NO_ERROR) {
7371 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7372 keyValuePair.string());
7373 if (status == INVALID_OPERATION) {
7374 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08007375 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7376 keyValuePair.string());
Eric Laurent10351942014-05-08 18:49:52 -07007377 }
7378 if (reconfig) {
7379 if (status == BAD_VALUE &&
Andy Hung97a893e2015-03-29 01:03:07 -07007380 audio_is_linear_pcm(mInput->stream->common.get_format(&mInput->stream->common)) &&
7381 audio_is_linear_pcm(reqFormat) &&
Eric Laurent10351942014-05-08 18:49:52 -07007382 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
Andy Hung97a893e2015-03-29 01:03:07 -07007383 <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate)) &&
Andy Hunge5412692014-05-16 11:25:07 -07007384 audio_channel_count_from_in_mask(
Andy Hungd1abb8f2015-05-05 23:42:34 -07007385 mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007386 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007387 }
Eric Laurent10351942014-05-08 18:49:52 -07007388 if (status == NO_ERROR) {
7389 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007390 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08007391 }
7392 }
Eric Laurent81784c32012-11-19 14:55:58 -08007393 }
Eric Laurent10351942014-05-08 18:49:52 -07007394
Eric Laurent81784c32012-11-19 14:55:58 -08007395 return reconfig;
7396}
7397
7398String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
7399{
Eric Laurent81784c32012-11-19 14:55:58 -08007400 Mutex::Autolock _l(mLock);
7401 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07007402 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08007403 }
7404
Glenn Kastend8ea6992013-07-16 14:17:15 -07007405 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
7406 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08007407 free(s);
7408 return out_s8;
7409}
7410
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007411void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007412 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7413
7414 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08007415
7416 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007417 case AUDIO_INPUT_OPENED:
7418 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07007419 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07007420 desc->mChannelMask = mChannelMask;
7421 desc->mSamplingRate = mSampleRate;
7422 desc->mFormat = mFormat;
7423 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07007424 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07007425 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007426 break;
7427
Eric Laurent73e26b62015-04-27 16:55:58 -07007428 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08007429 default:
7430 break;
7431 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007432 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08007433}
7434
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007435void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007436{
Eric Laurent81784c32012-11-19 14:55:58 -08007437 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
7438 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Andy Hunge5412692014-05-16 11:25:07 -07007439 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Andy Hungd330ee42015-04-20 13:23:41 -07007440 if (mChannelCount > FCC_8) {
7441 ALOGE("HAL channel count %d > %d", mChannelCount, FCC_8);
7442 }
Andy Hung463be252014-07-10 16:56:07 -07007443 mHALFormat = mInput->stream->common.get_format(&mInput->stream->common);
7444 mFormat = mHALFormat;
Andy Hungd330ee42015-04-20 13:23:41 -07007445 if (!audio_is_linear_pcm(mFormat)) {
7446 ALOGE("HAL format %#x is not linear pcm", mFormat);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07007447 }
Eric Laurent665470b2014-07-03 16:37:08 -07007448 mFrameSize = audio_stream_in_frame_size(mInput->stream);
Glenn Kasten548efc92012-11-29 08:48:51 -08007449 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
7450 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007451 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08007452 // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
Glenn Kasten85948432013-08-19 12:09:05 -07007453 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08007454 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007455 // A larger value should allow more old data to be read after a track calls start(),
7456 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07007457 //
7458 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08007459 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07007460 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07007461 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07007462 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007463
7464 // TODO optimize audio capture buffer sizes ...
7465 // Here we calculate the size of the sliding buffer used as a source
7466 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
7467 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
7468 // be better to have it derived from the pipe depth in the long term.
7469 // The current value is higher than necessary. However it should not add to latency.
7470
Glenn Kasten85948432013-08-19 12:09:05 -07007471 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Andy Hung0a01c2f2015-09-21 12:44:54 -07007472 size_t bufferSize = (mRsmpInFramesP2 + mFrameCount - 1) * mFrameSize;
7473 (void)posix_memalign(&mRsmpInBuffer, 32, bufferSize);
7474 memset(mRsmpInBuffer, 0, bufferSize); // if posix_memalign fails, will segv here.
Eric Laurent81784c32012-11-19 14:55:58 -08007475
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007476 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
7477 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08007478}
7479
Glenn Kasten5f972c02014-01-13 09:59:31 -08007480uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08007481{
7482 Mutex::Autolock _l(mLock);
7483 if (initCheck() != NO_ERROR) {
7484 return 0;
7485 }
7486
7487 return mInput->stream->get_input_frames_lost(mInput->stream);
7488}
7489
Eric Laurent4c415062016-06-17 16:14:16 -07007490// hasAudioSession_l() must be called with ThreadBase::mLock held
7491uint32_t AudioFlinger::RecordThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08007492{
Eric Laurent81784c32012-11-19 14:55:58 -08007493 uint32_t result = 0;
7494 if (getEffectChain_l(sessionId) != 0) {
7495 result = EFFECT_SESSION;
7496 }
7497
7498 for (size_t i = 0; i < mTracks.size(); ++i) {
7499 if (sessionId == mTracks[i]->sessionId()) {
7500 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07007501 if (mTracks[i]->isFastTrack()) {
7502 result |= FAST_SESSION;
7503 }
Eric Laurent81784c32012-11-19 14:55:58 -08007504 break;
7505 }
7506 }
7507
7508 return result;
7509}
7510
Glenn Kastend848eb42016-03-08 13:42:11 -08007511KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08007512{
Glenn Kastend848eb42016-03-08 13:42:11 -08007513 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08007514 Mutex::Autolock _l(mLock);
7515 for (size_t j = 0; j < mTracks.size(); ++j) {
7516 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08007517 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08007518 if (ids.indexOfKey(sessionId) < 0) {
7519 ids.add(sessionId, true);
7520 }
7521 }
7522 return ids;
7523}
7524
7525AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7526{
7527 Mutex::Autolock _l(mLock);
7528 AudioStreamIn *input = mInput;
7529 mInput = NULL;
7530 return input;
7531}
7532
7533// this method must always be called either with ThreadBase mLock held or inside the thread loop
7534audio_stream_t* AudioFlinger::RecordThread::stream() const
7535{
7536 if (mInput == NULL) {
7537 return NULL;
7538 }
7539 return &mInput->stream->common;
7540}
7541
7542status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7543{
7544 // only one chain per input thread
7545 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07007546 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08007547 return INVALID_OPERATION;
7548 }
7549 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07007550 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08007551 chain->setInBuffer(NULL);
7552 chain->setOutBuffer(NULL);
7553
7554 checkSuspendOnAddEffectChain_l(chain);
7555
Eric Laurent1b928682014-10-02 19:41:47 -07007556 // make sure enabled pre processing effects state is communicated to the HAL as we
7557 // just moved them to a new input stream.
7558 chain->syncHalEffectsState();
7559
Eric Laurent81784c32012-11-19 14:55:58 -08007560 mEffectChains.add(chain);
7561
7562 return NO_ERROR;
7563}
7564
7565size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7566{
7567 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7568 ALOGW_IF(mEffectChains.size() != 1,
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007569 "removeEffectChain_l() %p invalid chain size %zu on thread %p",
Eric Laurent81784c32012-11-19 14:55:58 -08007570 chain.get(), mEffectChains.size(), this);
7571 if (mEffectChains.size() == 1) {
7572 mEffectChains.removeAt(0);
7573 }
7574 return 0;
7575}
7576
Eric Laurent1c333e22014-05-20 10:48:17 -07007577status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7578 audio_patch_handle_t *handle)
7579{
7580 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007581
7582 // store new device and send to effects
7583 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07007584 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07007585 for (size_t i = 0; i < mEffectChains.size(); i++) {
7586 mEffectChains[i]->setDevice_l(mInDevice);
7587 }
7588
7589 // disable AEC and NS if the device is a BT SCO headset supporting those
7590 // pre processings
7591 if (mTracks.size() > 0) {
7592 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7593 mAudioFlinger->btNrecIsOff();
7594 for (size_t i = 0; i < mTracks.size(); i++) {
7595 sp<RecordTrack> track = mTracks[i];
7596 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7597 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
7598 }
7599 }
7600
7601 // store new source and send to effects
7602 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7603 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07007604 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07007605 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07007606 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007607 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007608
Eric Laurent054d9d32015-04-24 08:48:48 -07007609 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007610 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
7611 status = hwDevice->create_audio_patch(hwDevice,
7612 patch->num_sources,
7613 patch->sources,
7614 patch->num_sinks,
7615 patch->sinks,
7616 handle);
7617 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007618 char *address;
7619 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7620 address = audio_device_address_to_parameter(
7621 patch->sources[0].ext.device.type,
7622 patch->sources[0].ext.device.address);
7623 } else {
7624 address = (char *)calloc(1, 1);
7625 }
7626 AudioParameter param = AudioParameter(String8(address));
7627 free(address);
7628 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING),
7629 (int)patch->sources[0].ext.device.type);
7630 param.addInt(String8(AUDIO_PARAMETER_STREAM_INPUT_SOURCE),
7631 (int)patch->sinks[0].ext.mix.usecase.source);
7632 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7633 param.toString().string());
7634 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07007635 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007636
Eric Laurente8726fe2015-06-26 09:39:24 -07007637 if (mInDevice != mPrevInDevice) {
7638 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7639 mPrevInDevice = mInDevice;
7640 }
Eric Laurent296fb132015-05-01 11:38:42 -07007641
Eric Laurent1c333e22014-05-20 10:48:17 -07007642 return status;
7643}
7644
7645status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7646{
7647 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007648
7649 mInDevice = AUDIO_DEVICE_NONE;
7650
Eric Laurent1c333e22014-05-20 10:48:17 -07007651 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
7652 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
7653 status = hwDevice->release_audio_patch(hwDevice, handle);
7654 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007655 AudioParameter param;
7656 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
7657 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7658 param.toString().string());
Eric Laurent1c333e22014-05-20 10:48:17 -07007659 }
7660 return status;
7661}
7662
Eric Laurent83b88082014-06-20 18:31:16 -07007663void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
7664{
7665 Mutex::Autolock _l(mLock);
7666 mTracks.add(record);
7667}
7668
7669void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
7670{
7671 Mutex::Autolock _l(mLock);
7672 destroyTrack_l(record);
7673}
7674
7675void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
7676{
7677 ThreadBase::getAudioPortConfig(config);
7678 config->role = AUDIO_PORT_ROLE_SINK;
7679 config->ext.mix.hw_module = mInput->audioHwDev->handle();
7680 config->ext.mix.usecase.source = mAudioSource;
7681}
Eric Laurent1c333e22014-05-20 10:48:17 -07007682
Glenn Kasten63238ef2015-03-02 15:50:29 -08007683} // namespace android