blob: 14a7b8bbe3eeb85a0dcfb2f74ef9096b65cb8760 [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);
Andy Hung1f82f952016-11-28 19:01:02 -08001740 mLocalLog.dump(fd, args, " " /* prefix */);
Eric Laurent81784c32012-11-19 14:55:58 -08001741}
1742
Glenn Kasten0f11b512014-01-31 16:18:54 -08001743void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001744{
1745 const size_t SIZE = 256;
1746 char buffer[SIZE];
1747 String8 result;
1748
Marco Nelissenb2208842014-02-07 14:00:50 -08001749 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001750 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1751 const stream_type_t *st = &mStreamTypes[i];
1752 if (i > 0) {
1753 result.appendFormat(", ");
1754 }
1755 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1756 if (st->mute) {
1757 result.append("M");
1758 }
1759 }
1760 result.append("\n");
1761 write(fd, result.string(), result.length());
1762 result.clear();
1763
Eric Laurent81784c32012-11-19 14:55:58 -08001764 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1765 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001766 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001767 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001768
1769 size_t numtracks = mTracks.size();
1770 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001771 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001772 size_t numactiveseen = 0;
1773 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001774 dprintf(fd, " of which %zu are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001775 Track::appendDumpHeader(result);
1776 for (size_t i = 0; i < numtracks; ++i) {
1777 sp<Track> track = mTracks[i];
1778 if (track != 0) {
1779 bool active = mActiveTracks.indexOf(track) >= 0;
1780 if (active) {
1781 numactiveseen++;
1782 }
1783 track->dump(buffer, SIZE, active);
1784 result.append(buffer);
1785 }
1786 }
1787 } else {
1788 result.append("\n");
1789 }
1790 if (numactiveseen != numactive) {
1791 // some tracks in the active list were not in the tracks list
1792 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1793 " not in the track list\n");
1794 result.append(buffer);
1795 Track::appendDumpHeader(result);
1796 for (size_t i = 0; i < numactive; ++i) {
1797 sp<Track> track = mActiveTracks[i].promote();
1798 if (track != 0 && mTracks.indexOf(track) < 0) {
1799 track->dump(buffer, SIZE, true);
1800 result.append(buffer);
1801 }
1802 }
1803 }
1804
1805 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001806}
1807
1808void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1809{
Glenn Kasten97b7b752014-09-28 13:04:24 -07001810 dprintf(fd, "\nOutput thread %p type %d (%s):\n", this, type(), threadTypeToString(type()));
Glenn Kasten44182c22015-03-05 17:12:23 -08001811
1812 dumpBase(fd, args);
1813
Elliott Hughes87cebad2014-05-22 10:14:43 -07001814 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001815 dprintf(fd, " Last write occurred (msecs): %llu\n",
1816 (unsigned long long) ns2ms(systemTime() - mLastWriteTime));
Elliott Hughes87cebad2014-05-22 10:14:43 -07001817 dprintf(fd, " Total writes: %d\n", mNumWrites);
1818 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1819 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1820 dprintf(fd, " Suspend count: %d\n", mSuspended);
1821 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1822 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1823 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1824 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08001825 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001826 AudioStreamOut *output = mOutput;
1827 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
1828 String8 flagsAsString = outputFlagsToString(flags);
1829 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n", output, flags, flagsAsString.string());
Andy Hung2c453932016-09-21 12:55:15 -07001830 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
1831 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
1832 if (mPipeSink.get() != nullptr) {
1833 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
1834 }
1835 if (output != nullptr) {
1836 dprintf(fd, " Hal stream dump:\n");
1837 (void)output->stream->common.dump(&output->stream->common, fd);
1838 }
Eric Laurent81784c32012-11-19 14:55:58 -08001839}
1840
1841// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001842
1843void AudioFlinger::PlaybackThread::onFirstRef()
1844{
Glenn Kastend7dca052015-03-05 16:05:54 -08001845 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001846}
1847
1848// ThreadBase virtuals
1849void AudioFlinger::PlaybackThread::preExit()
1850{
1851 ALOGV(" preExit()");
1852 // FIXME this is using hard-coded strings but in the future, this functionality will be
1853 // converted to use audio HAL extensions required to support tunneling
1854 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1855}
1856
1857// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1858sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1859 const sp<AudioFlinger::Client>& client,
1860 audio_stream_type_t streamType,
1861 uint32_t sampleRate,
1862 audio_format_t format,
1863 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001864 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001865 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08001866 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07001867 audio_output_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08001868 pid_t tid,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001869 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -08001870 status_t *status)
1871{
Glenn Kasten74935e42013-12-19 08:56:45 -08001872 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001873 sp<Track> track;
1874 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07001875 audio_output_flags_t outputFlags = mOutput->flags;
1876
1877 // special case for FAST flag considered OK if fast mixer is present
1878 if (hasFastMixer()) {
1879 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
1880 }
1881
1882 // Check if requested flags are compatible with output stream flags
1883 if ((*flags & outputFlags) != *flags) {
1884 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
1885 *flags, outputFlags);
1886 *flags = (audio_output_flags_t)(*flags & outputFlags);
1887 }
Eric Laurent81784c32012-11-19 14:55:58 -08001888
Eric Laurent81784c32012-11-19 14:55:58 -08001889 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07001890 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08001891 if (
Eric Laurent81784c32012-11-19 14:55:58 -08001892 // PCM data
1893 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001894 // TODO: extract as a data library function that checks that a computationally
1895 // expensive downmixer is not required: isFastOutputChannelConversion()
Andy Hung9a592762014-07-21 21:56:01 -07001896 (channelMask == mChannelMask ||
Andy Hung1f439e12015-05-19 12:57:41 -07001897 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1898 (channelMask == AUDIO_CHANNEL_OUT_MONO
1899 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001900 // hardware sample rate
1901 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001902 // normal mixer has an associated fast mixer
1903 hasFastMixer() &&
1904 // there are sufficient fast track slots available
1905 (mFastTrackAvailMask != 0)
1906 // FIXME test that MixerThread for this fast track has a capable output HAL
1907 // FIXME add a permission test also?
1908 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07001909 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
1910 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001911 // read the fast track multiplier property the first time it is needed
1912 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1913 if (ok != 0) {
1914 ALOGE("%s pthread_once failed: %d", __func__, ok);
1915 }
Andy Hunge0a269a2016-03-23 15:13:42 -07001916 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08001917 }
Eric Laurent4c415062016-06-17 16:14:16 -07001918
1919 // check compatibility with audio effects.
1920 { // scope for mLock
1921 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07001922 for (audio_session_t session : {
1923 AUDIO_SESSION_OUTPUT_STAGE,
1924 AUDIO_SESSION_OUTPUT_MIX,
1925 sessionId,
1926 }) {
1927 sp<EffectChain> chain = getEffectChain_l(session);
1928 if (chain.get() != nullptr) {
1929 audio_output_flags_t old = *flags;
1930 chain->checkOutputFlagCompatibility(flags);
1931 if (old != *flags) {
1932 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
1933 (int)session, (int)old, (int)*flags);
1934 }
Eric Laurent4c415062016-06-17 16:14:16 -07001935 }
1936 }
1937 }
Eric Laurent122f7e72016-06-29 11:53:29 -07001938 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07001939 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
1940 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08001941 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001942 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
1943 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07001944 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001945 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08001946 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001947 audio_is_linear_pcm(format),
1948 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07001949 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08001950 }
1951 }
1952 // For normal PCM streaming tracks, update minimum frame count.
1953 // For compatibility with AudioTrack calculation, buffer depth is forced
1954 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1955 // This is probably too conservative, but legacy application code may depend on it.
1956 // If you change this calculation, also review the start threshold which is related.
Eric Laurent05067782016-06-01 18:27:28 -07001957 if (!(*flags & AUDIO_OUTPUT_FLAG_FAST)
Phil Burkfdb3c072016-02-09 10:47:02 -08001958 && audio_has_proportional_frames(format) && sharedBuffer == 0) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001959 // this must match AudioTrack.cpp calculateMinFrameCount().
1960 // TODO: Move to a common library
Eric Laurent81784c32012-11-19 14:55:58 -08001961 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1962 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1963 if (minBufCount < 2) {
1964 minBufCount = 2;
1965 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07001966 // For normal mixing tracks, if speed is > 1.0f (normal), AudioTrack
1967 // or the client should compute and pass in a larger buffer request.
Andy Hung0e48d252015-01-26 11:43:15 -08001968 size_t minFrameCount =
Andy Hung8edb8dc2015-03-26 19:13:55 -07001969 minBufCount * sourceFramesNeededWithTimestretch(
1970 sampleRate, mNormalFrameCount,
1971 mSampleRate, AUDIO_TIMESTRETCH_SPEED_NORMAL /*speed*/);
Andy Hung0e48d252015-01-26 11:43:15 -08001972 if (frameCount < minFrameCount) { // including frameCount == 0
Eric Laurent81784c32012-11-19 14:55:58 -08001973 frameCount = minFrameCount;
1974 }
Eric Laurent81784c32012-11-19 14:55:58 -08001975 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001976 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001977
Glenn Kastenc3df8382014-03-13 15:05:25 -07001978 switch (mType) {
1979
1980 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08001981 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08001982 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001983 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1984 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001985 sampleRate, format, channelMask, mOutput, mFormat);
1986 lStatus = BAD_VALUE;
1987 goto Exit;
1988 }
1989 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001990 break;
1991
1992 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001993 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001994 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1995 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001996 sampleRate, format, channelMask, mOutput, mFormat);
1997 lStatus = BAD_VALUE;
1998 goto Exit;
1999 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002000 break;
2001
2002 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002003 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002004 ALOGE("createTrack_l() Bad parameter: format %#x \""
2005 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002006 format, mOutput, mFormat);
2007 lStatus = BAD_VALUE;
2008 goto Exit;
2009 }
Andy Hungcd044842014-08-07 11:04:34 -07002010 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002011 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2012 lStatus = BAD_VALUE;
2013 goto Exit;
2014 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002015 break;
2016
Eric Laurent81784c32012-11-19 14:55:58 -08002017 }
2018
2019 lStatus = initCheck();
2020 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002021 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002022 goto Exit;
2023 }
2024
2025 { // scope for mLock
2026 Mutex::Autolock _l(mLock);
2027
2028 // all tracks in same audio session must share the same routing strategy otherwise
2029 // conflicts will happen when tracks are moved from one output to another by audio policy
2030 // manager
2031 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
2032 for (size_t i = 0; i < mTracks.size(); ++i) {
2033 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002034 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002035 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
2036 if (sessionId == t->sessionId() && strategy != actual) {
2037 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2038 strategy, actual);
2039 lStatus = BAD_VALUE;
2040 goto Exit;
2041 }
2042 }
2043 }
2044
Glenn Kastend79072e2016-01-06 08:41:20 -08002045 track = new Track(this, client, streamType, sampleRate, format,
2046 channelMask, frameCount, NULL, sharedBuffer,
2047 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT);
Glenn Kasten03003332013-08-06 15:40:54 -07002048
Glenn Kasten03003332013-08-06 15:40:54 -07002049 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2050 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002051 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002052 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002053 goto Exit;
2054 }
2055 mTracks.add(track);
2056
2057 sp<EffectChain> chain = getEffectChain_l(sessionId);
2058 if (chain != 0) {
2059 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2060 track->setMainBuffer(chain->inBuffer());
2061 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
2062 chain->incTrackCnt();
2063 }
2064
Eric Laurent05067782016-06-01 18:27:28 -07002065 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002066 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2067 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2068 // so ask activity manager to do this on our behalf
2069 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
2070 }
2071 }
2072
2073 lStatus = NO_ERROR;
2074
2075Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002076 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002077 return track;
2078}
2079
2080uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2081{
2082 return latency;
2083}
2084
2085uint32_t AudioFlinger::PlaybackThread::latency() const
2086{
2087 Mutex::Autolock _l(mLock);
2088 return latency_l();
2089}
2090uint32_t AudioFlinger::PlaybackThread::latency_l() const
2091{
2092 if (initCheck() == NO_ERROR) {
2093 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
2094 } else {
2095 return 0;
2096 }
2097}
2098
2099void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2100{
2101 Mutex::Autolock _l(mLock);
2102 // Don't apply master volume in SW if our HAL can do it for us.
2103 if (mOutput && mOutput->audioHwDev &&
2104 mOutput->audioHwDev->canSetMasterVolume()) {
2105 mMasterVolume = 1.0;
2106 } else {
2107 mMasterVolume = value;
2108 }
2109}
2110
2111void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2112{
2113 Mutex::Autolock _l(mLock);
2114 // Don't apply master mute in SW if our HAL can do it for us.
2115 if (mOutput && mOutput->audioHwDev &&
2116 mOutput->audioHwDev->canSetMasterMute()) {
2117 mMasterMute = false;
2118 } else {
2119 mMasterMute = muted;
2120 }
2121}
2122
2123void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2124{
2125 Mutex::Autolock _l(mLock);
2126 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002127 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002128}
2129
2130void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2131{
2132 Mutex::Autolock _l(mLock);
2133 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002134 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002135}
2136
2137float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2138{
2139 Mutex::Autolock _l(mLock);
2140 return mStreamTypes[stream].volume;
2141}
2142
2143// addTrack_l() must be called with ThreadBase::mLock held
2144status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2145{
2146 status_t status = ALREADY_EXISTS;
2147
Eric Laurent81784c32012-11-19 14:55:58 -08002148 if (mActiveTracks.indexOf(track) < 0) {
2149 // the track is newly added, make sure it fills up all its
2150 // buffers before playing. This is to ensure the client will
2151 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002152 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002153 TrackBase::track_state state = track->mState;
2154 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002155 status = AudioSystem::startOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002156 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002157 mLock.lock();
2158 // abort track was stopped/paused while we released the lock
2159 if (state != track->mState) {
2160 if (status == NO_ERROR) {
2161 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002162 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002163 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002164 mLock.lock();
2165 }
2166 return INVALID_OPERATION;
2167 }
2168 // abort if start is rejected by audio policy manager
2169 if (status != NO_ERROR) {
2170 return PERMISSION_DENIED;
2171 }
2172#ifdef ADD_BATTERY_DATA
2173 // to track the speaker usage
2174 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2175#endif
2176 }
2177
Eric Laurent51716182016-02-29 18:00:56 -08002178 // set retry count for buffer fill
2179 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002180 if (track->isStopping_1()) {
2181 track->mRetryCount = kMaxTrackStopRetriesOffload;
2182 } else {
2183 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2184 }
2185 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002186 } else {
2187 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002188 track->mFillingUpStatus =
2189 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002190 }
2191
Eric Laurent81784c32012-11-19 14:55:58 -08002192 track->mResetDone = false;
2193 track->mPresentationCompleteFrames = 0;
2194 mActiveTracks.add(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002195 mWakeLockUids.add(track->uid());
2196 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07002197 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07002198 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2199 if (chain != 0) {
2200 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2201 track->sessionId());
2202 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002203 }
2204
Andy Hung1f82f952016-11-28 19:01:02 -08002205 char buffer[256];
2206 track->dump(buffer, ARRAY_SIZE(buffer), false /* active */);
2207 mLocalLog.log("addTrack_l (%p) %s", track.get(), buffer + 4); // log for analysis
2208
Eric Laurent81784c32012-11-19 14:55:58 -08002209 status = NO_ERROR;
2210 }
2211
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002212 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002213 return status;
2214}
2215
Eric Laurentbfb1b832013-01-07 09:53:42 -08002216bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002217{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002218 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002219 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002220 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2221 track->mState = TrackBase::STOPPED;
2222 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002223 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002224 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002225 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002226 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002227
2228 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002229}
2230
2231void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2232{
2233 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung1f82f952016-11-28 19:01:02 -08002234
2235 char buffer[256];
2236 track->dump(buffer, ARRAY_SIZE(buffer), false /* active */);
2237 mLocalLog.log("removeTrack_l (%p) %s", track.get(), buffer + 4); // log for analysis
2238
Eric Laurent81784c32012-11-19 14:55:58 -08002239 mTracks.remove(track);
2240 deleteTrackName_l(track->name());
2241 // redundant as track is about to be destroyed, for dumpsys only
2242 track->mName = -1;
2243 if (track->isFastTrack()) {
2244 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002245 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002246 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2247 mFastTrackAvailMask |= 1 << index;
2248 // redundant as track is about to be destroyed, for dumpsys only
2249 track->mFastIndex = -1;
2250 }
2251 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2252 if (chain != 0) {
2253 chain->decTrackCnt();
2254 }
2255}
2256
Eric Laurentede6c3b2013-09-19 14:37:46 -07002257void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002258{
2259 // Thread could be blocked waiting for async
2260 // so signal it to handle state changes immediately
2261 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
2262 // be lost so we also flag to prevent it blocking on mWaitWorkCV
2263 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002264 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002265}
2266
Eric Laurent81784c32012-11-19 14:55:58 -08002267String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2268{
Eric Laurent81784c32012-11-19 14:55:58 -08002269 Mutex::Autolock _l(mLock);
2270 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07002271 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002272 }
2273
Glenn Kastend8ea6992013-07-16 14:17:15 -07002274 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
2275 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08002276 free(s);
2277 return out_s8;
2278}
2279
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002280void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002281 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2282 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002283
Eric Laurent73e26b62015-04-27 16:55:58 -07002284 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002285
2286 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002287 case AUDIO_OUTPUT_OPENED:
2288 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002289 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002290 desc->mChannelMask = mChannelMask;
2291 desc->mSamplingRate = mSampleRate;
2292 desc->mFormat = mFormat;
2293 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002294 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002295 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002296 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002297 break;
2298
Eric Laurent73e26b62015-04-27 16:55:58 -07002299 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002300 default:
2301 break;
2302 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002303 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002304}
2305
Eric Laurentbfb1b832013-01-07 09:53:42 -08002306void AudioFlinger::PlaybackThread::writeCallback()
2307{
2308 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002309 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002310}
2311
2312void AudioFlinger::PlaybackThread::drainCallback()
2313{
2314 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002315 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002316}
2317
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002318void AudioFlinger::PlaybackThread::errorCallback()
2319{
2320 ALOG_ASSERT(mCallbackThread != 0);
2321 mCallbackThread->setAsyncError();
2322}
2323
Eric Laurent3b4529e2013-09-05 18:09:19 -07002324void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002325{
2326 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002327 // reject out of sequence requests
2328 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2329 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002330 mWaitWorkCV.signal();
2331 }
2332}
2333
Eric Laurent3b4529e2013-09-05 18:09:19 -07002334void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002335{
2336 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002337 // reject out of sequence requests
2338 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
2339 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002340 mWaitWorkCV.signal();
2341 }
2342}
2343
2344// static
2345int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
Glenn Kasten0f11b512014-01-31 16:18:54 -08002346 void *param __unused,
Eric Laurentbfb1b832013-01-07 09:53:42 -08002347 void *cookie)
2348{
2349 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
2350 ALOGV("asyncCallback() event %d", event);
2351 switch (event) {
2352 case STREAM_CBK_EVENT_WRITE_READY:
2353 me->writeCallback();
2354 break;
2355 case STREAM_CBK_EVENT_DRAIN_READY:
2356 me->drainCallback();
2357 break;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002358 case STREAM_CBK_EVENT_ERROR:
2359 me->errorCallback();
2360 break;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002361 default:
2362 ALOGW("asyncCallback() unknown event %d", event);
2363 break;
2364 }
2365 return 0;
2366}
2367
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002368void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002369{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002370 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002371 mSampleRate = mOutput->getSampleRate();
2372 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002373 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002374 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002375 }
Andy Hung9a592762014-07-21 21:56:01 -07002376 if ((mType == MIXER || mType == DUPLICATING)
2377 && !isValidPcmSinkChannelMask(mChannelMask)) {
2378 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2379 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002380 }
Andy Hunge5412692014-05-16 11:25:07 -07002381 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002382
2383 // Get actual HAL format.
Andy Hung463be252014-07-10 16:56:07 -07002384 mHALFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Phil Burkca5e6142015-07-14 09:42:29 -07002385 // Get format from the shim, which will be different than the HAL format
2386 // if playing compressed audio over HDMI passthrough.
2387 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002388 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002389 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002390 }
Andy Hung6146c082014-03-18 11:56:15 -07002391 if ((mType == MIXER || mType == DUPLICATING)
2392 && !isValidPcmSinkFormat(mFormat)) {
2393 LOG_FATAL("HAL format %#x not supported for mixed output",
2394 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002395 }
Phil Burk062e67a2015-02-11 13:40:50 -08002396 mFrameSize = mOutput->getFrameSize();
Glenn Kasten70949c42013-08-06 07:40:12 -07002397 mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
2398 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002399 if (mFrameCount & 15) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002400 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002401 mFrameCount);
2402 }
2403
Eric Laurentbfb1b832013-01-07 09:53:42 -08002404 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
2405 (mOutput->stream->set_callback != NULL)) {
2406 if (mOutput->stream->set_callback(mOutput->stream,
2407 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
2408 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002409 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002410 }
2411 }
2412
Eric Laurentd1f69b02014-12-15 14:33:13 -08002413 mHwSupportsPause = false;
2414 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
2415 if (mOutput->stream->pause != NULL) {
2416 if (mOutput->stream->resume != NULL) {
2417 mHwSupportsPause = true;
2418 } else {
2419 ALOGW("direct output implements pause but not resume");
2420 }
2421 } else if (mOutput->stream->resume != NULL) {
2422 ALOGW("direct output implements resume but not pause");
2423 }
2424 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002425 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2426 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2427 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002428
Andy Hungfbfc3952015-01-15 13:33:51 -08002429 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2430 // For best precision, we use float instead of the associated output
2431 // device format (typically PCM 16 bit).
2432
2433 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2434 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2435 mBufferSize = mFrameSize * mFrameCount;
2436
2437 // TODO: We currently use the associated output device channel mask and sample rate.
2438 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2439 // (if a valid mask) to avoid premature downmix.
2440 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2441 // instead of the output device sample rate to avoid loss of high frequency information.
2442 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2443 }
2444
Andy Hung09a50072014-02-27 14:30:47 -08002445 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002446 double multiplier = 1.0;
2447 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2448 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002449 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2450 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002451
Eric Laurent81784c32012-11-19 14:55:58 -08002452 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2453 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2454 maxNormalFrameCount = maxNormalFrameCount & ~15;
2455 if (maxNormalFrameCount < minNormalFrameCount) {
2456 maxNormalFrameCount = minNormalFrameCount;
2457 }
2458 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2459 if (multiplier <= 1.0) {
2460 multiplier = 1.0;
2461 } else if (multiplier <= 2.0) {
2462 if (2 * mFrameCount <= maxNormalFrameCount) {
2463 multiplier = 2.0;
2464 } else {
2465 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2466 }
2467 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002468 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002469 }
2470 }
2471 mNormalFrameCount = multiplier * mFrameCount;
2472 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002473 if (mType == MIXER || mType == DUPLICATING) {
2474 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2475 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002476 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002477 mNormalFrameCount);
2478
Andy Hung08fb1742015-05-31 23:22:10 -07002479 // Check if we want to throttle the processing to no more than 2x normal rate
2480 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002481 mThreadThrottleTimeMs = 0;
2482 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002483 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2484
Andy Hung010a1a12014-03-13 13:57:33 -07002485 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2486 // Originally this was int16_t[] array, need to remove legacy implications.
2487 free(mSinkBuffer);
2488 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002489 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2490 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2491 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002492 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002493
Andy Hung69aed5f2014-02-25 17:24:40 -08002494 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2495 // drives the output.
2496 free(mMixerBuffer);
2497 mMixerBuffer = NULL;
2498 if (mMixerBufferEnabled) {
2499 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2500 mMixerBufferSize = mNormalFrameCount * mChannelCount
2501 * audio_bytes_per_sample(mMixerBufferFormat);
2502 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2503 }
Andy Hung98ef9782014-03-04 14:46:50 -08002504 free(mEffectBuffer);
2505 mEffectBuffer = NULL;
2506 if (mEffectBufferEnabled) {
2507 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2508 mEffectBufferSize = mNormalFrameCount * mChannelCount
2509 * audio_bytes_per_sample(mEffectBufferFormat);
2510 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2511 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002512
Eric Laurent81784c32012-11-19 14:55:58 -08002513 // force reconfiguration of effect chains and engines to take new buffer size and audio
2514 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002515 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002516 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2517 // matter.
2518 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2519 Vector< sp<EffectChain> > effectChains = mEffectChains;
2520 for (size_t i = 0; i < effectChains.size(); i ++) {
2521 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2522 }
2523}
2524
2525
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002526status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002527{
2528 if (halFrames == NULL || dspFrames == NULL) {
2529 return BAD_VALUE;
2530 }
2531 Mutex::Autolock _l(mLock);
2532 if (initCheck() != NO_ERROR) {
2533 return INVALID_OPERATION;
2534 }
Andy Hung818e7a32016-02-16 18:08:07 -08002535 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002536 *halFrames = framesWritten;
2537
2538 if (isSuspended()) {
2539 // return an estimation of rendered frames when the output is suspended
2540 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002541 *dspFrames = (uint32_t)
2542 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002543 return NO_ERROR;
2544 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002545 status_t status;
2546 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002547 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002548 *dspFrames = (size_t)frames;
2549 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002550 }
2551}
2552
Eric Laurent4c415062016-06-17 16:14:16 -07002553// hasAudioSession_l() must be called with ThreadBase::mLock held
2554uint32_t AudioFlinger::PlaybackThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08002555{
Eric Laurent81784c32012-11-19 14:55:58 -08002556 uint32_t result = 0;
2557 if (getEffectChain_l(sessionId) != 0) {
2558 result = EFFECT_SESSION;
2559 }
2560
2561 for (size_t i = 0; i < mTracks.size(); ++i) {
2562 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002563 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002564 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07002565 if (track->isFastTrack()) {
2566 result |= FAST_SESSION;
2567 }
Eric Laurent81784c32012-11-19 14:55:58 -08002568 break;
2569 }
2570 }
2571
2572 return result;
2573}
2574
Glenn Kastend848eb42016-03-08 13:42:11 -08002575uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08002576{
2577 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2578 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2579 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2580 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2581 }
2582 for (size_t i = 0; i < mTracks.size(); i++) {
2583 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002584 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002585 return AudioSystem::getStrategyForStream(track->streamType());
2586 }
2587 }
2588 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2589}
2590
2591
Phil Burk062e67a2015-02-11 13:40:50 -08002592AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002593{
2594 Mutex::Autolock _l(mLock);
2595 return mOutput;
2596}
2597
Phil Burk062e67a2015-02-11 13:40:50 -08002598AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002599{
2600 Mutex::Autolock _l(mLock);
2601 AudioStreamOut *output = mOutput;
2602 mOutput = NULL;
2603 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2604 // must push a NULL and wait for ack
2605 mOutputSink.clear();
2606 mPipeSink.clear();
2607 mNormalSink.clear();
2608 return output;
2609}
2610
2611// this method must always be called either with ThreadBase mLock held or inside the thread loop
2612audio_stream_t* AudioFlinger::PlaybackThread::stream() const
2613{
2614 if (mOutput == NULL) {
2615 return NULL;
2616 }
2617 return &mOutput->stream->common;
2618}
2619
2620uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2621{
2622 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2623}
2624
2625status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2626{
2627 if (!isValidSyncEvent(event)) {
2628 return BAD_VALUE;
2629 }
2630
2631 Mutex::Autolock _l(mLock);
2632
2633 for (size_t i = 0; i < mTracks.size(); ++i) {
2634 sp<Track> track = mTracks[i];
2635 if (event->triggerSession() == track->sessionId()) {
2636 (void) track->setSyncEvent(event);
2637 return NO_ERROR;
2638 }
2639 }
2640
2641 return NAME_NOT_FOUND;
2642}
2643
2644bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2645{
2646 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2647}
2648
2649void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2650 const Vector< sp<Track> >& tracksToRemove)
2651{
2652 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002653 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002654 for (size_t i = 0 ; i < count ; i++) {
2655 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002656 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002657 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002658 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002659#ifdef ADD_BATTERY_DATA
2660 // to track the speaker usage
2661 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2662#endif
2663 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002664 AudioSystem::releaseOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002665 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002666 }
Eric Laurent81784c32012-11-19 14:55:58 -08002667 }
2668 }
2669 }
Eric Laurent81784c32012-11-19 14:55:58 -08002670}
2671
2672void AudioFlinger::PlaybackThread::checkSilentMode_l()
2673{
2674 if (!mMasterMute) {
2675 char value[PROPERTY_VALUE_MAX];
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07002676 if (mOutDevice == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) {
2677 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
2678 return;
2679 }
Eric Laurent81784c32012-11-19 14:55:58 -08002680 if (property_get("ro.audio.silent", value, "0") > 0) {
2681 char *endptr;
2682 unsigned long ul = strtoul(value, &endptr, 0);
2683 if (*endptr == '\0' && ul != 0) {
2684 ALOGD("Silence is golden");
2685 // The setprop command will not allow a property to be changed after
2686 // the first time it is set, so we don't have to worry about un-muting.
2687 setMasterMute_l(true);
2688 }
2689 }
2690 }
2691}
2692
2693// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002694ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002695{
Eric Laurent81784c32012-11-19 14:55:58 -08002696 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002697 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002698 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002699
2700 // If an NBAIO sink is present, use it to write the normal mixer's submix
2701 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002702
Andy Hung010a1a12014-03-13 13:57:33 -07002703 const size_t count = mBytesRemaining / mFrameSize;
2704
Simon Wilson2d590962012-11-29 15:18:50 -08002705 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002706 // update the setpoint when AudioFlinger::mScreenState changes
2707 uint32_t screenState = AudioFlinger::mScreenState;
2708 if (screenState != mScreenState) {
2709 mScreenState = screenState;
2710 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2711 if (pipe != NULL) {
2712 pipe->setAvgFrames((mScreenState & 1) ?
2713 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2714 }
2715 }
Andy Hung010a1a12014-03-13 13:57:33 -07002716 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002717 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002718 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002719 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002720 } else {
2721 bytesWritten = framesWritten;
2722 }
2723 // otherwise use the HAL / AudioStreamOut directly
2724 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002725 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002726
Eric Laurentbfb1b832013-01-07 09:53:42 -08002727 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002728 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2729 mWriteAckSequence += 2;
2730 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002731 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002732 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002733 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002734 // FIXME We should have an implementation of timestamps for direct output threads.
2735 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002736 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurent51716182016-02-29 18:00:56 -08002737
Eric Laurentbfb1b832013-01-07 09:53:42 -08002738 if (mUseAsyncWrite &&
2739 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2740 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002741 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002742 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002743 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002744 }
Eric Laurent81784c32012-11-19 14:55:58 -08002745 }
2746
Eric Laurent81784c32012-11-19 14:55:58 -08002747 mNumWrites++;
2748 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002749 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002750 return bytesWritten;
2751}
2752
2753void AudioFlinger::PlaybackThread::threadLoop_drain()
2754{
2755 if (mOutput->stream->drain) {
2756 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2757 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002758 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2759 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002760 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002761 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002762 }
2763 mOutput->stream->drain(mOutput->stream,
2764 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2765 : AUDIO_DRAIN_ALL);
2766 }
2767}
2768
2769void AudioFlinger::PlaybackThread::threadLoop_exit()
2770{
Eric Laurent275e8e92014-11-30 15:14:47 -08002771 {
2772 Mutex::Autolock _l(mLock);
2773 for (size_t i = 0; i < mTracks.size(); i++) {
2774 sp<Track> track = mTracks[i];
2775 track->invalidate();
2776 }
2777 }
Eric Laurent81784c32012-11-19 14:55:58 -08002778}
2779
2780/*
2781The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002782 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002783 - mActiveSleepTimeUs from activeSleepTimeUs()
2784 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08002785 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
2786 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08002787 - maxPeriod from frame count and sample rate (MIXER only)
2788
2789The parameters that affect these derived values are:
2790 - frame count
2791 - frame size
2792 - sample rate
2793 - device type: A2DP or not
2794 - device latency
2795 - format: PCM or not
2796 - active sleep time
2797 - idle sleep time
2798*/
2799
2800void AudioFlinger::PlaybackThread::cacheParameters_l()
2801{
Andy Hung25c2dac2014-02-27 14:56:00 -08002802 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002803 mActiveSleepTimeUs = activeSleepTimeUs();
2804 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08002805
2806 // make sure standby delay is not too short when connected to an A2DP sink to avoid
2807 // truncating audio when going to standby.
2808 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
2809 if ((mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != 0) {
2810 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
2811 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
2812 }
2813 }
Eric Laurent81784c32012-11-19 14:55:58 -08002814}
2815
Eric Laurent13084622016-05-17 10:51:49 -07002816bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08002817{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002818 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08002819 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07002820 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002821 size_t size = mTracks.size();
2822 for (size_t i = 0; i < size; i++) {
2823 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07002824 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002825 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07002826 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002827 }
2828 }
Eric Laurent13084622016-05-17 10:51:49 -07002829 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08002830}
2831
Haynes Mathew George05317d22016-05-03 16:34:26 -07002832void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2833{
2834 Mutex::Autolock _l(mLock);
2835 invalidateTracks_l(streamType);
2836}
2837
Eric Laurent81784c32012-11-19 14:55:58 -08002838status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2839{
Glenn Kastend848eb42016-03-08 13:42:11 -08002840 audio_session_t session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002841 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2842 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002843 bool ownsBuffer = false;
2844
2845 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Glenn Kastend848eb42016-03-08 13:42:11 -08002846 if (session > AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002847 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002848 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002849 if (mType != DIRECT) {
2850 size_t numSamples = mNormalFrameCount * mChannelCount;
2851 buffer = new int16_t[numSamples];
2852 memset(buffer, 0, numSamples * sizeof(int16_t));
2853 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2854 ownsBuffer = true;
2855 }
2856
2857 // Attach all tracks with same session ID to this chain.
2858 for (size_t i = 0; i < mTracks.size(); ++i) {
2859 sp<Track> track = mTracks[i];
2860 if (session == track->sessionId()) {
2861 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2862 buffer);
2863 track->setMainBuffer(buffer);
2864 chain->incTrackCnt();
2865 }
2866 }
2867
2868 // indicate all active tracks in the chain
2869 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2870 sp<Track> track = mActiveTracks[i].promote();
2871 if (track == 0) {
2872 continue;
2873 }
2874 if (session == track->sessionId()) {
2875 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2876 chain->incActiveTrackCnt();
2877 }
2878 }
2879 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002880 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08002881 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002882 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2883 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002884 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Glenn Kastend848eb42016-03-08 13:42:11 -08002885 // chains list in order to be processed last as it contains output stage effects.
Eric Laurent81784c32012-11-19 14:55:58 -08002886 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2887 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08002888 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08002889 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08002890 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08002891 // Effect chain for other sessions are inserted at beginning of effect
2892 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08002893 // sessions is not important.
2894 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
2895 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX,
2896 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08002897 size_t size = mEffectChains.size();
2898 size_t i = 0;
2899 for (i = 0; i < size; i++) {
2900 if (mEffectChains[i]->sessionId() < session) {
2901 break;
2902 }
2903 }
2904 mEffectChains.insertAt(chain, i);
2905 checkSuspendOnAddEffectChain_l(chain);
2906
2907 return NO_ERROR;
2908}
2909
2910size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2911{
Glenn Kastend848eb42016-03-08 13:42:11 -08002912 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08002913
2914 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2915
2916 for (size_t i = 0; i < mEffectChains.size(); i++) {
2917 if (chain == mEffectChains[i]) {
2918 mEffectChains.removeAt(i);
2919 // detach all active tracks from the chain
2920 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2921 sp<Track> track = mActiveTracks[i].promote();
2922 if (track == 0) {
2923 continue;
2924 }
2925 if (session == track->sessionId()) {
2926 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2927 chain.get(), session);
2928 chain->decActiveTrackCnt();
2929 }
2930 }
2931
2932 // detach all tracks with same session ID from this chain
2933 for (size_t i = 0; i < mTracks.size(); ++i) {
2934 sp<Track> track = mTracks[i];
2935 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002936 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002937 chain->decTrackCnt();
2938 }
2939 }
2940 break;
2941 }
2942 }
2943 return mEffectChains.size();
2944}
2945
2946status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2947 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2948{
2949 Mutex::Autolock _l(mLock);
2950 return attachAuxEffect_l(track, EffectId);
2951}
2952
2953status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2954 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2955{
2956 status_t status = NO_ERROR;
2957
2958 if (EffectId == 0) {
2959 track->setAuxBuffer(0, NULL);
2960 } else {
2961 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2962 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2963 if (effect != 0) {
2964 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2965 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2966 } else {
2967 status = INVALID_OPERATION;
2968 }
2969 } else {
2970 status = BAD_VALUE;
2971 }
2972 }
2973 return status;
2974}
2975
2976void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2977{
2978 for (size_t i = 0; i < mTracks.size(); ++i) {
2979 sp<Track> track = mTracks[i];
2980 if (track->auxEffectId() == effectId) {
2981 attachAuxEffect_l(track, 0);
2982 }
2983 }
2984}
2985
2986bool AudioFlinger::PlaybackThread::threadLoop()
2987{
2988 Vector< sp<Track> > tracksToRemove;
2989
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002990 mStandbyTimeNs = systemTime();
Andy Hung69488c42016-05-16 18:43:33 -07002991 nsecs_t lastWriteFinished = -1; // time last server write completed
2992 int64_t lastFramesWritten = -1; // track changes in timestamp server frames written
Eric Laurent81784c32012-11-19 14:55:58 -08002993
2994 // MIXER
2995 nsecs_t lastWarning = 0;
2996
2997 // DUPLICATING
2998 // FIXME could this be made local to while loop?
2999 writeFrames = 0;
3000
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003001 int lastGeneration = 0;
3002
Eric Laurent81784c32012-11-19 14:55:58 -08003003 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003004 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003005
3006 if (mType == MIXER) {
3007 sleepTimeShift = 0;
3008 }
3009
3010 CpuStats cpuStats;
3011 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3012
3013 acquireWakeLock();
3014
Glenn Kasten9e58b552013-01-18 15:09:48 -08003015 // mNBLogWriter->log can only be called while thread mutex mLock is held.
3016 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3017 // and then that string will be logged at the next convenient opportunity.
3018 const char *logString = NULL;
3019
Eric Laurent664539d2013-09-23 18:24:31 -07003020 checkSilentMode_l();
3021
Eric Laurent81784c32012-11-19 14:55:58 -08003022 while (!exitPending())
3023 {
3024 cpuStats.sample(myName);
3025
3026 Vector< sp<EffectChain> > effectChains;
3027
Eric Laurent81784c32012-11-19 14:55:58 -08003028 { // scope for mLock
3029
3030 Mutex::Autolock _l(mLock);
3031
Eric Laurent021cf962014-05-13 10:18:14 -07003032 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07003033
Glenn Kasten9e58b552013-01-18 15:09:48 -08003034 if (logString != NULL) {
3035 mNBLogWriter->logTimestamp();
3036 mNBLogWriter->log(logString);
3037 logString = NULL;
3038 }
3039
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003040 // Gather the framesReleased counters for all active tracks,
Andy Hunge10393e2015-06-12 13:59:33 -07003041 // and associate with the sink frames written out. We need
3042 // this to convert the sink timestamp to the track timestamp.
Andy Hung69488c42016-05-16 18:43:33 -07003043 bool kernelLocationUpdate = false;
Andy Hunge10393e2015-06-12 13:59:33 -07003044 if (mNormalSink != 0) {
Andy Hungc54b1ff2016-02-23 14:07:07 -08003045 // Note: The DuplicatingThread may not have a mNormalSink.
Andy Hung818e7a32016-02-16 18:08:07 -08003046 // We always fetch the timestamp here because often the downstream
Andy Hung69488c42016-05-16 18:43:33 -07003047 // sink will block while writing.
Andy Hung818e7a32016-02-16 18:08:07 -08003048 ExtendedTimestamp timestamp; // use private copy to fetch
3049 (void) mNormalSink->getTimestamp(timestamp);
Andy Hung6d7b1192016-05-07 22:59:48 -07003050
3051 // We keep track of the last valid kernel position in case we are in underrun
3052 // and the normal mixer period is the same as the fast mixer period, or there
3053 // is some error from the HAL.
3054 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3055 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3056 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
3057 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3058 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
3059
3060 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3061 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
3062 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3063 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
Andy Hung69488c42016-05-16 18:43:33 -07003064 }
3065
3066 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3067 kernelLocationUpdate = true;
Andy Hung6d7b1192016-05-07 22:59:48 -07003068 } else {
Eric Laurent122f7e72016-06-29 11:53:29 -07003069 ALOGVV("getTimestamp error - no valid kernel position");
Andy Hung6d7b1192016-05-07 22:59:48 -07003070 }
3071
Andy Hung818e7a32016-02-16 18:08:07 -08003072 // copy over kernel info
3073 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
Andy Hung238fa3d2016-07-28 10:53:22 -07003074 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3075 + mSuspendedFrames; // add frames discarded when suspended
Andy Hung818e7a32016-02-16 18:08:07 -08003076 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
3077 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hungc54b1ff2016-02-23 14:07:07 -08003078 }
3079 // mFramesWritten for non-offloaded tracks are contiguous
3080 // even after standby() is called. This is useful for the track frame
3081 // to sink frame mapping.
Andy Hung69488c42016-05-16 18:43:33 -07003082 bool serverLocationUpdate = false;
3083 if (mFramesWritten != lastFramesWritten) {
3084 serverLocationUpdate = true;
3085 lastFramesWritten = mFramesWritten;
3086 }
3087 // Only update timestamps if there is a meaningful change.
3088 // Either the kernel timestamp must be valid or we have written something.
3089 if (kernelLocationUpdate || serverLocationUpdate) {
3090 if (serverLocationUpdate) {
3091 // use the time before we called the HAL write - it is a bit more accurate
3092 // to when the server last read data than the current time here.
3093 //
3094 // If we haven't written anything, mLastWriteTime will be -1
3095 // and we use systemTime().
3096 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
3097 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastWriteTime == -1
3098 ? systemTime() : mLastWriteTime;
3099 }
3100 const size_t size = mActiveTracks.size();
3101 for (size_t i = 0; i < size; ++i) {
3102 sp<Track> t = mActiveTracks[i].promote();
3103 if (t != 0 && !t->isFastTrack()) {
3104 t->updateTrackFrameInfo(
3105 t->mAudioTrackServerProxy->framesReleased(),
3106 mFramesWritten,
3107 mTimestamp);
3108 }
Andy Hunge10393e2015-06-12 13:59:33 -07003109 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07003110 }
3111
Eric Laurent81784c32012-11-19 14:55:58 -08003112 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003113 if (mSignalPending) {
3114 // A signal was raised while we were unlocked
3115 mSignalPending = false;
3116 } else if (waitingAsyncCallback_l()) {
3117 if (exitPending()) {
3118 break;
3119 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003120 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003121 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003122 releaseWakeLock_l();
3123 released = true;
Mikhail Naganove94c27a2016-08-18 17:31:46 -07003124 mWakeLockUids.clear();
3125 mActiveTracksGeneration++;
Marco Nelissen078538c2015-05-12 09:17:57 -07003126 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003127 ALOGV("wait async completion");
3128 mWaitWorkCV.wait(mLock);
3129 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003130 if (released) {
3131 acquireWakeLock_l();
3132 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003133 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3134 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003135
3136 continue;
3137 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003138 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003139 isSuspended()) {
3140 // put audio hardware into standby after short delay
3141 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003142
3143 threadLoop_standby();
3144
3145 mStandby = true;
3146 }
3147
3148 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
3149 // we're about to wait, flush the binder command buffer
3150 IPCThreadState::self()->flushCommands();
3151
3152 clearOutputTracks();
3153
3154 if (exitPending()) {
3155 break;
3156 }
3157
3158 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003159 mWakeLockUids.clear();
3160 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08003161 // wait until we have something to do...
3162 ALOGV("%s going to sleep", myName.string());
3163 mWaitWorkCV.wait(mLock);
3164 ALOGV("%s waking up", myName.string());
3165 acquireWakeLock_l();
3166
3167 mMixerStatus = MIXER_IDLE;
3168 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3169 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003170 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003171 checkSilentMode_l();
3172
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003173 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3174 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003175 if (mType == MIXER) {
3176 sleepTimeShift = 0;
3177 }
3178
3179 continue;
3180 }
3181 }
Eric Laurent81784c32012-11-19 14:55:58 -08003182 // mMixerStatusIgnoringFastTracks is also updated internally
3183 mMixerStatus = prepareTracks_l(&tracksToRemove);
3184
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003185 // compare with previously applied list
3186 if (lastGeneration != mActiveTracksGeneration) {
3187 // update wakelock
3188 updateWakeLockUids_l(mWakeLockUids);
3189 lastGeneration = mActiveTracksGeneration;
3190 }
3191
Eric Laurent81784c32012-11-19 14:55:58 -08003192 // prevent any changes in effect chain list and in each effect chain
3193 // during mixing and effect process as the audio buffers could be deleted
3194 // or modified if an effect is created or deleted
3195 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003196 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003197
Eric Laurentbfb1b832013-01-07 09:53:42 -08003198 if (mBytesRemaining == 0) {
3199 mCurrentWriteLength = 0;
3200 if (mMixerStatus == MIXER_TRACKS_READY) {
3201 // threadLoop_mix() sets mCurrentWriteLength
3202 threadLoop_mix();
3203 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3204 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003205 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003206 // must be written to HAL
3207 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003208 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003209 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003210 }
3211 }
Andy Hung98ef9782014-03-04 14:46:50 -08003212 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003213 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003214 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3215 // or mSinkBuffer (if there are no effects).
3216 //
3217 // This is done pre-effects computation; if effects change to
3218 // support higher precision, this needs to move.
3219 //
3220 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003221 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003222 if (mMixerBufferValid) {
3223 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3224 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3225
Andy Hung2ddee192015-12-18 17:34:44 -08003226 // mono blend occurs for mixer threads only (not direct or offloaded)
3227 // and is handled here if we're going directly to the sink.
3228 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003229 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3230 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003231 }
3232
Andy Hung98ef9782014-03-04 14:46:50 -08003233 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
3234 mNormalFrameCount * mChannelCount);
3235 }
3236
Eric Laurentbfb1b832013-01-07 09:53:42 -08003237 mBytesRemaining = mCurrentWriteLength;
3238 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003239 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3240 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3241 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3242 mBytesWritten += mBytesRemaining;
3243 mFramesWritten += framesRemaining;
3244 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003245 mBytesRemaining = 0;
3246 }
Eric Laurent81784c32012-11-19 14:55:58 -08003247
Eric Laurentbfb1b832013-01-07 09:53:42 -08003248 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003249 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003250 for (size_t i = 0; i < effectChains.size(); i ++) {
3251 effectChains[i]->process_l();
3252 }
Eric Laurent81784c32012-11-19 14:55:58 -08003253 }
3254 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003255 // Process effect chains for offloaded thread even if no audio
3256 // was read from audio track: process only updates effect state
3257 // and thus does have to be synchronized with audio writes but may have
3258 // to be called while waiting for async write callback
3259 if (mType == OFFLOAD) {
3260 for (size_t i = 0; i < effectChains.size(); i ++) {
3261 effectChains[i]->process_l();
3262 }
3263 }
Eric Laurent81784c32012-11-19 14:55:58 -08003264
Andy Hung98ef9782014-03-04 14:46:50 -08003265 // Only if the Effects buffer is enabled and there is data in the
3266 // Effects buffer (buffer valid), we need to
3267 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003268 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003269 if (mEffectBufferValid) {
3270 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003271
3272 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003273 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3274 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003275 }
3276
Andy Hung98ef9782014-03-04 14:46:50 -08003277 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
3278 mNormalFrameCount * mChannelCount);
3279 }
3280
Eric Laurent81784c32012-11-19 14:55:58 -08003281 // enable changes in effect chain
3282 unlockEffectChains(effectChains);
3283
Eric Laurentbfb1b832013-01-07 09:53:42 -08003284 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003285 // mSleepTimeUs == 0 means we must write to audio hardware
3286 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003287 ssize_t ret = 0;
Andy Hung69488c42016-05-16 18:43:33 -07003288 // We save lastWriteFinished here, as previousLastWriteFinished,
3289 // for throttling. On thread start, previousLastWriteFinished will be
3290 // set to -1, which properly results in no throttling after the first write.
3291 nsecs_t previousLastWriteFinished = lastWriteFinished;
3292 nsecs_t delta = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003293 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003294 // FIXME rewrite to reduce number of system calls
3295 mLastWriteTime = systemTime(); // also used for dumpsys
Andy Hung08fb1742015-05-31 23:22:10 -07003296 ret = threadLoop_write();
Andy Hung69488c42016-05-16 18:43:33 -07003297 lastWriteFinished = systemTime();
3298 delta = lastWriteFinished - mLastWriteTime;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003299 if (ret < 0) {
3300 mBytesRemaining = 0;
3301 } else {
3302 mBytesWritten += ret;
3303 mBytesRemaining -= ret;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003304 mFramesWritten += ret / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003305 }
3306 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3307 (mMixerStatus == MIXER_DRAIN_ALL)) {
3308 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003309 }
Andy Hung08fb1742015-05-31 23:22:10 -07003310 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003311 // write blocked detection
Andy Hung08fb1742015-05-31 23:22:10 -07003312 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003313 mNumDelayedWrites++;
Andy Hung69488c42016-05-16 18:43:33 -07003314 if ((lastWriteFinished - lastWarning) > kWarningThrottleNs) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003315 ATRACE_NAME("underrun");
3316 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003317 (unsigned long long) ns2ms(delta), mNumDelayedWrites, this);
Andy Hung69488c42016-05-16 18:43:33 -07003318 lastWarning = lastWriteFinished;
Glenn Kasten4944acb2013-08-19 08:39:20 -07003319 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003320 }
Andy Hung08fb1742015-05-31 23:22:10 -07003321
3322 if (mThreadThrottle
3323 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
3324 && ret > 0) { // we wrote something
3325 // Limit MixerThread data processing to no more than twice the
3326 // expected processing rate.
3327 //
3328 // This helps prevent underruns with NuPlayer and other applications
3329 // which may set up buffers that are close to the minimum size, or use
3330 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3331 //
3332 // The throttle smooths out sudden large data drains from the device,
3333 // e.g. when it comes out of standby, which often causes problems with
3334 // (1) mixer threads without a fast mixer (which has its own warm-up)
3335 // (2) minimum buffer sized tracks (even if the track is full,
3336 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07003337 //
3338 // Total time spent in last processing cycle equals time spent in
3339 // 1. threadLoop_write, as well as time spent in
3340 // 2. threadLoop_mix (significant for heavy mixing, especially
3341 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07003342
Andy Hung69488c42016-05-16 18:43:33 -07003343 // it's OK if deltaMs is an overestimate.
3344 const int32_t deltaMs =
3345 (lastWriteFinished - previousLastWriteFinished) / 1000000;
Andy Hung08fb1742015-05-31 23:22:10 -07003346 const int32_t throttleMs = mHalfBufferMs - deltaMs;
3347 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3348 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003349 // notify of throttle start on verbose log
3350 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3351 "mixer(%p) throttle begin:"
3352 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003353 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003354 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07003355 // Throttle must be attributed to the previous mixer loop's write time
3356 // to allow back-to-back throttling.
3357 lastWriteFinished += throttleMs * 1000000;
Andy Hung40eb1a12015-06-18 13:42:02 -07003358 } else {
3359 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3360 if (diff > 0) {
3361 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07003362 // but prevent spamming for bluetooth
3363 ALOGD_IF(!audio_is_a2dp_out_device(outDevice()),
3364 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07003365 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3366 }
Andy Hung08fb1742015-05-31 23:22:10 -07003367 }
3368 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003369 }
Eric Laurent81784c32012-11-19 14:55:58 -08003370
Eric Laurentbfb1b832013-01-07 09:53:42 -08003371 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003372 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07003373 Mutex::Autolock _l(mLock);
3374 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
3375 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08003376 }
Glenn Kastene7754022014-10-31 12:11:26 -07003377 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003378 }
Eric Laurent81784c32012-11-19 14:55:58 -08003379 }
3380
3381 // Finally let go of removed track(s), without the lock held
3382 // since we can't guarantee the destructors won't acquire that
3383 // same lock. This will also mutate and push a new fast mixer state.
3384 threadLoop_removeTracks(tracksToRemove);
3385 tracksToRemove.clear();
3386
3387 // FIXME I don't understand the need for this here;
3388 // it was in the original code but maybe the
3389 // assignment in saveOutputTracks() makes this unnecessary?
3390 clearOutputTracks();
3391
3392 // Effect chains will be actually deleted here if they were removed from
3393 // mEffectChains list during mixing or effects processing
3394 effectChains.clear();
3395
3396 // FIXME Note that the above .clear() is no longer necessary since effectChains
3397 // is now local to this block, but will keep it for now (at least until merge done).
3398 }
3399
Eric Laurentbfb1b832013-01-07 09:53:42 -08003400 threadLoop_exit();
3401
Eric Laurentcf817a22014-08-04 20:36:31 -07003402 if (!mStandby) {
3403 threadLoop_standby();
3404 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003405 }
3406
3407 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003408 mWakeLockUids.clear();
3409 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08003410
3411 ALOGV("Thread %p type %d exiting", this, mType);
3412 return false;
3413}
3414
Eric Laurentbfb1b832013-01-07 09:53:42 -08003415// removeTracks_l() must be called with ThreadBase::mLock held
3416void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3417{
3418 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003419 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003420 for (size_t i=0 ; i<count ; i++) {
3421 const sp<Track>& track = tracksToRemove.itemAt(i);
3422 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003423 mWakeLockUids.remove(track->uid());
3424 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003425 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3426 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3427 if (chain != 0) {
3428 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3429 track->sessionId());
3430 chain->decActiveTrackCnt();
3431 }
3432 if (track->isTerminated()) {
3433 removeTrack_l(track);
Andy Hung1f82f952016-11-28 19:01:02 -08003434 } else { // inactive but not terminated
3435 char buffer[256];
3436 track->dump(buffer, ARRAY_SIZE(buffer), false /* active */);
3437 mLocalLog.log("removeTracks_l(%p) %s", track.get(), buffer + 4);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003438 }
3439 }
3440 }
3441
3442}
Eric Laurent81784c32012-11-19 14:55:58 -08003443
Eric Laurentaccc1472013-09-20 09:36:34 -07003444status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3445{
3446 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08003447 ExtendedTimestamp ets;
3448 status_t status = mNormalSink->getTimestamp(ets);
3449 if (status == NO_ERROR) {
3450 status = ets.getBestTimestamp(&timestamp);
3451 }
3452 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07003453 }
Andy Hung9a1c8892014-12-03 11:37:42 -08003454 if ((mType == OFFLOAD || mType == DIRECT)
3455 && mOutput != NULL && mOutput->stream->get_presentation_position) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003456 uint64_t position64;
Phil Burk062e67a2015-02-11 13:40:50 -08003457 int ret = mOutput->getPresentationPosition(&position64, &timestamp.mTime);
Eric Laurentaccc1472013-09-20 09:36:34 -07003458 if (ret == 0) {
3459 timestamp.mPosition = (uint32_t)position64;
3460 return NO_ERROR;
3461 }
3462 }
3463 return INVALID_OPERATION;
3464}
Eric Laurent1c333e22014-05-20 10:48:17 -07003465
Eric Laurent054d9d32015-04-24 08:48:48 -07003466status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3467 audio_patch_handle_t *handle)
3468{
Andy Hungf60abce2016-08-26 11:37:54 -07003469 status_t status;
3470 if (property_get_bool("af.patch_park", false /* default_value */)) {
3471 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3472 // or if HAL does not properly lock against access.
3473 AutoPark<FastMixer> park(mFastMixer);
3474 status = PlaybackThread::createAudioPatch_l(patch, handle);
3475 } else {
3476 status = PlaybackThread::createAudioPatch_l(patch, handle);
3477 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003478 return status;
3479}
3480
Eric Laurent1c333e22014-05-20 10:48:17 -07003481status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3482 audio_patch_handle_t *handle)
3483{
3484 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003485
3486 // store new device and send to effects
3487 audio_devices_t type = AUDIO_DEVICE_NONE;
3488 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3489 type |= patch->sinks[i].ext.device.type;
3490 }
3491
3492#ifdef ADD_BATTERY_DATA
3493 // when changing the audio output device, call addBatteryData to notify
3494 // the change
3495 if (mOutDevice != type) {
3496 uint32_t params = 0;
3497 // check whether speaker is on
3498 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3499 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003500 }
3501
Eric Laurent054d9d32015-04-24 08:48:48 -07003502 audio_devices_t deviceWithoutSpeaker
3503 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3504 // check if any other device (except speaker) is on
3505 if (type & deviceWithoutSpeaker) {
3506 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3507 }
3508
3509 if (params != 0) {
3510 addBatteryData(params);
3511 }
3512 }
3513#endif
3514
3515 for (size_t i = 0; i < mEffectChains.size(); i++) {
3516 mEffectChains[i]->setDevice_l(type);
3517 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003518
3519 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3520 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3521 bool configChanged = mPrevOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003522 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003523 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003524
3525 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003526 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3527 status = hwDevice->create_audio_patch(hwDevice,
3528 patch->num_sources,
3529 patch->sources,
3530 patch->num_sinks,
3531 patch->sinks,
3532 handle);
3533 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003534 char *address;
3535 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3536 //FIXME: we only support address on first sink with HAL version < 3.0
3537 address = audio_device_address_to_parameter(
3538 patch->sinks[0].ext.device.type,
3539 patch->sinks[0].ext.device.address);
3540 } else {
3541 address = (char *)calloc(1, 1);
3542 }
3543 AudioParameter param = AudioParameter(String8(address));
3544 free(address);
3545 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), (int)type);
3546 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3547 param.toString().string());
3548 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003549 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003550 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003551 mPrevOutDevice = type;
Eric Laurente8726fe2015-06-26 09:39:24 -07003552 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3553 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003554 return status;
3555}
3556
Eric Laurent054d9d32015-04-24 08:48:48 -07003557status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3558{
Andy Hungf60abce2016-08-26 11:37:54 -07003559 status_t status;
3560 if (property_get_bool("af.patch_park", false /* default_value */)) {
3561 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3562 // or if HAL does not properly lock against access.
3563 AutoPark<FastMixer> park(mFastMixer);
3564 status = PlaybackThread::releaseAudioPatch_l(handle);
3565 } else {
3566 status = PlaybackThread::releaseAudioPatch_l(handle);
3567 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003568 return status;
3569}
3570
Eric Laurent1c333e22014-05-20 10:48:17 -07003571status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3572{
3573 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003574
3575 mOutDevice = AUDIO_DEVICE_NONE;
3576
Eric Laurent1c333e22014-05-20 10:48:17 -07003577 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
3578 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3579 status = hwDevice->release_audio_patch(hwDevice, handle);
3580 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003581 AudioParameter param;
3582 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
3583 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3584 param.toString().string());
Eric Laurent1c333e22014-05-20 10:48:17 -07003585 }
3586 return status;
3587}
3588
Eric Laurent83b88082014-06-20 18:31:16 -07003589void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3590{
3591 Mutex::Autolock _l(mLock);
3592 mTracks.add(track);
3593}
3594
3595void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3596{
3597 Mutex::Autolock _l(mLock);
3598 destroyTrack_l(track);
3599}
3600
3601void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3602{
3603 ThreadBase::getAudioPortConfig(config);
3604 config->role = AUDIO_PORT_ROLE_SOURCE;
3605 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3606 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3607}
3608
Eric Laurent81784c32012-11-19 14:55:58 -08003609// ----------------------------------------------------------------------------
3610
3611AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003612 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3613 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003614 // mAudioMixer below
3615 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08003616 mFastMixerFutex(0),
3617 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08003618 // mOutputSink below
3619 // mPipeSink below
3620 // mNormalSink below
3621{
3622 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003623 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%zu, "
3624 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003625 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3626 mNormalFrameCount);
3627 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3628
Andy Hungfbfc3952015-01-15 13:33:51 -08003629 if (type == DUPLICATING) {
3630 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3631 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3632 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3633 return;
3634 }
Eric Laurent81784c32012-11-19 14:55:58 -08003635 // create an NBAIO sink for the HAL output stream, and negotiate
3636 mOutputSink = new AudioStreamOutSink(output->stream);
3637 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003638 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003639#if !LOG_NDEBUG
3640 ssize_t index =
3641#else
3642 (void)
3643#endif
3644 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003645 ALOG_ASSERT(index == 0);
3646
3647 // initialize fast mixer depending on configuration
3648 bool initFastMixer;
3649 switch (kUseFastMixer) {
3650 case FastMixer_Never:
3651 initFastMixer = false;
3652 break;
3653 case FastMixer_Always:
3654 initFastMixer = true;
3655 break;
3656 case FastMixer_Static:
3657 case FastMixer_Dynamic:
3658 initFastMixer = mFrameCount < mNormalFrameCount;
3659 break;
3660 }
3661 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003662 audio_format_t fastMixerFormat;
3663 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3664 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3665 } else {
3666 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3667 }
3668 if (mFormat != fastMixerFormat) {
3669 // change our Sink format to accept our intermediate precision
3670 mFormat = fastMixerFormat;
3671 free(mSinkBuffer);
3672 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3673 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3674 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3675 }
Eric Laurent81784c32012-11-19 14:55:58 -08003676
3677 // create a MonoPipe to connect our submix to FastMixer
3678 NBAIO_Format format = mOutputSink->format();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003679#ifdef TEE_SINK
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003680 NBAIO_Format origformat = format;
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003681#endif
Andy Hung1258c1a2014-05-23 21:22:17 -07003682 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07003683 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003684 format.mFormat = fastMixerFormat;
3685 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3686
Eric Laurent81784c32012-11-19 14:55:58 -08003687 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3688 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3689 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3690 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3691 const NBAIO_Format offers[1] = {format};
3692 size_t numCounterOffers = 0;
Glenn Kastenfc302fd2016-04-11 14:11:26 -07003693#if !LOG_NDEBUG || defined(TEE_SINK)
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003694 ssize_t index =
3695#else
3696 (void)
3697#endif
3698 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003699 ALOG_ASSERT(index == 0);
3700 monoPipe->setAvgFrames((mScreenState & 1) ?
3701 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3702 mPipeSink = monoPipe;
3703
Glenn Kasten46909e72013-02-26 09:20:22 -08003704#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003705 if (mTeeSinkOutputEnabled) {
3706 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003707 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3708 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003709 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003710 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003711 ALOG_ASSERT(index == 0);
3712 mTeeSink = teeSink;
3713 PipeReader *teeSource = new PipeReader(*teeSink);
3714 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003715 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003716 ALOG_ASSERT(index == 0);
3717 mTeeSource = teeSource;
3718 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003719#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003720
3721 // create fast mixer and configure it initially with just one fast track for our submix
3722 mFastMixer = new FastMixer();
3723 FastMixerStateQueue *sq = mFastMixer->sq();
3724#ifdef STATE_QUEUE_DUMP
3725 sq->setObserverDump(&mStateQueueObserverDump);
3726 sq->setMutatorDump(&mStateQueueMutatorDump);
3727#endif
3728 FastMixerState *state = sq->begin();
3729 FastTrack *fastTrack = &state->mFastTracks[0];
3730 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3731 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3732 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003733 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3734 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003735 fastTrack->mGeneration++;
3736 state->mFastTracksGen++;
3737 state->mTrackMask = 1;
3738 // fast mixer will use the HAL output sink
3739 state->mOutputSink = mOutputSink.get();
3740 state->mOutputSinkGen++;
3741 state->mFrameCount = mFrameCount;
3742 state->mCommand = FastMixerState::COLD_IDLE;
3743 // already done in constructor initialization list
3744 //mFastMixerFutex = 0;
3745 state->mColdFutexAddr = &mFastMixerFutex;
3746 state->mColdGen++;
3747 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003748#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003749 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003750#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003751 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3752 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003753 sq->end();
3754 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3755
3756 // start the fast mixer
3757 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3758 pid_t tid = mFastMixer->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003759 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003760
3761#ifdef AUDIO_WATCHDOG
3762 // create and start the watchdog
3763 mAudioWatchdog = new AudioWatchdog();
3764 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3765 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3766 tid = mAudioWatchdog->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003767 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003768#endif
3769
Eric Laurent81784c32012-11-19 14:55:58 -08003770 }
3771
3772 switch (kUseFastMixer) {
3773 case FastMixer_Never:
3774 case FastMixer_Dynamic:
3775 mNormalSink = mOutputSink;
3776 break;
3777 case FastMixer_Always:
3778 mNormalSink = mPipeSink;
3779 break;
3780 case FastMixer_Static:
3781 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3782 break;
3783 }
3784}
3785
3786AudioFlinger::MixerThread::~MixerThread()
3787{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003788 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003789 FastMixerStateQueue *sq = mFastMixer->sq();
3790 FastMixerState *state = sq->begin();
3791 if (state->mCommand == FastMixerState::COLD_IDLE) {
3792 int32_t old = android_atomic_inc(&mFastMixerFutex);
3793 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003794 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003795 }
3796 }
3797 state->mCommand = FastMixerState::EXIT;
3798 sq->end();
3799 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3800 mFastMixer->join();
3801 // Though the fast mixer thread has exited, it's state queue is still valid.
3802 // We'll use that extract the final state which contains one remaining fast track
3803 // corresponding to our sub-mix.
3804 state = sq->begin();
3805 ALOG_ASSERT(state->mTrackMask == 1);
3806 FastTrack *fastTrack = &state->mFastTracks[0];
3807 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3808 delete fastTrack->mBufferProvider;
3809 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003810 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003811#ifdef AUDIO_WATCHDOG
3812 if (mAudioWatchdog != 0) {
3813 mAudioWatchdog->requestExit();
3814 mAudioWatchdog->requestExitAndWait();
3815 mAudioWatchdog.clear();
3816 }
3817#endif
3818 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003819 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003820 delete mAudioMixer;
3821}
3822
3823
3824uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3825{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003826 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003827 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3828 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3829 }
3830 return latency;
3831}
3832
3833
3834void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3835{
3836 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3837}
3838
Eric Laurentbfb1b832013-01-07 09:53:42 -08003839ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003840{
3841 // FIXME we should only do one push per cycle; confirm this is true
3842 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003843 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003844 FastMixerStateQueue *sq = mFastMixer->sq();
3845 FastMixerState *state = sq->begin();
3846 if (state->mCommand != FastMixerState::MIX_WRITE &&
3847 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3848 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07003849
3850 // FIXME workaround for first HAL write being CPU bound on some devices
3851 ATRACE_BEGIN("write");
3852 mOutput->write((char *)mSinkBuffer, 0);
3853 ATRACE_END();
3854
Eric Laurent81784c32012-11-19 14:55:58 -08003855 int32_t old = android_atomic_inc(&mFastMixerFutex);
3856 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003857 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003858 }
3859#ifdef AUDIO_WATCHDOG
3860 if (mAudioWatchdog != 0) {
3861 mAudioWatchdog->resume();
3862 }
3863#endif
3864 }
3865 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003866#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003867 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003868 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003869#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003870 sq->end();
3871 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3872 if (kUseFastMixer == FastMixer_Dynamic) {
3873 mNormalSink = mPipeSink;
3874 }
3875 } else {
3876 sq->end(false /*didModify*/);
3877 }
3878 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003879 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003880}
3881
3882void AudioFlinger::MixerThread::threadLoop_standby()
3883{
3884 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003885 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003886 FastMixerStateQueue *sq = mFastMixer->sq();
3887 FastMixerState *state = sq->begin();
3888 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung1f82f952016-11-28 19:01:02 -08003889 // Report any frames trapped in the Monopipe
3890 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
3891 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
3892 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
3893 "monoPipeWritten:%lld monoPipeLeft:%lld",
3894 (long long)mFramesWritten, (long long)mSuspendedFrames,
3895 (long long)mPipeSink->framesWritten(), pipeFrames);
3896 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
3897
Eric Laurent81784c32012-11-19 14:55:58 -08003898 state->mCommand = FastMixerState::COLD_IDLE;
3899 state->mColdFutexAddr = &mFastMixerFutex;
3900 state->mColdGen++;
3901 mFastMixerFutex = 0;
3902 sq->end();
3903 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3904 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3905 if (kUseFastMixer == FastMixer_Dynamic) {
3906 mNormalSink = mOutputSink;
3907 }
3908#ifdef AUDIO_WATCHDOG
3909 if (mAudioWatchdog != 0) {
3910 mAudioWatchdog->pause();
3911 }
3912#endif
3913 } else {
3914 sq->end(false /*didModify*/);
3915 }
3916 }
3917 PlaybackThread::threadLoop_standby();
3918}
3919
Eric Laurentbfb1b832013-01-07 09:53:42 -08003920bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3921{
3922 return false;
3923}
3924
3925bool AudioFlinger::PlaybackThread::shouldStandby_l()
3926{
3927 return !mStandby;
3928}
3929
3930bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3931{
3932 Mutex::Autolock _l(mLock);
3933 return waitingAsyncCallback_l();
3934}
3935
Eric Laurent81784c32012-11-19 14:55:58 -08003936// shared by MIXER and DIRECT, overridden by DUPLICATING
3937void AudioFlinger::PlaybackThread::threadLoop_standby()
3938{
3939 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08003940 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003941 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003942 // discard any pending drain or write ack by incrementing sequence
3943 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3944 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003945 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003946 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3947 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003948 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003949 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003950}
3951
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003952void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3953{
3954 ALOGV("signal playback thread");
3955 broadcast_l();
3956}
3957
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003958void AudioFlinger::PlaybackThread::onAsyncError()
3959{
3960 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
3961 invalidateTracks((audio_stream_type_t)i);
3962 }
3963}
3964
Eric Laurent81784c32012-11-19 14:55:58 -08003965void AudioFlinger::MixerThread::threadLoop_mix()
3966{
Eric Laurent81784c32012-11-19 14:55:58 -08003967 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08003968 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08003969 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003970 // increase sleep time progressively when application underrun condition clears.
3971 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3972 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3973 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003974 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003975 sleepTimeShift--;
3976 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003977 mSleepTimeUs = 0;
3978 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08003979 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003980
Eric Laurent81784c32012-11-19 14:55:58 -08003981}
3982
3983void AudioFlinger::MixerThread::threadLoop_sleepTime()
3984{
3985 // If no tracks are ready, sleep once for the duration of an output
3986 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003987 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003988 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003989 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
3990 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
3991 mSleepTimeUs = kMinThreadSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003992 }
3993 // reduce sleep time in case of consecutive application underruns to avoid
3994 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3995 // duration we would end up writing less data than needed by the audio HAL if
3996 // the condition persists.
3997 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3998 sleepTimeShift++;
3999 }
4000 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004001 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004002 }
4003 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004004 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
4005 // before effects processing or output.
4006 if (mMixerBufferValid) {
4007 memset(mMixerBuffer, 0, mMixerBufferSize);
4008 } else {
4009 memset(mSinkBuffer, 0, mSinkBufferSize);
4010 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004011 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004012 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
4013 "anticipated start");
4014 }
4015 // TODO add standby time extension fct of effect tail
4016}
4017
4018// prepareTracks_l() must be called with ThreadBase::mLock held
4019AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
4020 Vector< sp<Track> > *tracksToRemove)
4021{
4022
4023 mixer_state mixerStatus = MIXER_IDLE;
4024 // find out which tracks need to be processed
4025 size_t count = mActiveTracks.size();
4026 size_t mixedTracks = 0;
4027 size_t tracksWithEffect = 0;
4028 // counts only _active_ fast tracks
4029 size_t fastTracks = 0;
4030 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
4031
4032 float masterVolume = mMasterVolume;
4033 bool masterMute = mMasterMute;
4034
4035 if (masterMute) {
4036 masterVolume = 0;
4037 }
4038 // Delegate master volume control to effect in output mix effect chain if needed
4039 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4040 if (chain != 0) {
4041 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
4042 chain->setVolume_l(&v, &v);
4043 masterVolume = (float)((v + (1 << 23)) >> 24);
4044 chain.clear();
4045 }
4046
4047 // prepare a new state to push
4048 FastMixerStateQueue *sq = NULL;
4049 FastMixerState *state = NULL;
4050 bool didModify = false;
4051 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004052 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004053 sq = mFastMixer->sq();
4054 state = sq->begin();
4055 }
4056
Andy Hung69aed5f2014-02-25 17:24:40 -08004057 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08004058 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08004059
Eric Laurent81784c32012-11-19 14:55:58 -08004060 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07004061 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08004062 if (t == 0) {
4063 continue;
4064 }
4065
4066 // this const just means the local variable doesn't change
4067 Track* const track = t.get();
4068
4069 // process fast tracks
4070 if (track->isFastTrack()) {
4071
4072 // It's theoretically possible (though unlikely) for a fast track to be created
4073 // and then removed within the same normal mix cycle. This is not a problem, as
4074 // the track never becomes active so it's fast mixer slot is never touched.
4075 // The converse, of removing an (active) track and then creating a new track
4076 // at the identical fast mixer slot within the same normal mix cycle,
4077 // is impossible because the slot isn't marked available until the end of each cycle.
4078 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07004079 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08004080 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
4081 FastTrack *fastTrack = &state->mFastTracks[j];
4082
4083 // Determine whether the track is currently in underrun condition,
4084 // and whether it had a recent underrun.
4085 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
4086 FastTrackUnderruns underruns = ftDump->mUnderruns;
4087 uint32_t recentFull = (underruns.mBitFields.mFull -
4088 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
4089 uint32_t recentPartial = (underruns.mBitFields.mPartial -
4090 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
4091 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
4092 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
4093 uint32_t recentUnderruns = recentPartial + recentEmpty;
4094 track->mObservedUnderruns = underruns;
4095 // don't count underruns that occur while stopping or pausing
4096 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07004097 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
4098 recentUnderruns > 0) {
4099 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
4100 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Phil Burk2812d9e2016-01-04 10:34:30 -08004101 } else {
4102 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Eric Laurent81784c32012-11-19 14:55:58 -08004103 }
4104
4105 // This is similar to the state machine for normal tracks,
4106 // with a few modifications for fast tracks.
4107 bool isActive = true;
4108 switch (track->mState) {
4109 case TrackBase::STOPPING_1:
4110 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08004111 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004112 track->mState = TrackBase::STOPPING_2;
4113 }
4114 break;
4115 case TrackBase::PAUSING:
4116 // ramp down is not yet implemented
4117 track->setPaused();
4118 break;
4119 case TrackBase::RESUMING:
4120 // ramp up is not yet implemented
4121 track->mState = TrackBase::ACTIVE;
4122 break;
4123 case TrackBase::ACTIVE:
4124 if (recentFull > 0 || recentPartial > 0) {
4125 // track has provided at least some frames recently: reset retry count
4126 track->mRetryCount = kMaxTrackRetries;
4127 }
4128 if (recentUnderruns == 0) {
4129 // no recent underruns: stay active
4130 break;
4131 }
4132 // there has recently been an underrun of some kind
4133 if (track->sharedBuffer() == 0) {
4134 // were any of the recent underruns "empty" (no frames available)?
4135 if (recentEmpty == 0) {
4136 // no, then ignore the partial underruns as they are allowed indefinitely
4137 break;
4138 }
4139 // there has recently been an "empty" underrun: decrement the retry counter
4140 if (--(track->mRetryCount) > 0) {
4141 break;
4142 }
4143 // indicate to client process that the track was disabled because of underrun;
4144 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004145 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004146 // remove from active list, but state remains ACTIVE [confusing but true]
4147 isActive = false;
4148 break;
4149 }
4150 // fall through
4151 case TrackBase::STOPPING_2:
4152 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08004153 case TrackBase::STOPPED:
4154 case TrackBase::FLUSHED: // flush() while active
4155 // Check for presentation complete if track is inactive
4156 // We have consumed all the buffers of this track.
4157 // This would be incomplete if we auto-paused on underrun
4158 {
4159 size_t audioHALFrames =
4160 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004161 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004162 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
4163 // track stays in active list until presentation is complete
4164 break;
4165 }
4166 }
4167 if (track->isStopping_2()) {
4168 track->mState = TrackBase::STOPPED;
4169 }
4170 if (track->isStopped()) {
4171 // Can't reset directly, as fast mixer is still polling this track
4172 // track->reset();
4173 // So instead mark this track as needing to be reset after push with ack
4174 resetMask |= 1 << i;
4175 }
4176 isActive = false;
4177 break;
4178 case TrackBase::IDLE:
4179 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08004180 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08004181 }
4182
4183 if (isActive) {
4184 // was it previously inactive?
4185 if (!(state->mTrackMask & (1 << j))) {
4186 ExtendedAudioBufferProvider *eabp = track;
4187 VolumeProvider *vp = track;
4188 fastTrack->mBufferProvider = eabp;
4189 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08004190 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07004191 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08004192 fastTrack->mGeneration++;
4193 state->mTrackMask |= 1 << j;
4194 didModify = true;
4195 // no acknowledgement required for newly active tracks
4196 }
4197 // cache the combined master volume and stream type volume for fast mixer; this
4198 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08004199 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08004200 ++fastTracks;
4201 } else {
4202 // was it previously active?
4203 if (state->mTrackMask & (1 << j)) {
4204 fastTrack->mBufferProvider = NULL;
4205 fastTrack->mGeneration++;
4206 state->mTrackMask &= ~(1 << j);
4207 didModify = true;
4208 // If any fast tracks were removed, we must wait for acknowledgement
4209 // because we're about to decrement the last sp<> on those tracks.
4210 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4211 } else {
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08004212 LOG_ALWAYS_FATAL("fast track %d should have been active; "
4213 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
4214 j, track->mState, state->mTrackMask, recentUnderruns,
4215 track->sharedBuffer() != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004216 }
4217 tracksToRemove->add(track);
4218 // Avoids a misleading display in dumpsys
4219 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
4220 }
4221 continue;
4222 }
4223
4224 { // local variable scope to avoid goto warning
4225
4226 audio_track_cblk_t* cblk = track->cblk();
4227
4228 // The first time a track is added we wait
4229 // for all its buffers to be filled before processing it
4230 int name = track->name();
4231 // make sure that we have enough frames to mix one full buffer.
4232 // enforce this condition only once to enable draining the buffer in case the client
4233 // app does not call stop() and relies on underrun to stop:
4234 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
4235 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004236 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07004237 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004238 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004239
4240 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004241 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004242 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
4243 // add frames already consumed but not yet released by the resampler
4244 // because mAudioTrackServerProxy->framesReady() will include these frames
4245 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
4246
Eric Laurent81784c32012-11-19 14:55:58 -08004247 uint32_t minFrames = 1;
4248 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
4249 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004250 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08004251 }
Eric Laurent13e4c962013-12-20 17:36:01 -08004252
4253 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07004254 if (ATRACE_ENABLED()) {
4255 // I wish we had formatted trace names
4256 char traceName[16];
4257 strcpy(traceName, "nRdy");
4258 int name = track->name();
4259 if (AudioMixer::TRACK0 <= name &&
4260 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
4261 name -= AudioMixer::TRACK0;
4262 traceName[4] = (name / 10) + '0';
4263 traceName[5] = (name % 10) + '0';
4264 } else {
4265 traceName[4] = '?';
4266 traceName[5] = '?';
4267 }
4268 traceName[6] = '\0';
4269 ATRACE_INT(traceName, framesReady);
4270 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004271 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08004272 !track->isPaused() && !track->isTerminated())
4273 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004274 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004275
4276 mixedTracks++;
4277
Andy Hung69aed5f2014-02-25 17:24:40 -08004278 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
4279 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08004280 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08004281 if (track->mainBuffer() != mSinkBuffer &&
4282 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004283 if (mEffectBufferEnabled) {
4284 mEffectBufferValid = true; // Later can set directly.
4285 }
Eric Laurent81784c32012-11-19 14:55:58 -08004286 chain = getEffectChain_l(track->sessionId());
4287 // Delegate volume control to effect in track effect chain if needed
4288 if (chain != 0) {
4289 tracksWithEffect++;
4290 } else {
4291 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
4292 "session %d",
4293 name, track->sessionId());
4294 }
4295 }
4296
4297
4298 int param = AudioMixer::VOLUME;
4299 if (track->mFillingUpStatus == Track::FS_FILLED) {
4300 // no ramp for the first volume setting
4301 track->mFillingUpStatus = Track::FS_ACTIVE;
4302 if (track->mState == TrackBase::RESUMING) {
4303 track->mState = TrackBase::ACTIVE;
4304 param = AudioMixer::RAMP_VOLUME;
4305 }
4306 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004307 // FIXME should not make a decision based on mServer
4308 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004309 // If the track is stopped before the first frame was mixed,
4310 // do not apply ramp
4311 param = AudioMixer::RAMP_VOLUME;
4312 }
4313
4314 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07004315 uint32_t vl, vr; // in U8.24 integer format
4316 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08004317 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07004318 vl = vr = 0;
4319 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08004320 if (track->isPausing()) {
4321 track->setPaused();
4322 }
4323 } else {
4324
4325 // read original volumes with volume control
4326 float typeVolume = mStreamTypes[track->streamType()].volume;
4327 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004328 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004329 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07004330 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
4331 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08004332 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07004333 if (vlf > GAIN_FLOAT_UNITY) {
4334 ALOGV("Track left volume out of range: %.3g", vlf);
4335 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004336 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07004337 if (vrf > GAIN_FLOAT_UNITY) {
4338 ALOGV("Track right volume out of range: %.3g", vrf);
4339 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004340 }
4341 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07004342 vlf *= v;
4343 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08004344 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07004345 // then derive vl and vr as U8.24 versions for the effect chain
4346 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
4347 vl = (uint32_t) (scaleto8_24 * vlf);
4348 vr = (uint32_t) (scaleto8_24 * vrf);
4349 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08004350 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08004351 // send level comes from shared memory and so may be corrupt
4352 if (sendLevel > MAX_GAIN_INT) {
4353 ALOGV("Track send level out of range: %04X", sendLevel);
4354 sendLevel = MAX_GAIN_INT;
4355 }
Andy Hung6be49402014-05-30 10:42:03 -07004356 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4357 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08004358 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004359
Eric Laurent81784c32012-11-19 14:55:58 -08004360 // Delegate volume control to effect in track effect chain if needed
4361 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4362 // Do not ramp volume if volume is controlled by effect
4363 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08004364 // Update remaining floating point volume levels
4365 vlf = (float)vl / (1 << 24);
4366 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004367 track->mHasVolumeController = true;
4368 } else {
4369 // force no volume ramp when volume controller was just disabled or removed
4370 // from effect chain to avoid volume spike
4371 if (track->mHasVolumeController) {
4372 param = AudioMixer::VOLUME;
4373 }
4374 track->mHasVolumeController = false;
4375 }
4376
Eric Laurent81784c32012-11-19 14:55:58 -08004377 // XXX: these things DON'T need to be done each time
4378 mAudioMixer->setBufferProvider(name, track);
4379 mAudioMixer->enable(name);
4380
Andy Hung6be49402014-05-30 10:42:03 -07004381 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
4382 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
4383 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004384 mAudioMixer->setParameter(
4385 name,
4386 AudioMixer::TRACK,
4387 AudioMixer::FORMAT, (void *)track->format());
4388 mAudioMixer->setParameter(
4389 name,
4390 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004391 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004392 mAudioMixer->setParameter(
4393 name,
4394 AudioMixer::TRACK,
4395 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004396 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004397 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004398 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004399 if (reqSampleRate == 0) {
4400 reqSampleRate = mSampleRate;
4401 } else if (reqSampleRate > maxSampleRate) {
4402 reqSampleRate = maxSampleRate;
4403 }
Eric Laurent81784c32012-11-19 14:55:58 -08004404 mAudioMixer->setParameter(
4405 name,
4406 AudioMixer::RESAMPLE,
4407 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004408 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004409
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004410 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004411 mAudioMixer->setParameter(
4412 name,
4413 AudioMixer::TIMESTRETCH,
4414 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004415 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004416
Andy Hung69aed5f2014-02-25 17:24:40 -08004417 /*
4418 * Select the appropriate output buffer for the track.
4419 *
Andy Hung98ef9782014-03-04 14:46:50 -08004420 * Tracks with effects go into their own effects chain buffer
4421 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004422 *
4423 * Other tracks can use mMixerBuffer for higher precision
4424 * channel accumulation. If this buffer is enabled
4425 * (mMixerBufferEnabled true), then selected tracks will accumulate
4426 * into it.
4427 *
4428 */
4429 if (mMixerBufferEnabled
4430 && (track->mainBuffer() == mSinkBuffer
4431 || track->mainBuffer() == mMixerBuffer)) {
4432 mAudioMixer->setParameter(
4433 name,
4434 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004435 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004436 mAudioMixer->setParameter(
4437 name,
4438 AudioMixer::TRACK,
4439 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4440 // TODO: override track->mainBuffer()?
4441 mMixerBufferValid = true;
4442 } else {
4443 mAudioMixer->setParameter(
4444 name,
4445 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004446 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004447 mAudioMixer->setParameter(
4448 name,
4449 AudioMixer::TRACK,
4450 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4451 }
Eric Laurent81784c32012-11-19 14:55:58 -08004452 mAudioMixer->setParameter(
4453 name,
4454 AudioMixer::TRACK,
4455 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4456
4457 // reset retry count
4458 track->mRetryCount = kMaxTrackRetries;
4459
4460 // If one track is ready, set the mixer ready if:
4461 // - the mixer was not ready during previous round OR
4462 // - no other track is not ready
4463 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4464 mixerStatus != MIXER_TRACKS_ENABLED) {
4465 mixerStatus = MIXER_TRACKS_READY;
4466 }
4467 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004468 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hung08fb1742015-05-31 23:22:10 -07004469 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)",
4470 track, framesReady, desiredFrames);
Glenn Kasten82aaf942013-07-17 16:05:07 -07004471 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08004472 } else {
4473 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004474 }
Phil Burk2812d9e2016-01-04 10:34:30 -08004475
Eric Laurent81784c32012-11-19 14:55:58 -08004476 // clear effect chain input buffer if an active track underruns to avoid sending
4477 // previous audio buffer again to effects
4478 chain = getEffectChain_l(track->sessionId());
4479 if (chain != 0) {
4480 chain->clearInputBuffer();
4481 }
4482
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004483 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004484 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4485 track->isStopped() || track->isPaused()) {
4486 // We have consumed all the buffers of this track.
4487 // Remove it from the list of active tracks.
4488 // TODO: use actual buffer filling status instead of latency when available from
4489 // audio HAL
4490 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004491 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004492 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4493 if (track->isStopped()) {
4494 track->reset();
4495 }
4496 tracksToRemove->add(track);
4497 }
4498 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004499 // No buffers for this track. Give it a few chances to
4500 // fill a buffer, then remove it from active list.
4501 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004502 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004503 tracksToRemove->add(track);
4504 // indicate to client process that the track was disabled because of underrun;
4505 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004506 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004507 // If one track is not ready, mark the mixer also not ready if:
4508 // - the mixer was ready during previous round OR
4509 // - no other track is ready
4510 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4511 mixerStatus != MIXER_TRACKS_READY) {
4512 mixerStatus = MIXER_TRACKS_ENABLED;
4513 }
4514 }
4515 mAudioMixer->disable(name);
4516 }
4517
4518 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08004519
4520 }
4521
4522 // Push the new FastMixer state if necessary
4523 bool pauseAudioWatchdog = false;
4524 if (didModify) {
4525 state->mFastTracksGen++;
4526 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4527 if (kUseFastMixer == FastMixer_Dynamic &&
4528 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4529 state->mCommand = FastMixerState::COLD_IDLE;
4530 state->mColdFutexAddr = &mFastMixerFutex;
4531 state->mColdGen++;
4532 mFastMixerFutex = 0;
4533 if (kUseFastMixer == FastMixer_Dynamic) {
4534 mNormalSink = mOutputSink;
4535 }
4536 // If we go into cold idle, need to wait for acknowledgement
4537 // so that fast mixer stops doing I/O.
4538 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4539 pauseAudioWatchdog = true;
4540 }
Eric Laurent81784c32012-11-19 14:55:58 -08004541 }
4542 if (sq != NULL) {
4543 sq->end(didModify);
4544 sq->push(block);
4545 }
4546#ifdef AUDIO_WATCHDOG
4547 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4548 mAudioWatchdog->pause();
4549 }
4550#endif
4551
4552 // Now perform the deferred reset on fast tracks that have stopped
4553 while (resetMask != 0) {
4554 size_t i = __builtin_ctz(resetMask);
4555 ALOG_ASSERT(i < count);
4556 resetMask &= ~(1 << i);
4557 sp<Track> t = mActiveTracks[i].promote();
4558 if (t == 0) {
4559 continue;
4560 }
4561 Track* track = t.get();
4562 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4563 track->reset();
4564 }
4565
4566 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004567 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004568
Eric Laurent97d547d2014-09-02 14:45:53 -07004569 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4570 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004571 }
4572
4573 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004574 // as long as there are effects we should clear the effects buffer, to avoid
4575 // passing a non-clean buffer to the effect chain
4576 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004577 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004578 // sink or mix buffer must be cleared if all tracks are connected to an
4579 // effect chain as in this case the mixer will not write to the sink or mix buffer
4580 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004581 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4582 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004583 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004584 if (mMixerBufferValid) {
4585 memset(mMixerBuffer, 0, mMixerBufferSize);
4586 // TODO: In testing, mSinkBuffer below need not be cleared because
4587 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4588 // after mixing.
4589 //
4590 // To enforce this guarantee:
4591 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4592 // (mixedTracks == 0 && fastTracks > 0))
4593 // must imply MIXER_TRACKS_READY.
4594 // Later, we may clear buffers regardless, and skip much of this logic.
4595 }
Andy Hung98ef9782014-03-04 14:46:50 -08004596 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004597 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004598 }
4599
4600 // if any fast tracks, then status is ready
4601 mMixerStatusIgnoringFastTracks = mixerStatus;
4602 if (fastTracks > 0) {
4603 mixerStatus = MIXER_TRACKS_READY;
4604 }
4605 return mixerStatus;
4606}
4607
Eric Laurentad7dd962016-09-22 12:38:37 -07004608// trackCountForUid_l() must be called with ThreadBase::mLock held
4609uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid)
4610{
4611 uint32_t trackCount = 0;
4612 for (size_t i = 0; i < mTracks.size() ; i++) {
4613 if (mTracks[i]->uid() == (int)uid) {
4614 trackCount++;
4615 }
4616 }
4617 return trackCount;
4618}
4619
Eric Laurent81784c32012-11-19 14:55:58 -08004620// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07004621int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
Eric Laurentad7dd962016-09-22 12:38:37 -07004622 audio_format_t format, audio_session_t sessionId, uid_t uid)
Eric Laurent81784c32012-11-19 14:55:58 -08004623{
Eric Laurentad7dd962016-09-22 12:38:37 -07004624 if (trackCountForUid_l(uid) > (PlaybackThread::kMaxTracksPerUid - 1)) {
4625 return -1;
4626 }
Andy Hunge8a1ced2014-05-09 15:02:21 -07004627 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08004628}
4629
4630// deleteTrackName_l() must be called with ThreadBase::mLock held
4631void AudioFlinger::MixerThread::deleteTrackName_l(int name)
4632{
4633 ALOGV("remove track (%d) and delete from mixer", name);
4634 mAudioMixer->deleteTrackName(name);
4635}
4636
Eric Laurent10351942014-05-08 18:49:52 -07004637// checkForNewParameter_l() must be called with ThreadBase::mLock held
4638bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4639 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004640{
Eric Laurent81784c32012-11-19 14:55:58 -08004641 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08004642 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004643
Eric Laurent10351942014-05-08 18:49:52 -07004644 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004645
Glenn Kastenc05b8d72016-03-24 09:48:17 -07004646 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004647
Eric Laurent10351942014-05-08 18:49:52 -07004648 AudioParameter param = AudioParameter(keyValuePair);
4649 int value;
4650 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4651 reconfig = true;
4652 }
4653 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004654 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004655 status = BAD_VALUE;
4656 } else {
4657 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004658 reconfig = true;
4659 }
Eric Laurent10351942014-05-08 18:49:52 -07004660 }
4661 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004662 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004663 status = BAD_VALUE;
4664 } else {
4665 // no need to save value, since it's constant
4666 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004667 }
Eric Laurent10351942014-05-08 18:49:52 -07004668 }
4669 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4670 // do not accept frame count changes if tracks are open as the track buffer
4671 // size depends on frame count and correct behavior would not be guaranteed
4672 // if frame count is changed after track creation
4673 if (!mTracks.isEmpty()) {
4674 status = INVALID_OPERATION;
4675 } else {
4676 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004677 }
Eric Laurent10351942014-05-08 18:49:52 -07004678 }
4679 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004680#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004681 // when changing the audio output device, call addBatteryData to notify
4682 // the change
4683 if (mOutDevice != value) {
4684 uint32_t params = 0;
4685 // check whether speaker is on
4686 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4687 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004688 }
Eric Laurent10351942014-05-08 18:49:52 -07004689
4690 audio_devices_t deviceWithoutSpeaker
4691 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4692 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07004693 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07004694 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4695 }
4696
4697 if (params != 0) {
4698 addBatteryData(params);
4699 }
4700 }
Eric Laurent81784c32012-11-19 14:55:58 -08004701#endif
4702
Eric Laurent10351942014-05-08 18:49:52 -07004703 // forward device change to effects that have requested to be
4704 // aware of attached audio device.
4705 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08004706 a2dpDeviceChanged =
4707 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07004708 mOutDevice = value;
4709 for (size_t i = 0; i < mEffectChains.size(); i++) {
4710 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004711 }
4712 }
Eric Laurent10351942014-05-08 18:49:52 -07004713 }
Eric Laurent81784c32012-11-19 14:55:58 -08004714
Eric Laurent10351942014-05-08 18:49:52 -07004715 if (status == NO_ERROR) {
4716 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4717 keyValuePair.string());
4718 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004719 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004720 mStandby = true;
4721 mBytesWritten = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004722 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Eric Laurent10351942014-05-08 18:49:52 -07004723 keyValuePair.string());
Eric Laurent81784c32012-11-19 14:55:58 -08004724 }
Eric Laurent10351942014-05-08 18:49:52 -07004725 if (status == NO_ERROR && reconfig) {
4726 readOutputParameters_l();
4727 delete mAudioMixer;
4728 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4729 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004730 int name = getTrackName_l(mTracks[i]->mChannelMask,
Eric Laurentad7dd962016-09-22 12:38:37 -07004731 mTracks[i]->mFormat, mTracks[i]->mSessionId, mTracks[i]->uid());
Eric Laurent10351942014-05-08 18:49:52 -07004732 if (name < 0) {
4733 break;
4734 }
4735 mTracks[i]->mName = name;
4736 }
Eric Laurent73e26b62015-04-27 16:55:58 -07004737 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004738 }
Eric Laurent81784c32012-11-19 14:55:58 -08004739 }
4740
Eric Laurent42537be2016-01-08 17:16:42 -08004741 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08004742}
4743
4744
4745void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4746{
Eric Laurent81784c32012-11-19 14:55:58 -08004747 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07004748 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Elliott Hughes87cebad2014-05-22 10:14:43 -07004749 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Andy Hung2ddee192015-12-18 17:34:44 -08004750 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent81784c32012-11-19 14:55:58 -08004751
4752 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten2f90c512015-12-02 11:40:09 -08004753 // while we are dumping it. It may be inconsistent, but it won't mutate!
4754 // This is a large object so we place it on the heap.
4755 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
4756 const FastMixerDumpState *copy = new FastMixerDumpState(mFastMixerDumpState);
4757 copy->dump(fd);
4758 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08004759
4760#ifdef STATE_QUEUE_DUMP
4761 // Similar for state queue
4762 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4763 observerCopy.dump(fd);
4764 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4765 mutatorCopy.dump(fd);
4766#endif
4767
Glenn Kasten46909e72013-02-26 09:20:22 -08004768#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004769 // Write the tee output to a .wav file
4770 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08004771#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004772
4773#ifdef AUDIO_WATCHDOG
4774 if (mAudioWatchdog != 0) {
4775 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4776 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4777 wdCopy.dump(fd);
4778 }
4779#endif
4780}
4781
4782uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4783{
4784 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4785}
4786
4787uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4788{
4789 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4790}
4791
4792void AudioFlinger::MixerThread::cacheParameters_l()
4793{
4794 PlaybackThread::cacheParameters_l();
4795
4796 // FIXME: Relaxed timing because of a certain device that can't meet latency
4797 // Should be reduced to 2x after the vendor fixes the driver issue
4798 // increase threshold again due to low power audio mode. The way this warning
4799 // threshold is calculated and its usefulness should be reconsidered anyway.
4800 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4801}
4802
4803// ----------------------------------------------------------------------------
4804
4805AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07004806 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady)
4807 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08004808 // mLeftVolFloat, mRightVolFloat
4809{
4810}
4811
Eric Laurentbfb1b832013-01-07 09:53:42 -08004812AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4813 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurente93cc032016-05-05 10:15:10 -07004814 ThreadBase::type_t type, bool systemReady)
4815 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004816 // mLeftVolFloat, mRightVolFloat
4817{
4818}
4819
Eric Laurent81784c32012-11-19 14:55:58 -08004820AudioFlinger::DirectOutputThread::~DirectOutputThread()
4821{
4822}
4823
Eric Laurentbfb1b832013-01-07 09:53:42 -08004824void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
4825{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004826 float left, right;
4827
4828 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4829 left = right = 0;
4830 } else {
4831 float typeVolume = mStreamTypes[track->streamType()].volume;
4832 float v = mMasterVolume * typeVolume;
4833 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004834 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4835 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4836 if (left > GAIN_FLOAT_UNITY) {
4837 left = GAIN_FLOAT_UNITY;
4838 }
4839 left *= v;
4840 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4841 if (right > GAIN_FLOAT_UNITY) {
4842 right = GAIN_FLOAT_UNITY;
4843 }
4844 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004845 }
4846
4847 if (lastTrack) {
4848 if (left != mLeftVolFloat || right != mRightVolFloat) {
4849 mLeftVolFloat = left;
4850 mRightVolFloat = right;
4851
4852 // Convert volumes from float to 8.24
4853 uint32_t vl = (uint32_t)(left * (1 << 24));
4854 uint32_t vr = (uint32_t)(right * (1 << 24));
4855
4856 // Delegate volume control to effect in track effect chain if needed
4857 // only one effect chain can be present on DirectOutputThread, so if
4858 // there is one, the track is connected to it
4859 if (!mEffectChains.isEmpty()) {
4860 mEffectChains[0]->setVolume_l(&vl, &vr);
4861 left = (float)vl / (1 << 24);
4862 right = (float)vr / (1 << 24);
4863 }
4864 if (mOutput->stream->set_volume) {
4865 mOutput->stream->set_volume(mOutput->stream, left, right);
4866 }
4867 }
4868 }
4869}
4870
Phil Burk43b4dcc2015-06-09 16:53:44 -07004871void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
4872{
4873 sp<Track> previousTrack = mPreviousTrack.promote();
4874 sp<Track> latestTrack = mLatestActiveTrack.promote();
4875
Eric Laurent0f0631e2015-07-06 18:01:25 -07004876 if (previousTrack != 0 && latestTrack != 0) {
4877 if (mType == DIRECT) {
4878 if (previousTrack.get() != latestTrack.get()) {
4879 mFlushPending = true;
4880 }
4881 } else /* mType == OFFLOAD */ {
4882 if (previousTrack->sessionId() != latestTrack->sessionId()) {
4883 mFlushPending = true;
4884 }
4885 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004886 }
4887 PlaybackThread::onAddNewTrack_l();
4888}
Eric Laurentbfb1b832013-01-07 09:53:42 -08004889
Eric Laurent81784c32012-11-19 14:55:58 -08004890AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4891 Vector< sp<Track> > *tracksToRemove
4892)
4893{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004894 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004895 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004896 bool doHwPause = false;
4897 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004898
4899 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07004900 for (size_t i = 0; i < count; i++) {
4901 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08004902 // The track died recently
4903 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004904 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08004905 }
4906
Phil Burk43b4dcc2015-06-09 16:53:44 -07004907 if (t->isInvalid()) {
4908 ALOGW("An invalidated track shouldn't be in active list");
4909 tracksToRemove->add(t);
4910 continue;
4911 }
4912
Eric Laurent81784c32012-11-19 14:55:58 -08004913 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004914#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08004915 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004916#endif
Eric Laurentfd477972013-10-25 18:10:40 -07004917 // Only consider last track started for volume and mixer state control.
4918 // In theory an older track could underrun and restart after the new one starts
4919 // but as we only care about the transition phase between two tracks on a
4920 // direct output, it is not a problem to ignore the underrun case.
4921 sp<Track> l = mLatestActiveTrack.promote();
4922 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004923
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004924 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004925 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004926 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004927 doHwPause = true;
4928 mHwPaused = true;
4929 }
4930 tracksToRemove->add(track);
4931 } else if (track->isFlushPending()) {
4932 track->flushAck();
4933 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004934 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004935 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004936 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004937 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07004938 if (last) {
4939 mLeftVolFloat = mRightVolFloat = -1.0;
4940 if (mHwPaused) {
4941 doHwResume = true;
4942 mHwPaused = false;
4943 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004944 }
4945 }
4946
Eric Laurent81784c32012-11-19 14:55:58 -08004947 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004948 // for all its buffers to be filled before processing it.
4949 // Allow draining the buffer in case the client
4950 // app does not call stop() and relies on underrun to stop:
4951 // hence the test on (track->mRetryCount > 1).
4952 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07004953 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08004954 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004955 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08004956 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004957 minFrames = mNormalFrameCount;
4958 } else {
4959 minFrames = 1;
4960 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004961
Eric Laurentab5cdba2014-06-09 17:22:27 -07004962 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4963 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004964 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004965 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004966
4967 if (track->mFillingUpStatus == Track::FS_FILLED) {
4968 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07004969 if (last) {
4970 // make sure processVolume_l() will apply new volume even if 0
4971 mLeftVolFloat = mRightVolFloat = -1.0;
4972 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004973 if (!mHwSupportsPause) {
4974 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004975 }
4976 }
4977
4978 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004979 processVolume_l(track, last);
4980 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004981 sp<Track> previousTrack = mPreviousTrack.promote();
4982 if (previousTrack != 0) {
4983 if (track != previousTrack.get()) {
4984 // Flush any data still being written from last track
4985 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07004986 // Invalidate previous track to force a seek when resuming.
4987 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004988 }
4989 }
4990 mPreviousTrack = track;
4991
Eric Laurentd595b7c2013-04-03 17:27:56 -07004992 // reset retry count
4993 track->mRetryCount = kMaxTrackRetriesDirect;
4994 mActiveTrack = t;
4995 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07004996 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004997 doHwResume = true;
4998 mHwPaused = false;
4999 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005000 }
Eric Laurent81784c32012-11-19 14:55:58 -08005001 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07005002 // clear effect chain input buffer if the last active track started underruns
5003 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07005004 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08005005 mEffectChains[0]->clearInputBuffer();
5006 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005007 if (track->isStopping_1()) {
5008 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07005009 if (last && mHwPaused) {
5010 doHwResume = true;
5011 mHwPaused = false;
5012 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005013 }
5014 if ((track->sharedBuffer() != 0) || track->isStopped() ||
5015 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005016 // We have consumed all the buffers of this track.
5017 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07005018 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08005019 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005020 audioHALFrames = (latency_l() * mSampleRate) / 1000;
5021 } else {
5022 audioHALFrames = 0;
5023 }
5024
Andy Hung818e7a32016-02-16 18:08:07 -08005025 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07005026 if (mStandby || !last ||
5027 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005028 if (track->isStopping_2()) {
5029 track->mState = TrackBase::STOPPED;
5030 }
Eric Laurent81784c32012-11-19 14:55:58 -08005031 if (track->isStopped()) {
5032 track->reset();
5033 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005034 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08005035 }
5036 } else {
5037 // No buffers for this track. Give it a few chances to
5038 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07005039 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08005040 if (--(track->mRetryCount) <= 0) {
5041 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07005042 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005043 // indicate to client process that the track was disabled because of underrun;
5044 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005045 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005046 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07005047 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
5048 "minFrames = %u, mFormat = %#x",
5049 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08005050 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07005051 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005052 doHwPause = true;
5053 mHwPaused = true;
5054 }
Eric Laurent81784c32012-11-19 14:55:58 -08005055 }
5056 }
5057 }
5058 }
5059
Eric Laurentd1f69b02014-12-15 14:33:13 -08005060 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07005061 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005062 for (size_t i = 0; i < mTracks.size(); i++) {
5063 if (mTracks[i]->isFlushPending()) {
5064 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005065 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005066 }
5067 }
5068 }
5069
5070 // make sure the pause/flush/resume sequence is executed in the right order.
5071 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5072 // before flush and then resume HW. This can happen in case of pause/flush/resume
5073 // if resume is received before pause is executed.
5074 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07005075 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005076 mOutput->stream->pause(mOutput->stream);
5077 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005078 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005079 flushHw_l();
5080 }
5081 if (mHwSupportsPause && !mStandby && doHwResume) {
5082 mOutput->stream->resume(mOutput->stream);
5083 }
Eric Laurent81784c32012-11-19 14:55:58 -08005084 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005085 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005086
5087 return mixerStatus;
5088}
5089
5090void AudioFlinger::DirectOutputThread::threadLoop_mix()
5091{
Eric Laurent81784c32012-11-19 14:55:58 -08005092 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08005093 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005094 // output audio to hardware
5095 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07005096 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005097 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08005098 status_t status = mActiveTrack->getNextBuffer(&buffer);
5099 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08005100 // no need to pad with 0 for compressed audio
5101 if (audio_has_proportional_frames(mFormat)) {
5102 memset(curBuf, 0, frameCount * mFrameSize);
5103 }
Eric Laurent81784c32012-11-19 14:55:58 -08005104 break;
5105 }
5106 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
5107 frameCount -= buffer.frameCount;
5108 curBuf += buffer.frameCount * mFrameSize;
5109 mActiveTrack->releaseBuffer(&buffer);
5110 }
Andy Hung2098f272014-02-27 14:00:06 -08005111 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005112 mSleepTimeUs = 0;
5113 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005114 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005115}
5116
5117void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
5118{
Eric Laurentd1f69b02014-12-15 14:33:13 -08005119 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005120 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005121 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005122 return;
5123 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005124 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005125 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurente93cc032016-05-05 10:15:10 -07005126 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005127 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005128 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005129 }
Phil Burkfdb3c072016-02-09 10:47:02 -08005130 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08005131 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005132 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005133 }
5134}
5135
Eric Laurentd1f69b02014-12-15 14:33:13 -08005136void AudioFlinger::DirectOutputThread::threadLoop_exit()
5137{
5138 {
5139 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005140 for (size_t i = 0; i < mTracks.size(); i++) {
5141 if (mTracks[i]->isFlushPending()) {
5142 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005143 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005144 }
5145 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005146 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005147 flushHw_l();
5148 }
5149 }
5150 PlaybackThread::threadLoop_exit();
5151}
5152
5153// must be called with thread mutex locked
5154bool AudioFlinger::DirectOutputThread::shouldStandby_l()
5155{
5156 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07005157 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005158
vivek mehta9cd7ad12016-03-17 00:18:29 -07005159 if ((mType == DIRECT) && audio_is_linear_pcm(mFormat) && !usesHwAvSync()) {
5160 return !mStandby;
5161 }
5162
Eric Laurentd1f69b02014-12-15 14:33:13 -08005163 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
5164 // after a timeout and we will enter standby then.
5165 if (mTracks.size() > 0) {
5166 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07005167 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
5168 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005169 }
5170
Eric Laurent5cff4032015-05-26 13:49:58 -07005171 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08005172}
5173
Eric Laurent81784c32012-11-19 14:55:58 -08005174// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005175int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Eric Laurentad7dd962016-09-22 12:38:37 -07005176 audio_format_t format __unused, audio_session_t sessionId __unused, uid_t uid)
Eric Laurent81784c32012-11-19 14:55:58 -08005177{
Eric Laurentad7dd962016-09-22 12:38:37 -07005178 if (trackCountForUid_l(uid) > (PlaybackThread::kMaxTracksPerUid - 1)) {
5179 return -1;
5180 }
Eric Laurent81784c32012-11-19 14:55:58 -08005181 return 0;
5182}
5183
5184// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005185void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005186{
5187}
5188
Eric Laurent10351942014-05-08 18:49:52 -07005189// checkForNewParameter_l() must be called with ThreadBase::mLock held
5190bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
5191 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005192{
5193 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005194 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005195
Eric Laurent10351942014-05-08 18:49:52 -07005196 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005197
Eric Laurent10351942014-05-08 18:49:52 -07005198 AudioParameter param = AudioParameter(keyValuePair);
5199 int value;
5200 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5201 // forward device change to effects that have requested to be
5202 // aware of attached audio device.
5203 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005204 a2dpDeviceChanged =
5205 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005206 mOutDevice = value;
5207 for (size_t i = 0; i < mEffectChains.size(); i++) {
5208 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07005209 }
5210 }
Eric Laurent81784c32012-11-19 14:55:58 -08005211 }
Eric Laurent10351942014-05-08 18:49:52 -07005212 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5213 // do not accept frame count changes if tracks are open as the track buffer
5214 // size depends on frame count and correct behavior would not be garantied
5215 // if frame count is changed after track creation
5216 if (!mTracks.isEmpty()) {
5217 status = INVALID_OPERATION;
5218 } else {
5219 reconfig = true;
5220 }
5221 }
5222 if (status == NO_ERROR) {
5223 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
5224 keyValuePair.string());
5225 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005226 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005227 mStandby = true;
5228 mBytesWritten = 0;
5229 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
5230 keyValuePair.string());
5231 }
5232 if (status == NO_ERROR && reconfig) {
5233 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07005234 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005235 }
5236 }
5237
Eric Laurent42537be2016-01-08 17:16:42 -08005238 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005239}
5240
5241uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
5242{
5243 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005244 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005245 time = PlaybackThread::activeSleepTimeUs();
5246 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005247 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005248 }
5249 return time;
5250}
5251
5252uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
5253{
5254 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005255 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005256 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
5257 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005258 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005259 }
5260 return time;
5261}
5262
5263uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
5264{
5265 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005266 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005267 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
5268 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005269 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005270 }
5271 return time;
5272}
5273
5274void AudioFlinger::DirectOutputThread::cacheParameters_l()
5275{
5276 PlaybackThread::cacheParameters_l();
5277
5278 // use shorter standby delay as on normal output to release
5279 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07005280 // no delay on outputs with HW A/V sync
5281 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005282 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08005283 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005284 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07005285 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005286 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07005287 }
Eric Laurent81784c32012-11-19 14:55:58 -08005288}
5289
Eric Laurente659ef42014-09-29 13:06:46 -07005290void AudioFlinger::DirectOutputThread::flushHw_l()
5291{
Phil Burk062e67a2015-02-11 13:40:50 -08005292 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08005293 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005294 mFlushPending = false;
Eric Laurente659ef42014-09-29 13:06:46 -07005295}
5296
Eric Laurent81784c32012-11-19 14:55:58 -08005297// ----------------------------------------------------------------------------
5298
Eric Laurentbfb1b832013-01-07 09:53:42 -08005299AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07005300 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005301 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07005302 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07005303 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005304 mDrainSequence(0),
5305 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005306{
5307}
5308
5309AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
5310{
5311}
5312
5313void AudioFlinger::AsyncCallbackThread::onFirstRef()
5314{
5315 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
5316}
5317
5318bool AudioFlinger::AsyncCallbackThread::threadLoop()
5319{
5320 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005321 uint32_t writeAckSequence;
5322 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005323 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005324
5325 {
5326 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005327 while (!((mWriteAckSequence & 1) ||
5328 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005329 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005330 exitPending())) {
5331 mWaitWorkCV.wait(mLock);
5332 }
5333
Eric Laurentbfb1b832013-01-07 09:53:42 -08005334 if (exitPending()) {
5335 break;
5336 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005337 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
5338 mWriteAckSequence, mDrainSequence);
5339 writeAckSequence = mWriteAckSequence;
5340 mWriteAckSequence &= ~1;
5341 drainSequence = mDrainSequence;
5342 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005343 asyncError = mAsyncError;
5344 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005345 }
5346 {
Eric Laurent4de95592013-09-26 15:28:21 -07005347 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
5348 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005349 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005350 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005351 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005352 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005353 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005354 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005355 if (asyncError) {
5356 playbackThread->onAsyncError();
5357 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005358 }
5359 }
5360 }
5361 return false;
5362}
5363
5364void AudioFlinger::AsyncCallbackThread::exit()
5365{
5366 ALOGV("AsyncCallbackThread::exit");
5367 Mutex::Autolock _l(mLock);
5368 requestExit();
5369 mWaitWorkCV.broadcast();
5370}
5371
Eric Laurent3b4529e2013-09-05 18:09:19 -07005372void AudioFlinger::AsyncCallbackThread::setWriteBlocked(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 mWriteAckSequence = sequence << 1;
5377}
5378
5379void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5380{
5381 Mutex::Autolock _l(mLock);
5382 // ignore unexpected callbacks
5383 if (mWriteAckSequence & 2) {
5384 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005385 mWaitWorkCV.signal();
5386 }
5387}
5388
Eric Laurent3b4529e2013-09-05 18:09:19 -07005389void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005390{
5391 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005392 // bit 0 is cleared
5393 mDrainSequence = sequence << 1;
5394}
5395
5396void AudioFlinger::AsyncCallbackThread::resetDraining()
5397{
5398 Mutex::Autolock _l(mLock);
5399 // ignore unexpected callbacks
5400 if (mDrainSequence & 2) {
5401 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005402 mWaitWorkCV.signal();
5403 }
5404}
5405
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005406void AudioFlinger::AsyncCallbackThread::setAsyncError()
5407{
5408 Mutex::Autolock _l(mLock);
5409 mAsyncError = true;
5410 mWaitWorkCV.signal();
5411}
5412
Eric Laurentbfb1b832013-01-07 09:53:42 -08005413
5414// ----------------------------------------------------------------------------
5415AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07005416 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
5417 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07005418 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
5419 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005420{
Eric Laurentfd477972013-10-25 18:10:40 -07005421 //FIXME: mStandby should be set to true by ThreadBase constructor
5422 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07005423 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005424}
5425
Eric Laurentbfb1b832013-01-07 09:53:42 -08005426void AudioFlinger::OffloadThread::threadLoop_exit()
5427{
5428 if (mFlushPending || mHwPaused) {
5429 // If a flush is pending or track was paused, just discard buffered data
5430 flushHw_l();
5431 } else {
5432 mMixerStatus = MIXER_DRAIN_ALL;
5433 threadLoop_drain();
5434 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005435 if (mUseAsyncWrite) {
5436 ALOG_ASSERT(mCallbackThread != 0);
5437 mCallbackThread->exit();
5438 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005439 PlaybackThread::threadLoop_exit();
5440}
5441
5442AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5443 Vector< sp<Track> > *tracksToRemove
5444)
5445{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005446 size_t count = mActiveTracks.size();
5447
5448 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005449 bool doHwPause = false;
5450 bool doHwResume = false;
5451
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005452 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07005453
Eric Laurentbfb1b832013-01-07 09:53:42 -08005454 // find out which tracks need to be processed
5455 for (size_t i = 0; i < count; i++) {
5456 sp<Track> t = mActiveTracks[i].promote();
5457 // The track died recently
5458 if (t == 0) {
5459 continue;
5460 }
5461 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005462#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08005463 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005464#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005465 // Only consider last track started for volume and mixer state control.
5466 // In theory an older track could underrun and restart after the new one starts
5467 // but as we only care about the transition phase between two tracks on a
5468 // direct output, it is not a problem to ignore the underrun case.
5469 sp<Track> l = mLatestActiveTrack.promote();
5470 bool last = l.get() == track;
5471
Haynes Mathew George7844f672014-01-15 12:32:55 -08005472 if (track->isInvalid()) {
5473 ALOGW("An invalidated track shouldn't be in active list");
5474 tracksToRemove->add(track);
5475 continue;
5476 }
5477
5478 if (track->mState == TrackBase::IDLE) {
5479 ALOGW("An idle track shouldn't be in active list");
5480 continue;
5481 }
5482
Eric Laurentbfb1b832013-01-07 09:53:42 -08005483 if (track->isPausing()) {
5484 track->setPaused();
5485 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005486 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005487 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005488 mHwPaused = true;
5489 }
5490 // If we were part way through writing the mixbuffer to
5491 // the HAL we must save this until we resume
5492 // BUG - this will be wrong if a different track is made active,
5493 // in that case we want to discard the pending data in the
5494 // mixbuffer and tell the client to present it again when the
5495 // track is resumed
5496 mPausedWriteLength = mCurrentWriteLength;
5497 mPausedBytesRemaining = mBytesRemaining;
5498 mBytesRemaining = 0; // stop writing
5499 }
5500 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005501 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005502 if (track->isStopping_1()) {
5503 track->mRetryCount = kMaxTrackStopRetriesOffload;
5504 } else {
5505 track->mRetryCount = kMaxTrackRetriesOffload;
5506 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08005507 track->flushAck();
5508 if (last) {
5509 mFlushPending = true;
5510 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005511 } else if (track->isResumePending()){
5512 track->resumeAck();
5513 if (last) {
5514 if (mPausedBytesRemaining) {
5515 // Need to continue write that was interrupted
5516 mCurrentWriteLength = mPausedWriteLength;
5517 mBytesRemaining = mPausedBytesRemaining;
5518 mPausedBytesRemaining = 0;
5519 }
5520 if (mHwPaused) {
5521 doHwResume = true;
5522 mHwPaused = false;
5523 // threadLoop_mix() will handle the case that we need to
5524 // resume an interrupted write
5525 }
5526 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005527 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005528
Eric Laurent3df841a2016-07-15 15:15:40 -07005529 mLeftVolFloat = mRightVolFloat = -1.0;
5530
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005531 // Do not handle new data in this iteration even if track->framesReady()
5532 mixerStatus = MIXER_TRACKS_ENABLED;
5533 }
5534 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005535 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005536 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005537 if (track->mFillingUpStatus == Track::FS_FILLED) {
5538 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005539 if (last) {
5540 // make sure processVolume_l() will apply new volume even if 0
5541 mLeftVolFloat = mRightVolFloat = -1.0;
5542 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005543 }
5544
5545 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005546 sp<Track> previousTrack = mPreviousTrack.promote();
5547 if (previousTrack != 0) {
5548 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005549 // Flush any data still being written from last track
5550 mBytesRemaining = 0;
5551 if (mPausedBytesRemaining) {
5552 // Last track was paused so we also need to flush saved
5553 // mixbuffer state and invalidate track so that it will
5554 // re-submit that unwritten data when it is next resumed
5555 mPausedBytesRemaining = 0;
5556 // Invalidate is a bit drastic - would be more efficient
5557 // to have a flag to tell client that some of the
5558 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005559 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005560 }
5561 // flush data already sent to the DSP if changing audio session as audio
5562 // comes from a different source. Also invalidate previous track to force a
5563 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005564 if (previousTrack->sessionId() != track->sessionId()) {
5565 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005566 }
5567 }
5568 }
5569 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005570 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07005571 if (track->isStopping_1()) {
5572 track->mRetryCount = kMaxTrackStopRetriesOffload;
5573 } else {
5574 track->mRetryCount = kMaxTrackRetriesOffload;
5575 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005576 mActiveTrack = t;
5577 mixerStatus = MIXER_TRACKS_READY;
5578 }
5579 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005580 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005581 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005582 if (--(track->mRetryCount) <= 0) {
5583 // Hardware buffer can hold a large amount of audio so we must
5584 // wait for all current track's data to drain before we say
5585 // that the track is stopped.
5586 if (mBytesRemaining == 0) {
5587 // Only start draining when all data in mixbuffer
5588 // has been written
5589 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5590 track->mState = TrackBase::STOPPING_2; // so presentation completes after
5591 // drain do not drain if no data was ever sent to HAL (mStandby == true)
5592 if (last && !mStandby) {
5593 // do not modify drain sequence if we are already draining. This happens
5594 // when resuming from pause after drain.
5595 if ((mDrainSequence & 1) == 0) {
5596 mSleepTimeUs = 0;
5597 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
5598 mixerStatus = MIXER_DRAIN_TRACK;
5599 mDrainSequence += 2;
5600 }
5601 if (mHwPaused) {
5602 // It is possible to move from PAUSED to STOPPING_1 without
5603 // a resume so we must ensure hardware is running
5604 doHwResume = true;
5605 mHwPaused = false;
5606 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005607 }
5608 }
Eric Laurente93cc032016-05-05 10:15:10 -07005609 } else if (last) {
5610 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
5611 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005612 }
5613 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005614 // Drain has completed or we are in standby, signal presentation complete
5615 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005616 track->mState = TrackBase::STOPPED;
5617 size_t audioHALFrames =
5618 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005619 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005620 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005621 track->presentationComplete(framesWritten, audioHALFrames);
5622 track->reset();
5623 tracksToRemove->add(track);
5624 }
5625 } else {
5626 // No buffers for this track. Give it a few chances to
5627 // fill a buffer, then remove it from active list.
5628 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07005629 bool running = false;
5630 if (mOutput->stream->get_presentation_position != nullptr) {
5631 uint64_t position = 0;
5632 struct timespec unused;
5633 // The running check restarts the retry counter at least once.
5634 int ret = mOutput->stream->get_presentation_position(
5635 mOutput->stream, &position, &unused);
5636 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
5637 running = true;
5638 mOffloadUnderrunPosition = position;
5639 }
5640 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
5641 (long long)position, (long long)mOffloadUnderrunPosition);
5642 }
5643 if (running) { // still running, give us more time.
5644 track->mRetryCount = kMaxTrackRetriesOffload;
5645 } else {
5646 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5647 track->name());
5648 tracksToRemove->add(track);
5649 // indicate to client process that the track was disabled because of underrun;
5650 // it will then automatically call start() when data is available
5651 track->disable();
5652 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005653 } else if (last){
5654 mixerStatus = MIXER_TRACKS_ENABLED;
5655 }
5656 }
5657 }
5658 // compute volume for this track
5659 processVolume_l(track, last);
5660 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005661
Eric Laurentea0fade2013-10-04 16:23:48 -07005662 // make sure the pause/flush/resume sequence is executed in the right order.
5663 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5664 // before flush and then resume HW. This can happen in case of pause/flush/resume
5665 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07005666 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07005667 mOutput->stream->pause(mOutput->stream);
5668 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005669 if (mFlushPending) {
5670 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005671 }
Eric Laurentfd477972013-10-25 18:10:40 -07005672 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07005673 mOutput->stream->resume(mOutput->stream);
5674 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005675
Eric Laurentbfb1b832013-01-07 09:53:42 -08005676 // remove all the tracks that need to be...
5677 removeTracks_l(*tracksToRemove);
5678
5679 return mixerStatus;
5680}
5681
Eric Laurentbfb1b832013-01-07 09:53:42 -08005682// must be called with thread mutex locked
5683bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5684{
Eric Laurent3b4529e2013-09-05 18:09:19 -07005685 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5686 mWriteAckSequence, mDrainSequence);
5687 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005688 return true;
5689 }
5690 return false;
5691}
5692
Eric Laurentbfb1b832013-01-07 09:53:42 -08005693bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5694{
5695 Mutex::Autolock _l(mLock);
5696 return waitingAsyncCallback_l();
5697}
5698
5699void AudioFlinger::OffloadThread::flushHw_l()
5700{
Eric Laurente659ef42014-09-29 13:06:46 -07005701 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005702 // Flush anything still waiting in the mixbuffer
5703 mCurrentWriteLength = 0;
5704 mBytesRemaining = 0;
5705 mPausedWriteLength = 0;
5706 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07005707 // reset bytes written count to reflect that DSP buffers are empty after flush.
5708 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07005709 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08005710
Eric Laurentbfb1b832013-01-07 09:53:42 -08005711 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005712 // discard any pending drain or write ack by incrementing sequence
5713 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5714 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005715 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005716 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5717 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005718 }
5719}
5720
Haynes Mathew George05317d22016-05-03 16:34:26 -07005721void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
5722{
5723 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07005724 if (PlaybackThread::invalidateTracks_l(streamType)) {
5725 mFlushPending = true;
5726 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07005727}
5728
Eric Laurentbfb1b832013-01-07 09:53:42 -08005729// ----------------------------------------------------------------------------
5730
Eric Laurent81784c32012-11-19 14:55:58 -08005731AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005732 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005733 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07005734 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08005735 mWaitTimeMs(UINT_MAX)
5736{
5737 addOutputTrack(mainThread);
5738}
5739
5740AudioFlinger::DuplicatingThread::~DuplicatingThread()
5741{
5742 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5743 mOutputTracks[i]->destroy();
5744 }
5745}
5746
5747void AudioFlinger::DuplicatingThread::threadLoop_mix()
5748{
5749 // mix buffers...
5750 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08005751 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08005752 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005753 if (mMixerBufferValid) {
5754 memset(mMixerBuffer, 0, mMixerBufferSize);
5755 } else {
5756 memset(mSinkBuffer, 0, mSinkBufferSize);
5757 }
Eric Laurent81784c32012-11-19 14:55:58 -08005758 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005759 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005760 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005761 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005762 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005763}
5764
5765void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5766{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005767 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005768 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005769 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005770 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005771 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005772 }
5773 } else if (mBytesWritten != 0) {
5774 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5775 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005776 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005777 } else {
5778 // flush remaining overflow buffers in output tracks
5779 writeFrames = 0;
5780 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005781 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005782 }
5783}
5784
Eric Laurentbfb1b832013-01-07 09:53:42 -08005785ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005786{
5787 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005788 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005789 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005790 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005791 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005792}
5793
5794void AudioFlinger::DuplicatingThread::threadLoop_standby()
5795{
5796 // DuplicatingThread implements standby by stopping all tracks
5797 for (size_t i = 0; i < outputTracks.size(); i++) {
5798 outputTracks[i]->stop();
5799 }
5800}
5801
5802void AudioFlinger::DuplicatingThread::saveOutputTracks()
5803{
5804 outputTracks = mOutputTracks;
5805}
5806
5807void AudioFlinger::DuplicatingThread::clearOutputTracks()
5808{
5809 outputTracks.clear();
5810}
5811
5812void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5813{
5814 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005815 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5816 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5817 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5818 const size_t frameCount =
5819 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5820 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5821 // from different OutputTracks and their associated MixerThreads (e.g. one may
5822 // nearly empty and the other may be dropping data).
5823
5824 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005825 this,
5826 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005827 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005828 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005829 frameCount,
5830 IPCThreadState::self()->getCallingUid());
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07005831 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
5832 if (status != NO_ERROR) {
5833 ALOGE("addOutputTrack() initCheck failed %d", status);
5834 return;
Eric Laurent81784c32012-11-19 14:55:58 -08005835 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07005836 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
5837 mOutputTracks.add(outputTrack);
5838 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
5839 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005840}
5841
5842void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5843{
5844 Mutex::Autolock _l(mLock);
5845 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5846 if (mOutputTracks[i]->thread() == thread) {
5847 mOutputTracks[i]->destroy();
5848 mOutputTracks.removeAt(i);
5849 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07005850 if (thread->getOutput() == mOutput) {
5851 mOutput = NULL;
5852 }
Eric Laurent81784c32012-11-19 14:55:58 -08005853 return;
5854 }
5855 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07005856 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005857}
5858
5859// caller must hold mLock
5860void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5861{
5862 mWaitTimeMs = UINT_MAX;
5863 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5864 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5865 if (strong != 0) {
5866 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5867 if (waitTimeMs < mWaitTimeMs) {
5868 mWaitTimeMs = waitTimeMs;
5869 }
5870 }
5871 }
5872}
5873
5874
5875bool AudioFlinger::DuplicatingThread::outputsReady(
5876 const SortedVector< sp<OutputTrack> > &outputTracks)
5877{
5878 for (size_t i = 0; i < outputTracks.size(); i++) {
5879 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5880 if (thread == 0) {
5881 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5882 outputTracks[i].get());
5883 return false;
5884 }
5885 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5886 // see note at standby() declaration
5887 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5888 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5889 thread.get());
5890 return false;
5891 }
5892 }
5893 return true;
5894}
5895
5896uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5897{
5898 return (mWaitTimeMs * 1000) / 2;
5899}
5900
5901void AudioFlinger::DuplicatingThread::cacheParameters_l()
5902{
5903 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5904 updateWaitTime_l();
5905
5906 MixerThread::cacheParameters_l();
5907}
5908
5909// ----------------------------------------------------------------------------
5910// Record
5911// ----------------------------------------------------------------------------
5912
5913AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5914 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005915 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005916 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07005917 audio_devices_t inDevice,
5918 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08005919#ifdef TEE_SINK
5920 , const sp<NBAIO_Sink>& teeSink
5921#endif
5922 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07005923 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005924 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005925 // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005926 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005927#ifdef TEE_SINK
5928 , mTeeSink(teeSink)
5929#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005930 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5931 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005932 // mFastCapture below
5933 , mFastCaptureFutex(0)
5934 // mInputSource
5935 // mPipeSink
5936 // mPipeSource
5937 , mPipeFramesP2(0)
5938 // mPipeMemory
5939 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005940 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005941{
Glenn Kastend7dca052015-03-05 16:05:54 -08005942 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5943 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08005944
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005945 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005946
5947 // create an NBAIO source for the HAL input stream, and negotiate
5948 mInputSource = new AudioStreamInSource(input->stream);
5949 size_t numCounterOffers = 0;
5950 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005951#if !LOG_NDEBUG
5952 ssize_t index =
5953#else
5954 (void)
5955#endif
5956 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005957 ALOG_ASSERT(index == 0);
5958
5959 // initialize fast capture depending on configuration
5960 bool initFastCapture;
5961 switch (kUseFastCapture) {
5962 case FastCapture_Never:
5963 initFastCapture = false;
5964 break;
5965 case FastCapture_Always:
5966 initFastCapture = true;
5967 break;
5968 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07005969 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005970 break;
5971 // case FastCapture_Dynamic:
5972 }
5973
5974 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07005975 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005976 NBAIO_Format format = mInputSource->format();
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005977 size_t pipeFramesP2 = roundup(mSampleRate / 25); // double-buffering of 20 ms each
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005978 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5979 void *pipeBuffer;
5980 const sp<MemoryDealer> roHeap(readOnlyHeap());
5981 sp<IMemory> pipeMemory;
5982 if ((roHeap == 0) ||
5983 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5984 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5985 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5986 goto failed;
5987 }
5988 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5989 memset(pipeBuffer, 0, pipeSize);
5990 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5991 const NBAIO_Format offers[1] = {format};
5992 size_t numCounterOffers = 0;
5993 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5994 ALOG_ASSERT(index == 0);
5995 mPipeSink = pipe;
5996 PipeReader *pipeReader = new PipeReader(*pipe);
5997 numCounterOffers = 0;
5998 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5999 ALOG_ASSERT(index == 0);
6000 mPipeSource = pipeReader;
6001 mPipeFramesP2 = pipeFramesP2;
6002 mPipeMemory = pipeMemory;
6003
6004 // create fast capture
6005 mFastCapture = new FastCapture();
6006 FastCaptureStateQueue *sq = mFastCapture->sq();
6007#ifdef STATE_QUEUE_DUMP
6008 // FIXME
6009#endif
6010 FastCaptureState *state = sq->begin();
6011 state->mCblk = NULL;
6012 state->mInputSource = mInputSource.get();
6013 state->mInputSourceGen++;
6014 state->mPipeSink = pipe;
6015 state->mPipeSinkGen++;
6016 state->mFrameCount = mFrameCount;
6017 state->mCommand = FastCaptureState::COLD_IDLE;
6018 // already done in constructor initialization list
6019 //mFastCaptureFutex = 0;
6020 state->mColdFutexAddr = &mFastCaptureFutex;
6021 state->mColdGen++;
6022 state->mDumpState = &mFastCaptureDumpState;
6023#ifdef TEE_SINK
6024 // FIXME
6025#endif
6026 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
6027 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
6028 sq->end();
6029 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6030
6031 // start the fast capture
6032 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
6033 pid_t tid = mFastCapture->getTid();
Glenn Kasten8379b722016-03-18 14:54:17 -07006034 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006035#ifdef AUDIO_WATCHDOG
6036 // FIXME
6037#endif
6038
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006039 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006040 }
6041failed: ;
6042
6043 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08006044}
6045
Eric Laurent81784c32012-11-19 14:55:58 -08006046AudioFlinger::RecordThread::~RecordThread()
6047{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006048 if (mFastCapture != 0) {
6049 FastCaptureStateQueue *sq = mFastCapture->sq();
6050 FastCaptureState *state = sq->begin();
6051 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6052 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6053 if (old == -1) {
6054 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6055 }
6056 }
6057 state->mCommand = FastCaptureState::EXIT;
6058 sq->end();
6059 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6060 mFastCapture->join();
6061 mFastCapture.clear();
6062 }
6063 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07006064 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07006065 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08006066}
6067
6068void AudioFlinger::RecordThread::onFirstRef()
6069{
Glenn Kastend7dca052015-03-05 16:05:54 -08006070 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08006071}
6072
Eric Laurent81784c32012-11-19 14:55:58 -08006073bool AudioFlinger::RecordThread::threadLoop()
6074{
Eric Laurent81784c32012-11-19 14:55:58 -08006075 nsecs_t lastWarning = 0;
6076
6077 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006078
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006079reacquire_wakelock:
6080 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08006081 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006082 {
6083 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006084 size_t size = mActiveTracks.size();
6085 activeTracksGen = mActiveTracksGen;
6086 if (size > 0) {
6087 // FIXME an arbitrary choice
6088 activeTrack = mActiveTracks[0];
6089 acquireWakeLock_l(activeTrack->uid());
6090 if (size > 1) {
6091 SortedVector<int> tmp;
6092 for (size_t i = 0; i < size; i++) {
6093 tmp.add(mActiveTracks[i]->uid());
6094 }
6095 updateWakeLockUids_l(tmp);
6096 }
6097 } else {
6098 acquireWakeLock_l(-1);
6099 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006100 }
6101
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006102 // used to request a deferred sleep, to be executed later while mutex is unlocked
6103 uint32_t sleepUs = 0;
6104
6105 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006106 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006107 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07006108
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006109 // activeTracks accumulates a copy of a subset of mActiveTracks
6110 Vector< sp<RecordTrack> > activeTracks;
6111
Glenn Kasten735f45f2014-08-18 15:51:59 -07006112 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006113 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07006114
Glenn Kasten735f45f2014-08-18 15:51:59 -07006115 // reference to a fast track which is about to be removed
6116 sp<RecordTrack> fastTrackToRemove;
6117
Eric Laurent81784c32012-11-19 14:55:58 -08006118 { // scope for mLock
6119 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08006120
Eric Laurent021cf962014-05-13 10:18:14 -07006121 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006122
Eric Laurent000a4192014-01-29 15:17:32 -08006123 // check exitPending here because checkForNewParameters_l() and
6124 // checkForNewParameters_l() can temporarily release mLock
6125 if (exitPending()) {
6126 break;
6127 }
6128
Eric Laurent5c25d562016-07-13 17:17:45 -07006129 // sleep with mutex unlocked
6130 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07006131 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07006132 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
6133 ATRACE_END();
6134 sleepUs = 0;
6135 continue;
6136 }
6137
Glenn Kasten2b806402013-11-20 16:37:38 -08006138 // if no active track(s), then standby and release wakelock
6139 size_t size = mActiveTracks.size();
6140 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07006141 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006142 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08006143 releaseWakeLock_l();
6144 ALOGV("RecordThread: loop stopping");
6145 // go to sleep
6146 mWaitWorkCV.wait(mLock);
6147 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006148 goto reacquire_wakelock;
6149 }
6150
Glenn Kasten2b806402013-11-20 16:37:38 -08006151 if (mActiveTracksGen != activeTracksGen) {
6152 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006153 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08006154 for (size_t i = 0; i < size; i++) {
6155 tmp.add(mActiveTracks[i]->uid());
6156 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006157 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08006158 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006159
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006160 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07006161 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006162 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07006163
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006164 activeTrack = mActiveTracks[i];
6165 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07006166 if (activeTrack->isFastTrack()) {
6167 ALOG_ASSERT(fastTrackToRemove == 0);
6168 fastTrackToRemove = activeTrack;
6169 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006170 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08006171 mActiveTracks.remove(activeTrack);
6172 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006173 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07006174 continue;
6175 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006176
6177 TrackBase::track_state activeTrackState = activeTrack->mState;
6178 switch (activeTrackState) {
6179
6180 case TrackBase::PAUSING:
6181 mActiveTracks.remove(activeTrack);
6182 mActiveTracksGen++;
6183 doBroadcast = true;
6184 size--;
6185 continue;
6186
6187 case TrackBase::STARTING_1:
6188 sleepUs = 10000;
6189 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07006190 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006191 continue;
6192
6193 case TrackBase::STARTING_2:
6194 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006195 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07006196 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07006197 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006198 break;
6199
6200 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07006201 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006202 break;
6203
6204 case TrackBase::IDLE:
6205 i++;
6206 continue;
6207
6208 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08006209 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07006210 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006211
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006212 activeTracks.add(activeTrack);
6213 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07006214
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006215 if (activeTrack->isFastTrack()) {
6216 ALOG_ASSERT(!mFastTrackAvail);
6217 ALOG_ASSERT(fastTrack == 0);
6218 fastTrack = activeTrack;
6219 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006220 }
Eric Laurent5c25d562016-07-13 17:17:45 -07006221
6222 if (allStopped) {
6223 standbyIfNotAlreadyInStandby();
6224 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006225 if (doBroadcast) {
6226 mStartStopCond.broadcast();
6227 }
6228
6229 // sleep if there are no active tracks to process
6230 if (activeTracks.size() == 0) {
6231 if (sleepUs == 0) {
6232 sleepUs = kRecordThreadSleepUs;
6233 }
6234 continue;
6235 }
6236 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07006237
Eric Laurent81784c32012-11-19 14:55:58 -08006238 lockEffectChains_l(effectChains);
6239 }
6240
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006241 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07006242
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006243 size_t size = effectChains.size();
6244 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006245 // thread mutex is not locked, but effect chain is locked
6246 effectChains[i]->process_l();
6247 }
6248
Glenn Kasten735f45f2014-08-18 15:51:59 -07006249 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006250 if (mFastCapture != 0) {
6251 FastCaptureStateQueue *sq = mFastCapture->sq();
6252 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07006253 bool didModify = false;
6254 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006255 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
6256 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
6257 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6258 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6259 if (old == -1) {
6260 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6261 }
6262 }
6263 state->mCommand = FastCaptureState::READ_WRITE;
6264#if 0 // FIXME
6265 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08006266 FastThreadDumpState::kSamplingNforLowRamDevice :
6267 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006268#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07006269 didModify = true;
6270 }
6271 audio_track_cblk_t *cblkOld = state->mCblk;
6272 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
6273 if (cblkNew != cblkOld) {
6274 state->mCblk = cblkNew;
6275 // block until acked if removing a fast track
6276 if (cblkOld != NULL) {
6277 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
6278 }
6279 didModify = true;
6280 }
6281 sq->end(didModify);
6282 if (didModify) {
6283 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006284#if 0
6285 if (kUseFastCapture == FastCapture_Dynamic) {
6286 mNormalSource = mPipeSource;
6287 }
6288#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006289 }
6290 }
6291
Glenn Kasten735f45f2014-08-18 15:51:59 -07006292 // now run the fast track destructor with thread mutex unlocked
6293 fastTrackToRemove.clear();
6294
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006295 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
6296 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
6297 // slow, then this RecordThread will overrun by not calling HAL read often enough.
6298 // If destination is non-contiguous, first read past the nominal end of buffer, then
6299 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006300
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006301 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006302 ssize_t framesRead;
6303
6304 // If an NBAIO source is present, use it to read the normal capture's data
6305 if (mPipeSource != 0) {
6306 size_t framesToRead = mBufferSize / mFrameSize;
Andy Hung57446612015-04-19 23:56:46 -07006307 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
Glenn Kastend79072e2016-01-06 08:41:20 -08006308 framesToRead);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006309 if (framesRead == 0) {
6310 // since pipe is non-blocking, simulate blocking input
6311 sleepUs = (framesToRead * 1000000LL) / mSampleRate;
6312 }
6313 // otherwise use the HAL / AudioStreamIn directly
6314 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07006315 ATRACE_BEGIN("read");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006316 ssize_t bytesRead = mInput->stream->read(mInput->stream,
Andy Hung57446612015-04-19 23:56:46 -07006317 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize);
Glenn Kastenec6a7032016-03-14 07:40:23 -07006318 ATRACE_END();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006319 if (bytesRead < 0) {
6320 framesRead = bytesRead;
6321 } else {
6322 framesRead = bytesRead / mFrameSize;
6323 }
6324 }
6325
Andy Hung3f0c9022016-01-15 17:49:46 -08006326 // Update server timestamp with server stats
6327 // systemTime() is optional if the hardware supports timestamps.
6328 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
6329 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6330
6331 // Update server timestamp with kernel stats
Andy Hung69ce44d2016-07-18 12:14:25 -07006332 if (mInput->stream->get_capture_position != nullptr
6333 && mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08006334 int64_t position, time;
6335 int ret = mInput->stream->get_capture_position(mInput->stream, &position, &time);
6336 if (ret == NO_ERROR) {
6337 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
6338 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
6339 // Note: In general record buffers should tend to be empty in
6340 // a properly running pipeline.
6341 //
6342 // Also, it is not advantageous to call get_presentation_position during the read
6343 // as the read obtains a lock, preventing the timestamp call from executing.
6344 }
6345 }
6346 // Use this to track timestamp information
6347 // ALOGD("%s", mTimestamp.toString().c_str());
6348
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006349 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006350 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006351 // Force input into standby so that it tries to recover at next read attempt
6352 inputStandBy();
6353 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006354 }
6355 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006356 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006357 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006358 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006359
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006360 if (mTeeSink != 0) {
Andy Hung57446612015-04-19 23:56:46 -07006361 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006362 }
6363 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006364 {
6365 size_t part1 = mRsmpInFramesP2 - rear;
6366 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07006367 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006368 (framesRead - part1) * mFrameSize);
6369 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006370 }
6371 rear = mRsmpInRear += framesRead;
6372
6373 size = activeTracks.size();
6374 // loop over each active track
6375 for (size_t i = 0; i < size; i++) {
6376 activeTrack = activeTracks[i];
6377
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006378 // skip fast tracks, as those are handled directly by FastCapture
6379 if (activeTrack->isFastTrack()) {
6380 continue;
6381 }
6382
Andy Hung73c02e42015-03-29 01:13:58 -07006383 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07006384 // TODO: Update the activeTrack buffer converter in case of reconfigure.
6385
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006386 enum {
6387 OVERRUN_UNKNOWN,
6388 OVERRUN_TRUE,
6389 OVERRUN_FALSE
6390 } overrun = OVERRUN_UNKNOWN;
6391
6392 // loop over getNextBuffer to handle circular sink
6393 for (;;) {
6394
6395 activeTrack->mSink.frameCount = ~0;
6396 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
6397 size_t framesOut = activeTrack->mSink.frameCount;
6398 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
6399
Andy Hung73c02e42015-03-29 01:13:58 -07006400 // check available frames and handle overrun conditions
6401 // if the record track isn't draining fast enough.
6402 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006403 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07006404 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
6405 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006406 overrun = OVERRUN_TRUE;
6407 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006408 if (framesOut == 0 || framesIn == 0) {
6409 break;
6410 }
6411
Andy Hung6770c6f2015-04-07 13:43:36 -07006412 // Don't allow framesOut to be larger than what is possible with resampling
6413 // from framesIn.
6414 // This isn't strictly necessary but helps limit buffer resizing in
6415 // RecordBufferConverter. TODO: remove when no longer needed.
6416 framesOut = min(framesOut,
6417 destinationFramesPossible(
6418 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07006419 // process frames from the RecordThread buffer provider to the RecordTrack buffer
6420 framesOut = activeTrack->mRecordBufferConverter->convert(
6421 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006422
6423 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
6424 overrun = OVERRUN_FALSE;
6425 }
6426
6427 if (activeTrack->mFramesToDrop == 0) {
6428 if (framesOut > 0) {
6429 activeTrack->mSink.frameCount = framesOut;
6430 activeTrack->releaseBuffer(&activeTrack->mSink);
6431 }
6432 } else {
6433 // FIXME could do a partial drop of framesOut
6434 if (activeTrack->mFramesToDrop > 0) {
6435 activeTrack->mFramesToDrop -= framesOut;
6436 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006437 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006438 }
6439 } else {
6440 activeTrack->mFramesToDrop += framesOut;
6441 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
6442 activeTrack->mSyncStartEvent->isCancelled()) {
6443 ALOGW("Synced record %s, session %d, trigger session %d",
6444 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
6445 activeTrack->sessionId(),
6446 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08006447 activeTrack->mSyncStartEvent->triggerSession() :
6448 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006449 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006450 }
6451 }
6452 }
6453
6454 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006455 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006456 }
6457 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006458
6459 switch (overrun) {
6460 case OVERRUN_TRUE:
6461 // client isn't retrieving buffers fast enough
6462 if (!activeTrack->setOverflow()) {
6463 nsecs_t now = systemTime();
6464 // FIXME should lastWarning per track?
6465 if ((now - lastWarning) > kWarningThrottleNs) {
6466 ALOGW("RecordThread: buffer overflow");
6467 lastWarning = now;
6468 }
6469 }
6470 break;
6471 case OVERRUN_FALSE:
6472 activeTrack->clearOverflow();
6473 break;
6474 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006475 break;
6476 }
6477
Andy Hung3f0c9022016-01-15 17:49:46 -08006478 // update frame information and push timestamp out
6479 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08006480 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08006481 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
6482 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006483 }
6484
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006485unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08006486 // enable changes in effect chain
6487 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006488 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08006489 }
6490
Glenn Kasten93e471f2013-08-19 08:40:07 -07006491 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08006492
6493 {
6494 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07006495 for (size_t i = 0; i < mTracks.size(); i++) {
6496 sp<RecordTrack> track = mTracks[i];
6497 track->invalidate();
6498 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006499 mActiveTracks.clear();
6500 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08006501 mStartStopCond.broadcast();
6502 }
6503
6504 releaseWakeLock();
6505
6506 ALOGV("RecordThread %p exiting", this);
6507 return false;
6508}
6509
Glenn Kasten93e471f2013-08-19 08:40:07 -07006510void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08006511{
6512 if (!mStandby) {
6513 inputStandBy();
6514 mStandby = true;
6515 }
6516}
6517
6518void AudioFlinger::RecordThread::inputStandBy()
6519{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006520 // Idle the fast capture if it's currently running
6521 if (mFastCapture != 0) {
6522 FastCaptureStateQueue *sq = mFastCapture->sq();
6523 FastCaptureState *state = sq->begin();
6524 if (!(state->mCommand & FastCaptureState::IDLE)) {
6525 state->mCommand = FastCaptureState::COLD_IDLE;
6526 state->mColdFutexAddr = &mFastCaptureFutex;
6527 state->mColdGen++;
6528 mFastCaptureFutex = 0;
6529 sq->end();
6530 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
6531 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
6532#if 0
6533 if (kUseFastCapture == FastCapture_Dynamic) {
6534 // FIXME
6535 }
6536#endif
6537#ifdef AUDIO_WATCHDOG
6538 // FIXME
6539#endif
6540 } else {
6541 sq->end(false /*didModify*/);
6542 }
6543 }
Eric Laurent81784c32012-11-19 14:55:58 -08006544 mInput->stream->common.standby(&mInput->stream->common);
6545}
6546
Glenn Kasten05997e22014-03-13 15:08:33 -07006547// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07006548sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08006549 const sp<AudioFlinger::Client>& client,
6550 uint32_t sampleRate,
6551 audio_format_t format,
6552 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08006553 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08006554 audio_session_t sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07006555 size_t *notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006556 int uid,
Eric Laurent05067782016-06-01 18:27:28 -07006557 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08006558 pid_t tid,
6559 status_t *status)
6560{
Glenn Kasten74935e42013-12-19 08:56:45 -08006561 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08006562 sp<RecordTrack> track;
6563 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07006564 audio_input_flags_t inputFlags = mInput->flags;
6565
6566 // special case for FAST flag considered OK if fast capture is present
6567 if (hasFastCapture()) {
6568 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
6569 }
6570
6571 // Check if requested flags are compatible with output stream flags
6572 if ((*flags & inputFlags) != *flags) {
6573 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
6574 " input flags (%08x)",
6575 *flags, inputFlags);
6576 *flags = (audio_input_flags_t)(*flags & inputFlags);
6577 }
Eric Laurent81784c32012-11-19 14:55:58 -08006578
Glenn Kasten90e58b12013-07-31 16:16:02 -07006579 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07006580 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006581 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07006582 // we formerly checked for a callback handler (non-0 tid),
6583 // but that is no longer required for TRANSFER_OBTAIN mode
6584 //
Glenn Kasten74105912014-07-03 12:28:53 -07006585 // frame count is not specified, or is exactly the pipe depth
6586 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006587 // PCM data
6588 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006589 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006590 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006591 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006592 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006593 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07006594 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006595 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006596 hasFastCapture() &&
6597 // there are sufficient fast track slots available
6598 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07006599 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07006600 // check compatibility with audio effects.
6601 Mutex::Autolock _l(mLock);
6602 // Do not accept FAST flag if the session has software effects
6603 sp<EffectChain> chain = getEffectChain_l(sessionId);
6604 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07006605 audio_input_flags_t old = *flags;
6606 chain->checkInputFlagCompatibility(flags);
6607 if (old != *flags) {
6608 ALOGV("AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
6609 (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07006610 }
6611 }
Eric Laurent122f7e72016-06-29 11:53:29 -07006612 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07006613 "AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
6614 frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006615 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006616 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
Glenn Kasten74105912014-07-03 12:28:53 -07006617 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006618 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07006619 frameCount, mFrameCount, mPipeFramesP2,
6620 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
6621 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07006622 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07006623 }
6624 }
6625
6626 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07006627 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07006628 // fast track: frame count is exactly the pipe depth
6629 frameCount = mPipeFramesP2;
6630 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
6631 *notificationFrames = mFrameCount;
6632 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006633 // not fast track: max notification period is resampled equivalent of one HAL buffer time
6634 // or 20 ms if there is a fast capture
6635 // TODO This could be a roundupRatio inline, and const
6636 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
6637 * sampleRate + mSampleRate - 1) / mSampleRate;
6638 // minimum number of notification periods is at least kMinNotifications,
6639 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
6640 static const size_t kMinNotifications = 3;
6641 static const uint32_t kMinMs = 30;
6642 // TODO This could be a roundupRatio inline
6643 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
6644 // TODO This could be a roundupRatio inline
6645 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
6646 maxNotificationFrames;
6647 const size_t minFrameCount = maxNotificationFrames *
6648 max(kMinNotifications, minNotificationsByMs);
6649 frameCount = max(frameCount, minFrameCount);
6650 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
6651 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07006652 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07006653 }
Glenn Kasten74935e42013-12-19 08:56:45 -08006654 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07006655
Glenn Kasten15e57982013-09-24 11:52:37 -07006656 lStatus = initCheck();
6657 if (lStatus != NO_ERROR) {
6658 ALOGE("createRecordTrack_l() audio driver not initialized");
6659 goto Exit;
6660 }
Eric Laurent81784c32012-11-19 14:55:58 -08006661
6662 { // scope for mLock
6663 Mutex::Autolock _l(mLock);
6664
6665 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07006666 format, channelMask, frameCount, NULL, sessionId, uid,
6667 *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08006668
Glenn Kasten03003332013-08-06 15:40:54 -07006669 lStatus = track->initCheck();
6670 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07006671 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08006672 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08006673 goto Exit;
6674 }
6675 mTracks.add(track);
6676
6677 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6678 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6679 mAudioFlinger->btNrecIsOff();
6680 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6681 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006682
Eric Laurent05067782016-06-01 18:27:28 -07006683 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006684 pid_t callingPid = IPCThreadState::self()->getCallingPid();
6685 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
6686 // so ask activity manager to do this on our behalf
6687 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
6688 }
Eric Laurent81784c32012-11-19 14:55:58 -08006689 }
Glenn Kasten05997e22014-03-13 15:08:33 -07006690
Eric Laurent81784c32012-11-19 14:55:58 -08006691 lStatus = NO_ERROR;
6692
6693Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07006694 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08006695 return track;
6696}
6697
6698status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6699 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08006700 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08006701{
6702 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6703 sp<ThreadBase> strongMe = this;
6704 status_t status = NO_ERROR;
6705
6706 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006707 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006708 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006709 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08006710 triggerSession,
6711 recordTrack->sessionId(),
6712 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006713 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08006714 // Sync event can be cancelled by the trigger session if the track is not in a
6715 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006716 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006717 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006718 } else {
6719 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006720 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006721 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08006722 }
6723 }
6724
6725 {
Glenn Kasten47c20702013-08-13 15:37:35 -07006726 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08006727 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006728 if (mActiveTracks.indexOf(recordTrack) >= 0) {
6729 if (recordTrack->mState == TrackBase::PAUSING) {
6730 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006731 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006732 } else {
6733 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08006734 }
6735 return status;
6736 }
6737
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006738 // TODO consider other ways of handling this, such as changing the state to :STARTING and
6739 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6740 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006741 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08006742 mActiveTracks.add(recordTrack);
6743 mActiveTracksGen++;
Eric Laurent83b88082014-06-20 18:31:16 -07006744 status_t status = NO_ERROR;
6745 if (recordTrack->isExternalTrack()) {
6746 mLock.unlock();
Glenn Kastend848eb42016-03-08 13:42:11 -08006747 status = AudioSystem::startInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006748 mLock.lock();
6749 // FIXME should verify that recordTrack is still in mActiveTracks
6750 if (status != NO_ERROR) {
6751 mActiveTracks.remove(recordTrack);
6752 mActiveTracksGen++;
6753 recordTrack->clearSyncStartEvent();
6754 ALOGV("RecordThread::start error %d", status);
6755 return status;
6756 }
Eric Laurent81784c32012-11-19 14:55:58 -08006757 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006758 // Catch up with current buffer indices if thread is already running.
6759 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
6760 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6761 // see previously buffered data before it called start(), but with greater risk of overrun.
6762
Andy Hung73c02e42015-03-29 01:13:58 -07006763 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07006764 // clear any converter state as new data will be discontinuous
6765 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006766 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08006767 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08006768 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08006769 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006770 ALOGV("Record failed to start");
6771 status = BAD_VALUE;
6772 goto startError;
6773 }
Eric Laurent81784c32012-11-19 14:55:58 -08006774 return status;
6775 }
Glenn Kasten7c027242012-12-26 14:43:16 -08006776
Eric Laurent81784c32012-11-19 14:55:58 -08006777startError:
Eric Laurent83b88082014-06-20 18:31:16 -07006778 if (recordTrack->isExternalTrack()) {
Glenn Kastend848eb42016-03-08 13:42:11 -08006779 AudioSystem::stopInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006780 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006781 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006782 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08006783 return status;
6784}
6785
Eric Laurent81784c32012-11-19 14:55:58 -08006786void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6787{
6788 sp<SyncEvent> strongEvent = event.promote();
6789
6790 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08006791 sp<RefBase> ptr = strongEvent->cookie().promote();
6792 if (ptr != 0) {
6793 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6794 recordTrack->handleSyncStartEvent(strongEvent);
6795 }
Eric Laurent81784c32012-11-19 14:55:58 -08006796 }
6797}
6798
Glenn Kastena8356f62013-07-25 14:37:52 -07006799bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08006800 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07006801 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006802 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08006803 return false;
6804 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006805 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006806 recordTrack->mState = TrackBase::PAUSING;
Eric Laurent5c25d562016-07-13 17:17:45 -07006807 // signal thread to stop
6808 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08006809 // do not wait for mStartStopCond if exiting
6810 if (exitPending()) {
6811 return true;
6812 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006813 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08006814 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006815 // if we have been restarted, recordTrack is in mActiveTracks here
6816 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006817 ALOGV("Record stopped OK");
6818 return true;
6819 }
6820 return false;
6821}
6822
Glenn Kasten0f11b512014-01-31 16:18:54 -08006823bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08006824{
6825 return false;
6826}
6827
Glenn Kasten0f11b512014-01-31 16:18:54 -08006828status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006829{
6830#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6831 if (!isValidSyncEvent(event)) {
6832 return BAD_VALUE;
6833 }
6834
Glenn Kastend848eb42016-03-08 13:42:11 -08006835 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08006836 status_t ret = NAME_NOT_FOUND;
6837
6838 Mutex::Autolock _l(mLock);
6839
6840 for (size_t i = 0; i < mTracks.size(); i++) {
6841 sp<RecordTrack> track = mTracks[i];
6842 if (eventSession == track->sessionId()) {
6843 (void) track->setSyncEvent(event);
6844 ret = NO_ERROR;
6845 }
6846 }
6847 return ret;
6848#else
6849 return BAD_VALUE;
6850#endif
6851}
6852
6853// destroyTrack_l() must be called with ThreadBase::mLock held
6854void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6855{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006856 track->terminate();
6857 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006858 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006859 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006860 removeTrack_l(track);
6861 }
6862}
6863
6864void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6865{
6866 mTracks.remove(track);
6867 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006868 if (track->isFastTrack()) {
6869 ALOG_ASSERT(!mFastTrackAvail);
6870 mFastTrackAvail = true;
6871 }
Eric Laurent81784c32012-11-19 14:55:58 -08006872}
6873
6874void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6875{
6876 dumpInternals(fd, args);
6877 dumpTracks(fd, args);
6878 dumpEffectChains(fd, args);
6879}
6880
6881void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6882{
Elliott Hughes87cebad2014-05-22 10:14:43 -07006883 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08006884
Glenn Kasten44182c22015-03-05 17:12:23 -08006885 dumpBase(fd, args);
6886
6887 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006888 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006889 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006890 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006891 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08006892
Glenn Kasten2f90c512015-12-02 11:40:09 -08006893 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
6894 // while we are dumping it. It may be inconsistent, but it won't mutate!
6895 // This is a large object so we place it on the heap.
6896 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
6897 const FastCaptureDumpState *copy = new FastCaptureDumpState(mFastCaptureDumpState);
6898 copy->dump(fd);
6899 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08006900}
6901
Glenn Kasten0f11b512014-01-31 16:18:54 -08006902void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006903{
6904 const size_t SIZE = 256;
6905 char buffer[SIZE];
6906 String8 result;
6907
Marco Nelissenb2208842014-02-07 14:00:50 -08006908 size_t numtracks = mTracks.size();
6909 size_t numactive = mActiveTracks.size();
6910 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006911 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006912 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006913 dprintf(fd, " of which %zu are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006914 RecordTrack::appendDumpHeader(result);
6915 for (size_t i = 0; i < numtracks ; ++i) {
6916 sp<RecordTrack> track = mTracks[i];
6917 if (track != 0) {
6918 bool active = mActiveTracks.indexOf(track) >= 0;
6919 if (active) {
6920 numactiveseen++;
6921 }
6922 track->dump(buffer, SIZE, active);
6923 result.append(buffer);
6924 }
Eric Laurent81784c32012-11-19 14:55:58 -08006925 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006926 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006927 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006928 }
6929
Marco Nelissenb2208842014-02-07 14:00:50 -08006930 if (numactiveseen != numactive) {
6931 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6932 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006933 result.append(buffer);
6934 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006935 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006936 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006937 if (mTracks.indexOf(track) < 0) {
6938 track->dump(buffer, SIZE, true);
6939 result.append(buffer);
6940 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006941 }
Eric Laurent81784c32012-11-19 14:55:58 -08006942
6943 }
6944 write(fd, result.string(), result.size());
6945}
6946
Andy Hung73c02e42015-03-29 01:13:58 -07006947
6948void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
6949{
6950 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6951 RecordThread *recordThread = (RecordThread *) threadBase.get();
6952 mRsmpInFront = recordThread->mRsmpInRear;
6953 mRsmpInUnrel = 0;
6954}
6955
6956void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
6957 size_t *framesAvailable, bool *hasOverrun)
6958{
6959 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6960 RecordThread *recordThread = (RecordThread *) threadBase.get();
6961 const int32_t rear = recordThread->mRsmpInRear;
6962 const int32_t front = mRsmpInFront;
6963 const ssize_t filled = rear - front;
6964
6965 size_t framesIn;
6966 bool overrun = false;
6967 if (filled < 0) {
6968 // should not happen, but treat like a massive overrun and re-sync
6969 framesIn = 0;
6970 mRsmpInFront = rear;
6971 overrun = true;
6972 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
6973 framesIn = (size_t) filled;
6974 } else {
6975 // client is not keeping up with server, but give it latest data
6976 framesIn = recordThread->mRsmpInFrames;
6977 mRsmpInFront = /* front = */ rear - framesIn;
6978 overrun = true;
6979 }
6980 if (framesAvailable != NULL) {
6981 *framesAvailable = framesIn;
6982 }
6983 if (hasOverrun != NULL) {
6984 *hasOverrun = overrun;
6985 }
6986}
6987
Eric Laurent81784c32012-11-19 14:55:58 -08006988// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006989status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08006990 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006991{
Andy Hung73c02e42015-03-29 01:13:58 -07006992 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006993 if (threadBase == 0) {
6994 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006995 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006996 return NOT_ENOUGH_DATA;
6997 }
6998 RecordThread *recordThread = (RecordThread *) threadBase.get();
6999 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07007000 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07007001 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007002 // FIXME should not be P2 (don't want to increase latency)
7003 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08007004 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07007005 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007006 front &= recordThread->mRsmpInFramesP2 - 1;
7007 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07007008 if (part1 > (size_t) filled) {
7009 part1 = filled;
7010 }
7011 size_t ask = buffer->frameCount;
7012 ALOG_ASSERT(ask > 0);
7013 if (part1 > ask) {
7014 part1 = ask;
7015 }
7016 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07007017 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07007018 buffer->raw = NULL;
7019 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07007020 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07007021 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08007022 }
7023
Andy Hung57446612015-04-19 23:56:46 -07007024 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07007025 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07007026 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08007027 return NO_ERROR;
7028}
7029
7030// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007031void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
7032 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08007033{
Glenn Kasten85948432013-08-19 12:09:05 -07007034 size_t stepCount = buffer->frameCount;
7035 if (stepCount == 0) {
7036 return;
7037 }
Andy Hung73c02e42015-03-29 01:13:58 -07007038 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
7039 mRsmpInUnrel -= stepCount;
7040 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07007041 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08007042 buffer->frameCount = 0;
7043}
7044
Andy Hung97a893e2015-03-29 01:03:07 -07007045AudioFlinger::RecordThread::RecordBufferConverter::RecordBufferConverter(
7046 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
7047 uint32_t srcSampleRate,
7048 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
7049 uint32_t dstSampleRate) :
7050 mSrcChannelMask(AUDIO_CHANNEL_INVALID), // updateParameters will set following vars
7051 // mSrcFormat
7052 // mSrcSampleRate
7053 // mDstChannelMask
7054 // mDstFormat
7055 // mDstSampleRate
7056 // mSrcChannelCount
7057 // mDstChannelCount
7058 // mDstFrameSize
7059 mBuf(NULL), mBufFrames(0), mBufFrameSize(0),
Andy Hungd330ee42015-04-20 13:23:41 -07007060 mResampler(NULL),
7061 mIsLegacyDownmix(false),
7062 mIsLegacyUpmix(false),
7063 mRequiresFloat(false),
7064 mInputConverterProvider(NULL)
Andy Hung97a893e2015-03-29 01:03:07 -07007065{
7066 (void)updateParameters(srcChannelMask, srcFormat, srcSampleRate,
7067 dstChannelMask, dstFormat, dstSampleRate);
7068}
7069
7070AudioFlinger::RecordThread::RecordBufferConverter::~RecordBufferConverter() {
7071 free(mBuf);
7072 delete mResampler;
Andy Hungd330ee42015-04-20 13:23:41 -07007073 delete mInputConverterProvider;
Andy Hung97a893e2015-03-29 01:03:07 -07007074}
7075
7076size_t AudioFlinger::RecordThread::RecordBufferConverter::convert(void *dst,
7077 AudioBufferProvider *provider, size_t frames)
7078{
Andy Hungd330ee42015-04-20 13:23:41 -07007079 if (mInputConverterProvider != NULL) {
7080 mInputConverterProvider->setBufferProvider(provider);
7081 provider = mInputConverterProvider;
7082 }
7083
7084 if (mResampler == NULL) {
Andy Hung97a893e2015-03-29 01:03:07 -07007085 ALOGVV("NO RESAMPLING sampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
7086 mSrcSampleRate, mSrcFormat, mDstFormat);
7087
7088 AudioBufferProvider::Buffer buffer;
7089 for (size_t i = frames; i > 0; ) {
7090 buffer.frameCount = i;
Glenn Kastend79072e2016-01-06 08:41:20 -08007091 status_t status = provider->getNextBuffer(&buffer);
Andy Hung97a893e2015-03-29 01:03:07 -07007092 if (status != OK || buffer.frameCount == 0) {
7093 frames -= i; // cannot fill request.
7094 break;
7095 }
Andy Hungd330ee42015-04-20 13:23:41 -07007096 // format convert to destination buffer
7097 convertNoResampler(dst, buffer.raw, buffer.frameCount);
Andy Hung97a893e2015-03-29 01:03:07 -07007098
7099 dst = (int8_t*)dst + buffer.frameCount * mDstFrameSize;
7100 i -= buffer.frameCount;
7101 provider->releaseBuffer(&buffer);
7102 }
7103 } else {
7104 ALOGVV("RESAMPLING mSrcSampleRate:%u mDstSampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
7105 mSrcSampleRate, mDstSampleRate, mSrcFormat, mDstFormat);
7106
Andy Hungd330ee42015-04-20 13:23:41 -07007107 // reallocate buffer if needed
7108 if (mBufFrameSize != 0 && mBufFrames < frames) {
7109 free(mBuf);
7110 mBufFrames = frames;
7111 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
7112 }
Andy Hung97a893e2015-03-29 01:03:07 -07007113 // resampler accumulates, but we only have one source track
Andy Hungd330ee42015-04-20 13:23:41 -07007114 memset(mBuf, 0, frames * mBufFrameSize);
7115 frames = mResampler->resample((int32_t*)mBuf, frames, provider);
7116 // format convert to destination buffer
7117 convertResampler(dst, mBuf, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07007118 }
7119 return frames;
7120}
7121
7122status_t AudioFlinger::RecordThread::RecordBufferConverter::updateParameters(
7123 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
7124 uint32_t srcSampleRate,
7125 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
7126 uint32_t dstSampleRate)
7127{
7128 // quick evaluation if there is any change.
7129 if (mSrcFormat == srcFormat
7130 && mSrcChannelMask == srcChannelMask
7131 && mSrcSampleRate == srcSampleRate
7132 && mDstFormat == dstFormat
7133 && mDstChannelMask == dstChannelMask
7134 && mDstSampleRate == dstSampleRate) {
7135 return NO_ERROR;
7136 }
7137
Andy Hungdb4c0312015-05-06 08:46:52 -07007138 ALOGV("RecordBufferConverter updateParameters srcMask:%#x dstMask:%#x"
7139 " srcFormat:%#x dstFormat:%#x srcRate:%u dstRate:%u",
7140 srcChannelMask, dstChannelMask, srcFormat, dstFormat, srcSampleRate, dstSampleRate);
Andy Hung97a893e2015-03-29 01:03:07 -07007141 const bool valid =
7142 audio_is_input_channel(srcChannelMask)
7143 && audio_is_input_channel(dstChannelMask)
7144 && audio_is_valid_format(srcFormat) && audio_is_linear_pcm(srcFormat)
7145 && audio_is_valid_format(dstFormat) && audio_is_linear_pcm(dstFormat)
7146 && (srcSampleRate <= dstSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX)
7147 ; // no upsampling checks for now
7148 if (!valid) {
7149 return BAD_VALUE;
7150 }
7151
7152 mSrcFormat = srcFormat;
7153 mSrcChannelMask = srcChannelMask;
7154 mSrcSampleRate = srcSampleRate;
7155 mDstFormat = dstFormat;
7156 mDstChannelMask = dstChannelMask;
7157 mDstSampleRate = dstSampleRate;
7158
7159 // compute derived parameters
7160 mSrcChannelCount = audio_channel_count_from_in_mask(srcChannelMask);
7161 mDstChannelCount = audio_channel_count_from_in_mask(dstChannelMask);
7162 mDstFrameSize = mDstChannelCount * audio_bytes_per_sample(mDstFormat);
7163
Andy Hungd330ee42015-04-20 13:23:41 -07007164 // do we need to resample?
7165 delete mResampler;
7166 mResampler = NULL;
7167 if (mSrcSampleRate != mDstSampleRate) {
7168 mResampler = AudioResampler::create(AUDIO_FORMAT_PCM_FLOAT,
7169 mSrcChannelCount, mDstSampleRate);
7170 mResampler->setSampleRate(mSrcSampleRate);
7171 mResampler->setVolume(AudioMixer::UNITY_GAIN_FLOAT, AudioMixer::UNITY_GAIN_FLOAT);
7172 }
7173
7174 // are we running legacy channel conversion modes?
7175 mIsLegacyDownmix = (mSrcChannelMask == AUDIO_CHANNEL_IN_STEREO
7176 || mSrcChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK)
7177 && mDstChannelMask == AUDIO_CHANNEL_IN_MONO;
7178 mIsLegacyUpmix = mSrcChannelMask == AUDIO_CHANNEL_IN_MONO
7179 && (mDstChannelMask == AUDIO_CHANNEL_IN_STEREO
7180 || mDstChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK);
7181
7182 // do we need to process in float?
7183 mRequiresFloat = mResampler != NULL || mIsLegacyDownmix || mIsLegacyUpmix;
7184
7185 // do we need a staging buffer to convert for destination (we can still optimize this)?
7186 // we use mBufFrameSize > 0 to indicate both frame size as well as buffer necessity
7187 if (mResampler != NULL) {
7188 mBufFrameSize = max(mSrcChannelCount, FCC_2)
7189 * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
Andy Hunga97630b2015-07-22 23:27:24 -07007190 } else if (mIsLegacyUpmix || mIsLegacyDownmix) { // legacy modes always float
Andy Hungd330ee42015-04-20 13:23:41 -07007191 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
7192 } else if (mSrcChannelMask != mDstChannelMask && mDstFormat != mSrcFormat) {
Andy Hung97a893e2015-03-29 01:03:07 -07007193 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(mSrcFormat);
7194 } else {
7195 mBufFrameSize = 0;
7196 }
7197 mBufFrames = 0; // force the buffer to be resized.
7198
Andy Hungd330ee42015-04-20 13:23:41 -07007199 // do we need an input converter buffer provider to give us float?
7200 delete mInputConverterProvider;
7201 mInputConverterProvider = NULL;
7202 if (mRequiresFloat && mSrcFormat != AUDIO_FORMAT_PCM_FLOAT) {
7203 mInputConverterProvider = new ReformatBufferProvider(
7204 audio_channel_count_from_in_mask(mSrcChannelMask),
7205 mSrcFormat,
7206 AUDIO_FORMAT_PCM_FLOAT,
7207 256 /* provider buffer frame count */);
7208 }
7209
7210 // do we need a remixer to do channel mask conversion
7211 if (!mIsLegacyDownmix && !mIsLegacyUpmix && mSrcChannelMask != mDstChannelMask) {
7212 (void) memcpy_by_index_array_initialization_from_channel_mask(
7213 mIdxAry, ARRAY_SIZE(mIdxAry), mDstChannelMask, mSrcChannelMask);
Andy Hung97a893e2015-03-29 01:03:07 -07007214 }
7215 return NO_ERROR;
7216}
7217
Andy Hungd330ee42015-04-20 13:23:41 -07007218void AudioFlinger::RecordThread::RecordBufferConverter::convertNoResampler(
7219 void *dst, const void *src, size_t frames)
Andy Hung97a893e2015-03-29 01:03:07 -07007220{
Andy Hungd330ee42015-04-20 13:23:41 -07007221 // src is native type unless there is legacy upmix or downmix, whereupon it is float.
Andy Hung97a893e2015-03-29 01:03:07 -07007222 if (mBufFrameSize != 0 && mBufFrames < frames) {
7223 free(mBuf);
7224 mBufFrames = frames;
7225 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
7226 }
Andy Hungd330ee42015-04-20 13:23:41 -07007227 // do we need to do legacy upmix and downmix?
7228 if (mIsLegacyUpmix || mIsLegacyDownmix) {
Andy Hung97a893e2015-03-29 01:03:07 -07007229 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07007230 if (mIsLegacyUpmix) {
7231 upmix_to_stereo_float_from_mono_float((float *)dstBuf,
7232 (const float *)src, frames);
7233 } else /*mIsLegacyDownmix */ {
7234 downmix_to_mono_float_from_stereo_float((float *)dstBuf,
7235 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07007236 }
Andy Hungd330ee42015-04-20 13:23:41 -07007237 if (mBuf != NULL) {
7238 memcpy_by_audio_format(dst, mDstFormat, mBuf, AUDIO_FORMAT_PCM_FLOAT,
7239 frames * mDstChannelCount);
7240 }
7241 return;
7242 }
7243 // do we need to do channel mask conversion?
7244 if (mSrcChannelMask != mDstChannelMask) {
Andy Hung97a893e2015-03-29 01:03:07 -07007245 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07007246 memcpy_by_index_array(dstBuf, mDstChannelCount,
7247 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mSrcFormat), frames);
7248 if (dstBuf == dst) {
7249 return; // format is the same
7250 }
7251 }
7252 // convert to destination buffer
7253 const void *convertBuf = mBuf != NULL ? mBuf : src;
7254 memcpy_by_audio_format(dst, mDstFormat, convertBuf, mSrcFormat,
7255 frames * mDstChannelCount);
7256}
7257
7258void AudioFlinger::RecordThread::RecordBufferConverter::convertResampler(
7259 void *dst, /*not-a-const*/ void *src, size_t frames)
7260{
7261 // src buffer format is ALWAYS float when entering this routine
7262 if (mIsLegacyUpmix) {
7263 ; // mono to stereo already handled by resampler
7264 } else if (mIsLegacyDownmix
7265 || (mSrcChannelMask == mDstChannelMask && mSrcChannelCount == 1)) {
7266 // the resampler outputs stereo for mono input channel (a feature?)
7267 // must convert to mono
7268 downmix_to_mono_float_from_stereo_float((float *)src,
7269 (const float *)src, frames);
7270 } else if (mSrcChannelMask != mDstChannelMask) {
7271 // convert to mono channel again for channel mask conversion (could be skipped
7272 // with further optimization).
Andy Hung97a893e2015-03-29 01:03:07 -07007273 if (mSrcChannelCount == 1) {
Andy Hungd330ee42015-04-20 13:23:41 -07007274 downmix_to_mono_float_from_stereo_float((float *)src,
7275 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07007276 }
Andy Hungd330ee42015-04-20 13:23:41 -07007277 // convert to destination format (in place, OK as float is larger than other types)
7278 if (mDstFormat != AUDIO_FORMAT_PCM_FLOAT) {
7279 memcpy_by_audio_format(src, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
7280 frames * mSrcChannelCount);
7281 }
7282 // channel convert and save to dst
7283 memcpy_by_index_array(dst, mDstChannelCount,
7284 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mDstFormat), frames);
7285 return;
Andy Hung97a893e2015-03-29 01:03:07 -07007286 }
Andy Hungd330ee42015-04-20 13:23:41 -07007287 // convert to destination format and save to dst
7288 memcpy_by_audio_format(dst, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
7289 frames * mDstChannelCount);
Andy Hung97a893e2015-03-29 01:03:07 -07007290}
7291
Eric Laurent10351942014-05-08 18:49:52 -07007292bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
7293 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007294{
7295 bool reconfig = false;
7296
Eric Laurent10351942014-05-08 18:49:52 -07007297 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007298
Eric Laurent10351942014-05-08 18:49:52 -07007299 audio_format_t reqFormat = mFormat;
7300 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07007301 // 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 -07007302 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
7303
7304 AudioParameter param = AudioParameter(keyValuePair);
7305 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07007306
7307 // scope for AutoPark extends to end of method
7308 AutoPark<FastCapture> park(mFastCapture);
7309
Eric Laurent10351942014-05-08 18:49:52 -07007310 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
7311 // channel count change can be requested. Do we mandate the first client defines the
7312 // HAL sampling rate and channel count or do we allow changes on the fly?
7313 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
7314 samplingRate = value;
7315 reconfig = true;
7316 }
7317 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07007318 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07007319 status = BAD_VALUE;
7320 } else {
7321 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08007322 reconfig = true;
7323 }
Eric Laurent10351942014-05-08 18:49:52 -07007324 }
7325 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
7326 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07007327 if (!audio_is_input_channel(mask) ||
7328 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007329 status = BAD_VALUE;
7330 } else {
7331 channelMask = mask;
7332 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007333 }
Eric Laurent10351942014-05-08 18:49:52 -07007334 }
7335 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7336 // do not accept frame count changes if tracks are open as the track buffer
7337 // size depends on frame count and correct behavior would not be guaranteed
7338 // if frame count is changed after track creation
7339 if (mActiveTracks.size() > 0) {
7340 status = INVALID_OPERATION;
7341 } else {
7342 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007343 }
Eric Laurent10351942014-05-08 18:49:52 -07007344 }
7345 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7346 // forward device change to effects that have requested to be
7347 // aware of attached audio device.
7348 for (size_t i = 0; i < mEffectChains.size(); i++) {
7349 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08007350 }
Eric Laurent81784c32012-11-19 14:55:58 -08007351
Eric Laurent10351942014-05-08 18:49:52 -07007352 // store input device and output device but do not forward output device to audio HAL.
7353 // Note that status is ignored by the caller for output device
7354 // (see AudioFlinger::setParameters()
7355 if (audio_is_output_devices(value)) {
7356 mOutDevice = value;
7357 status = BAD_VALUE;
7358 } else {
7359 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07007360 if (value != AUDIO_DEVICE_NONE) {
7361 mPrevInDevice = value;
7362 }
Eric Laurent10351942014-05-08 18:49:52 -07007363 // disable AEC and NS if the device is a BT SCO headset supporting those
7364 // pre processings
7365 if (mTracks.size() > 0) {
7366 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7367 mAudioFlinger->btNrecIsOff();
7368 for (size_t i = 0; i < mTracks.size(); i++) {
7369 sp<RecordTrack> track = mTracks[i];
7370 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7371 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08007372 }
7373 }
7374 }
Eric Laurent10351942014-05-08 18:49:52 -07007375 }
7376 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
7377 mAudioSource != (audio_source_t)value) {
7378 // forward device change to effects that have requested to be
7379 // aware of attached audio device.
7380 for (size_t i = 0; i < mEffectChains.size(); i++) {
7381 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08007382 }
Eric Laurent10351942014-05-08 18:49:52 -07007383 mAudioSource = (audio_source_t)value;
7384 }
Glenn Kastene198c362013-08-13 09:13:36 -07007385
Eric Laurent10351942014-05-08 18:49:52 -07007386 if (status == NO_ERROR) {
7387 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7388 keyValuePair.string());
7389 if (status == INVALID_OPERATION) {
7390 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08007391 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7392 keyValuePair.string());
Eric Laurent10351942014-05-08 18:49:52 -07007393 }
7394 if (reconfig) {
7395 if (status == BAD_VALUE &&
Andy Hung97a893e2015-03-29 01:03:07 -07007396 audio_is_linear_pcm(mInput->stream->common.get_format(&mInput->stream->common)) &&
7397 audio_is_linear_pcm(reqFormat) &&
Eric Laurent10351942014-05-08 18:49:52 -07007398 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
Andy Hung97a893e2015-03-29 01:03:07 -07007399 <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate)) &&
Andy Hunge5412692014-05-16 11:25:07 -07007400 audio_channel_count_from_in_mask(
Andy Hungd1abb8f2015-05-05 23:42:34 -07007401 mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007402 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007403 }
Eric Laurent10351942014-05-08 18:49:52 -07007404 if (status == NO_ERROR) {
7405 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007406 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08007407 }
7408 }
Eric Laurent81784c32012-11-19 14:55:58 -08007409 }
Eric Laurent10351942014-05-08 18:49:52 -07007410
Eric Laurent81784c32012-11-19 14:55:58 -08007411 return reconfig;
7412}
7413
7414String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
7415{
Eric Laurent81784c32012-11-19 14:55:58 -08007416 Mutex::Autolock _l(mLock);
7417 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07007418 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08007419 }
7420
Glenn Kastend8ea6992013-07-16 14:17:15 -07007421 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
7422 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08007423 free(s);
7424 return out_s8;
7425}
7426
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007427void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007428 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7429
7430 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08007431
7432 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007433 case AUDIO_INPUT_OPENED:
7434 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07007435 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07007436 desc->mChannelMask = mChannelMask;
7437 desc->mSamplingRate = mSampleRate;
7438 desc->mFormat = mFormat;
7439 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07007440 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07007441 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007442 break;
7443
Eric Laurent73e26b62015-04-27 16:55:58 -07007444 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08007445 default:
7446 break;
7447 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007448 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08007449}
7450
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007451void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007452{
Eric Laurent81784c32012-11-19 14:55:58 -08007453 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
7454 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Andy Hunge5412692014-05-16 11:25:07 -07007455 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Andy Hungd330ee42015-04-20 13:23:41 -07007456 if (mChannelCount > FCC_8) {
7457 ALOGE("HAL channel count %d > %d", mChannelCount, FCC_8);
7458 }
Andy Hung463be252014-07-10 16:56:07 -07007459 mHALFormat = mInput->stream->common.get_format(&mInput->stream->common);
7460 mFormat = mHALFormat;
Andy Hungd330ee42015-04-20 13:23:41 -07007461 if (!audio_is_linear_pcm(mFormat)) {
7462 ALOGE("HAL format %#x is not linear pcm", mFormat);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07007463 }
Eric Laurent665470b2014-07-03 16:37:08 -07007464 mFrameSize = audio_stream_in_frame_size(mInput->stream);
Glenn Kasten548efc92012-11-29 08:48:51 -08007465 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
7466 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007467 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08007468 // 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 -07007469 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08007470 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007471 // A larger value should allow more old data to be read after a track calls start(),
7472 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07007473 //
7474 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08007475 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07007476 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07007477 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07007478 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007479
7480 // TODO optimize audio capture buffer sizes ...
7481 // Here we calculate the size of the sliding buffer used as a source
7482 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
7483 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
7484 // be better to have it derived from the pipe depth in the long term.
7485 // The current value is higher than necessary. However it should not add to latency.
7486
Glenn Kasten85948432013-08-19 12:09:05 -07007487 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Andy Hung0a01c2f2015-09-21 12:44:54 -07007488 size_t bufferSize = (mRsmpInFramesP2 + mFrameCount - 1) * mFrameSize;
7489 (void)posix_memalign(&mRsmpInBuffer, 32, bufferSize);
7490 memset(mRsmpInBuffer, 0, bufferSize); // if posix_memalign fails, will segv here.
Eric Laurent81784c32012-11-19 14:55:58 -08007491
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007492 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
7493 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08007494}
7495
Glenn Kasten5f972c02014-01-13 09:59:31 -08007496uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08007497{
7498 Mutex::Autolock _l(mLock);
7499 if (initCheck() != NO_ERROR) {
7500 return 0;
7501 }
7502
7503 return mInput->stream->get_input_frames_lost(mInput->stream);
7504}
7505
Eric Laurent4c415062016-06-17 16:14:16 -07007506// hasAudioSession_l() must be called with ThreadBase::mLock held
7507uint32_t AudioFlinger::RecordThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08007508{
Eric Laurent81784c32012-11-19 14:55:58 -08007509 uint32_t result = 0;
7510 if (getEffectChain_l(sessionId) != 0) {
7511 result = EFFECT_SESSION;
7512 }
7513
7514 for (size_t i = 0; i < mTracks.size(); ++i) {
7515 if (sessionId == mTracks[i]->sessionId()) {
7516 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07007517 if (mTracks[i]->isFastTrack()) {
7518 result |= FAST_SESSION;
7519 }
Eric Laurent81784c32012-11-19 14:55:58 -08007520 break;
7521 }
7522 }
7523
7524 return result;
7525}
7526
Glenn Kastend848eb42016-03-08 13:42:11 -08007527KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08007528{
Glenn Kastend848eb42016-03-08 13:42:11 -08007529 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08007530 Mutex::Autolock _l(mLock);
7531 for (size_t j = 0; j < mTracks.size(); ++j) {
7532 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08007533 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08007534 if (ids.indexOfKey(sessionId) < 0) {
7535 ids.add(sessionId, true);
7536 }
7537 }
7538 return ids;
7539}
7540
7541AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7542{
7543 Mutex::Autolock _l(mLock);
7544 AudioStreamIn *input = mInput;
7545 mInput = NULL;
7546 return input;
7547}
7548
7549// this method must always be called either with ThreadBase mLock held or inside the thread loop
7550audio_stream_t* AudioFlinger::RecordThread::stream() const
7551{
7552 if (mInput == NULL) {
7553 return NULL;
7554 }
7555 return &mInput->stream->common;
7556}
7557
7558status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7559{
7560 // only one chain per input thread
7561 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07007562 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08007563 return INVALID_OPERATION;
7564 }
7565 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07007566 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08007567 chain->setInBuffer(NULL);
7568 chain->setOutBuffer(NULL);
7569
7570 checkSuspendOnAddEffectChain_l(chain);
7571
Eric Laurent1b928682014-10-02 19:41:47 -07007572 // make sure enabled pre processing effects state is communicated to the HAL as we
7573 // just moved them to a new input stream.
7574 chain->syncHalEffectsState();
7575
Eric Laurent81784c32012-11-19 14:55:58 -08007576 mEffectChains.add(chain);
7577
7578 return NO_ERROR;
7579}
7580
7581size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7582{
7583 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7584 ALOGW_IF(mEffectChains.size() != 1,
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007585 "removeEffectChain_l() %p invalid chain size %zu on thread %p",
Eric Laurent81784c32012-11-19 14:55:58 -08007586 chain.get(), mEffectChains.size(), this);
7587 if (mEffectChains.size() == 1) {
7588 mEffectChains.removeAt(0);
7589 }
7590 return 0;
7591}
7592
Eric Laurent1c333e22014-05-20 10:48:17 -07007593status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7594 audio_patch_handle_t *handle)
7595{
7596 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007597
7598 // store new device and send to effects
7599 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07007600 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07007601 for (size_t i = 0; i < mEffectChains.size(); i++) {
7602 mEffectChains[i]->setDevice_l(mInDevice);
7603 }
7604
7605 // disable AEC and NS if the device is a BT SCO headset supporting those
7606 // pre processings
7607 if (mTracks.size() > 0) {
7608 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7609 mAudioFlinger->btNrecIsOff();
7610 for (size_t i = 0; i < mTracks.size(); i++) {
7611 sp<RecordTrack> track = mTracks[i];
7612 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7613 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
7614 }
7615 }
7616
7617 // store new source and send to effects
7618 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7619 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07007620 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07007621 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07007622 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007623 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007624
Eric Laurent054d9d32015-04-24 08:48:48 -07007625 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007626 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
7627 status = hwDevice->create_audio_patch(hwDevice,
7628 patch->num_sources,
7629 patch->sources,
7630 patch->num_sinks,
7631 patch->sinks,
7632 handle);
7633 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007634 char *address;
7635 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7636 address = audio_device_address_to_parameter(
7637 patch->sources[0].ext.device.type,
7638 patch->sources[0].ext.device.address);
7639 } else {
7640 address = (char *)calloc(1, 1);
7641 }
7642 AudioParameter param = AudioParameter(String8(address));
7643 free(address);
7644 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING),
7645 (int)patch->sources[0].ext.device.type);
7646 param.addInt(String8(AUDIO_PARAMETER_STREAM_INPUT_SOURCE),
7647 (int)patch->sinks[0].ext.mix.usecase.source);
7648 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7649 param.toString().string());
7650 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07007651 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007652
Eric Laurente8726fe2015-06-26 09:39:24 -07007653 if (mInDevice != mPrevInDevice) {
7654 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7655 mPrevInDevice = mInDevice;
7656 }
Eric Laurent296fb132015-05-01 11:38:42 -07007657
Eric Laurent1c333e22014-05-20 10:48:17 -07007658 return status;
7659}
7660
7661status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7662{
7663 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007664
7665 mInDevice = AUDIO_DEVICE_NONE;
7666
Eric Laurent1c333e22014-05-20 10:48:17 -07007667 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
7668 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
7669 status = hwDevice->release_audio_patch(hwDevice, handle);
7670 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007671 AudioParameter param;
7672 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
7673 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7674 param.toString().string());
Eric Laurent1c333e22014-05-20 10:48:17 -07007675 }
7676 return status;
7677}
7678
Eric Laurent83b88082014-06-20 18:31:16 -07007679void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
7680{
7681 Mutex::Autolock _l(mLock);
7682 mTracks.add(record);
7683}
7684
7685void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
7686{
7687 Mutex::Autolock _l(mLock);
7688 destroyTrack_l(record);
7689}
7690
7691void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
7692{
7693 ThreadBase::getAudioPortConfig(config);
7694 config->role = AUDIO_PORT_ROLE_SINK;
7695 config->ext.mix.hw_module = mInput->audioHwDev->handle();
7696 config->ext.mix.usecase.source = mAudioSource;
7697}
Eric Laurent1c333e22014-05-20 10:48:17 -07007698
Glenn Kasten63238ef2015-03-02 15:50:29 -08007699} // namespace android