blob: 6b5651db9cb5ba235a50288f6d30489e81078eea [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
Chih-Hung Hsiehbf291732016-05-17 15:16:07 -0700100#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
Andy Hungd330ee42015-04-20 13:23:41 -0700101#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++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001156 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001157 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 }
1275 audio_input_flags_t flags = mInput->flags;
1276 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1277 if (flags & AUDIO_INPUT_FLAG_RAW) {
1278 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1279 desc->name, mThreadName);
1280 return BAD_VALUE;
1281 }
1282 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1283 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1284 desc->name, mThreadName);
1285 return BAD_VALUE;
1286 }
1287 }
1288 return NO_ERROR;
1289}
1290
1291// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1292status_t AudioFlinger::PlaybackThread::checkEffectCompatibility_l(
1293 const effect_descriptor_t *desc, audio_session_t sessionId)
1294{
1295 // no preprocessing on playback threads
1296 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
1297 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback"
1298 " thread %s", desc->name, mThreadName);
1299 return BAD_VALUE;
1300 }
1301
1302 switch (mType) {
1303 case MIXER: {
1304 // Reject any effect on mixer multichannel sinks.
1305 // TODO: fix both format and multichannel issues with effects.
1306 if (mChannelCount != FCC_2) {
1307 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d) on MIXER"
1308 " thread %s", desc->name, mChannelCount, mThreadName);
1309 return BAD_VALUE;
1310 }
1311 audio_output_flags_t flags = mOutput->flags;
1312 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1313 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1314 // global effects are applied only to non fast tracks if they are SW
1315 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1316 break;
1317 }
1318 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1319 // only post processing on output stage session
1320 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1321 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1322 " on output stage session", desc->name);
1323 return BAD_VALUE;
1324 }
1325 } else {
1326 // no restriction on effects applied on non fast tracks
1327 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1328 break;
1329 }
1330 }
1331 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
1332 ALOGW("checkEffectCompatibility_l(): effect %s on playback thread in raw mode",
1333 desc->name);
1334 return BAD_VALUE;
1335 }
1336 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1337 ALOGW("checkEffectCompatibility_l(): non HW effect %s on playback thread"
1338 " in fast mode", desc->name);
1339 return BAD_VALUE;
1340 }
1341 }
1342 } break;
1343 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001344 // nothing actionable on offload threads, if the effect:
1345 // - is offloadable: the effect can be created
1346 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1347 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001348 break;
1349 case DIRECT:
1350 // Reject any effect on Direct output threads for now, since the format of
1351 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1352 ALOGW("checkEffectCompatibility_l(): effect %s on DIRECT output thread %s",
1353 desc->name, mThreadName);
1354 return BAD_VALUE;
1355 case DUPLICATING:
1356 // Reject any effect on mixer multichannel sinks.
1357 // TODO: fix both format and multichannel issues with effects.
1358 if (mChannelCount != FCC_2) {
1359 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d)"
1360 " on DUPLICATING thread %s", desc->name, mChannelCount, mThreadName);
1361 return BAD_VALUE;
1362 }
1363 if ((sessionId == AUDIO_SESSION_OUTPUT_STAGE) || (sessionId == AUDIO_SESSION_OUTPUT_MIX)) {
1364 ALOGW("checkEffectCompatibility_l(): global effect %s on DUPLICATING"
1365 " thread %s", desc->name, mThreadName);
1366 return BAD_VALUE;
1367 }
1368 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
1369 ALOGW("checkEffectCompatibility_l(): post processing effect %s on"
1370 " DUPLICATING thread %s", desc->name, mThreadName);
1371 return BAD_VALUE;
1372 }
1373 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1374 ALOGW("checkEffectCompatibility_l(): HW tunneled effect %s on"
1375 " DUPLICATING thread %s", desc->name, mThreadName);
1376 return BAD_VALUE;
1377 }
1378 break;
1379 default:
1380 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1381 }
1382
1383 return NO_ERROR;
1384}
1385
Eric Laurent81784c32012-11-19 14:55:58 -08001386// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1387sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1388 const sp<AudioFlinger::Client>& client,
1389 const sp<IEffectClient>& effectClient,
1390 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001391 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001392 effect_descriptor_t *desc,
1393 int *enabled,
Glenn Kasten9156ef32013-08-06 15:39:08 -07001394 status_t *status)
Eric Laurent81784c32012-11-19 14:55:58 -08001395{
1396 sp<EffectModule> effect;
1397 sp<EffectHandle> handle;
1398 status_t lStatus;
1399 sp<EffectChain> chain;
1400 bool chainCreated = false;
1401 bool effectCreated = false;
1402 bool effectRegistered = false;
1403
1404 lStatus = initCheck();
1405 if (lStatus != NO_ERROR) {
1406 ALOGW("createEffect_l() Audio driver not initialized.");
1407 goto Exit;
1408 }
1409
Eric Laurent81784c32012-11-19 14:55:58 -08001410 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1411
1412 { // scope for mLock
1413 Mutex::Autolock _l(mLock);
1414
Eric Laurent4c415062016-06-17 16:14:16 -07001415 lStatus = checkEffectCompatibility_l(desc, sessionId);
1416 if (lStatus != NO_ERROR) {
1417 goto Exit;
1418 }
1419
Eric Laurent81784c32012-11-19 14:55:58 -08001420 // check for existing effect chain with the requested audio session
1421 chain = getEffectChain_l(sessionId);
1422 if (chain == 0) {
1423 // create a new chain for this session
1424 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1425 chain = new EffectChain(this, sessionId);
1426 addEffectChain_l(chain);
1427 chain->setStrategy(getStrategyForSession_l(sessionId));
1428 chainCreated = true;
1429 } else {
1430 effect = chain->getEffectFromDesc_l(desc);
1431 }
1432
1433 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1434
1435 if (effect == 0) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08001436 audio_unique_id_t id = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001437 // Check CPU and memory usage
1438 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
1439 if (lStatus != NO_ERROR) {
1440 goto Exit;
1441 }
1442 effectRegistered = true;
1443 // create a new effect module if none present in the chain
1444 effect = new EffectModule(this, chain, desc, id, sessionId);
1445 lStatus = effect->status();
1446 if (lStatus != NO_ERROR) {
1447 goto Exit;
1448 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001449 effect->setOffloaded(mType == OFFLOAD, mId);
1450
Eric Laurent81784c32012-11-19 14:55:58 -08001451 lStatus = chain->addEffect_l(effect);
1452 if (lStatus != NO_ERROR) {
1453 goto Exit;
1454 }
1455 effectCreated = true;
1456
1457 effect->setDevice(mOutDevice);
1458 effect->setDevice(mInDevice);
1459 effect->setMode(mAudioFlinger->getMode());
1460 effect->setAudioSource(mAudioSource);
1461 }
1462 // create effect handle and connect it to effect module
1463 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001464 lStatus = handle->initCheck();
1465 if (lStatus == OK) {
1466 lStatus = effect->addHandle(handle.get());
1467 }
Eric Laurent81784c32012-11-19 14:55:58 -08001468 if (enabled != NULL) {
1469 *enabled = (int)effect->isEnabled();
1470 }
1471 }
1472
1473Exit:
1474 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1475 Mutex::Autolock _l(mLock);
1476 if (effectCreated) {
1477 chain->removeEffect_l(effect);
1478 }
1479 if (effectRegistered) {
1480 AudioSystem::unregisterEffect(effect->id());
1481 }
1482 if (chainCreated) {
1483 removeEffectChain_l(chain);
1484 }
1485 handle.clear();
1486 }
1487
Glenn Kasten9156ef32013-08-06 15:39:08 -07001488 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001489 return handle;
1490}
1491
Glenn Kastend848eb42016-03-08 13:42:11 -08001492sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1493 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001494{
1495 Mutex::Autolock _l(mLock);
1496 return getEffect_l(sessionId, effectId);
1497}
1498
Glenn Kastend848eb42016-03-08 13:42:11 -08001499sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1500 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001501{
1502 sp<EffectChain> chain = getEffectChain_l(sessionId);
1503 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1504}
1505
1506// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1507// PlaybackThread::mLock held
1508status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1509{
1510 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001511 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001512 sp<EffectChain> chain = getEffectChain_l(sessionId);
1513 bool chainCreated = false;
1514
Eric Laurent5baf2af2013-09-12 17:37:00 -07001515 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1516 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1517 this, effect->desc().name, effect->desc().flags);
1518
Eric Laurent81784c32012-11-19 14:55:58 -08001519 if (chain == 0) {
1520 // create a new chain for this session
1521 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1522 chain = new EffectChain(this, sessionId);
1523 addEffectChain_l(chain);
1524 chain->setStrategy(getStrategyForSession_l(sessionId));
1525 chainCreated = true;
1526 }
1527 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1528
1529 if (chain->getEffectFromId_l(effect->id()) != 0) {
1530 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1531 this, effect->desc().name, chain.get());
1532 return BAD_VALUE;
1533 }
1534
Eric Laurent5baf2af2013-09-12 17:37:00 -07001535 effect->setOffloaded(mType == OFFLOAD, mId);
1536
Eric Laurent81784c32012-11-19 14:55:58 -08001537 status_t status = chain->addEffect_l(effect);
1538 if (status != NO_ERROR) {
1539 if (chainCreated) {
1540 removeEffectChain_l(chain);
1541 }
1542 return status;
1543 }
1544
1545 effect->setDevice(mOutDevice);
1546 effect->setDevice(mInDevice);
1547 effect->setMode(mAudioFlinger->getMode());
1548 effect->setAudioSource(mAudioSource);
1549 return NO_ERROR;
1550}
1551
1552void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
1553
1554 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
1555 effect_descriptor_t desc = effect->desc();
1556 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1557 detachAuxEffect_l(effect->id());
1558 }
1559
1560 sp<EffectChain> chain = effect->chain().promote();
1561 if (chain != 0) {
1562 // remove effect chain if removing last effect
1563 if (chain->removeEffect_l(effect) == 0) {
1564 removeEffectChain_l(chain);
1565 }
1566 } else {
1567 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1568 }
1569}
1570
1571void AudioFlinger::ThreadBase::lockEffectChains_l(
1572 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1573{
1574 effectChains = mEffectChains;
1575 for (size_t i = 0; i < mEffectChains.size(); i++) {
1576 mEffectChains[i]->lock();
1577 }
1578}
1579
1580void AudioFlinger::ThreadBase::unlockEffectChains(
1581 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1582{
1583 for (size_t i = 0; i < effectChains.size(); i++) {
1584 effectChains[i]->unlock();
1585 }
1586}
1587
Glenn Kastend848eb42016-03-08 13:42:11 -08001588sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001589{
1590 Mutex::Autolock _l(mLock);
1591 return getEffectChain_l(sessionId);
1592}
1593
Glenn Kastend848eb42016-03-08 13:42:11 -08001594sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1595 const
Eric Laurent81784c32012-11-19 14:55:58 -08001596{
1597 size_t size = mEffectChains.size();
1598 for (size_t i = 0; i < size; i++) {
1599 if (mEffectChains[i]->sessionId() == sessionId) {
1600 return mEffectChains[i];
1601 }
1602 }
1603 return 0;
1604}
1605
1606void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1607{
1608 Mutex::Autolock _l(mLock);
1609 size_t size = mEffectChains.size();
1610 for (size_t i = 0; i < size; i++) {
1611 mEffectChains[i]->setMode_l(mode);
1612 }
1613}
1614
Eric Laurent83b88082014-06-20 18:31:16 -07001615void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1616{
1617 config->type = AUDIO_PORT_TYPE_MIX;
1618 config->ext.mix.handle = mId;
1619 config->sample_rate = mSampleRate;
1620 config->format = mFormat;
1621 config->channel_mask = mChannelMask;
1622 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1623 AUDIO_PORT_CONFIG_FORMAT;
1624}
1625
Eric Laurent72e3f392015-05-20 14:43:50 -07001626void AudioFlinger::ThreadBase::systemReady()
1627{
1628 Mutex::Autolock _l(mLock);
1629 if (mSystemReady) {
1630 return;
1631 }
1632 mSystemReady = true;
1633
1634 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1635 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1636 }
1637 mPendingConfigEvents.clear();
1638}
1639
Eric Laurent83b88082014-06-20 18:31:16 -07001640
Eric Laurent81784c32012-11-19 14:55:58 -08001641// ----------------------------------------------------------------------------
1642// Playback
1643// ----------------------------------------------------------------------------
1644
1645AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1646 AudioStreamOut* output,
1647 audio_io_handle_t id,
1648 audio_devices_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07001649 type_t type,
Eric Laurente93cc032016-05-05 10:15:10 -07001650 bool systemReady)
Eric Laurent72e3f392015-05-20 14:43:50 -07001651 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001652 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001653 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001654 mMixerBuffer(NULL),
1655 mMixerBufferSize(0),
1656 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1657 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001658 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001659 mEffectBuffer(NULL),
1660 mEffectBufferSize(0),
1661 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1662 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001663 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001664 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07001665 mSuspendedFrames(0),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001666 mActiveTracksGeneration(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001667 // mStreamTypes[] initialized in constructor body
1668 mOutput(output),
Andy Hung69488c42016-05-16 18:43:33 -07001669 mLastWriteTime(-1), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001670 mMixerStatus(MIXER_IDLE),
1671 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001672 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001673 mBytesRemaining(0),
1674 mCurrentWriteLength(0),
1675 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001676 mWriteAckSequence(0),
1677 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001678 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001679 mScreenState(AudioFlinger::mScreenState),
1680 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001681 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Andy Hunge10393e2015-06-12 13:59:33 -07001682 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001683{
Glenn Kastend7dca052015-03-05 16:05:54 -08001684 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1685 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001686
1687 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1688 // it would be safer to explicitly pass initial masterVolume/masterMute as
1689 // parameter.
1690 //
1691 // If the HAL we are using has support for master volume or master mute,
1692 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1693 // and the mute set to false).
1694 mMasterVolume = audioFlinger->masterVolume_l();
1695 mMasterMute = audioFlinger->masterMute_l();
1696 if (mOutput && mOutput->audioHwDev) {
1697 if (mOutput->audioHwDev->canSetMasterVolume()) {
1698 mMasterVolume = 1.0;
1699 }
1700
1701 if (mOutput->audioHwDev->canSetMasterMute()) {
1702 mMasterMute = false;
1703 }
1704 }
1705
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001706 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001707
Eric Laurent223fd5c2014-11-11 13:43:36 -08001708 // ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001709 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001710 stream = (audio_stream_type_t) (stream + 1)) {
1711 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1712 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1713 }
Eric Laurent81784c32012-11-19 14:55:58 -08001714}
1715
1716AudioFlinger::PlaybackThread::~PlaybackThread()
1717{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001718 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001719 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001720 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001721 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001722}
1723
1724void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1725{
1726 dumpInternals(fd, args);
1727 dumpTracks(fd, args);
1728 dumpEffectChains(fd, args);
1729}
1730
Glenn Kasten0f11b512014-01-31 16:18:54 -08001731void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001732{
1733 const size_t SIZE = 256;
1734 char buffer[SIZE];
1735 String8 result;
1736
Marco Nelissenb2208842014-02-07 14:00:50 -08001737 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001738 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1739 const stream_type_t *st = &mStreamTypes[i];
1740 if (i > 0) {
1741 result.appendFormat(", ");
1742 }
1743 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1744 if (st->mute) {
1745 result.append("M");
1746 }
1747 }
1748 result.append("\n");
1749 write(fd, result.string(), result.length());
1750 result.clear();
1751
Eric Laurent81784c32012-11-19 14:55:58 -08001752 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1753 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001754 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001755 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001756
1757 size_t numtracks = mTracks.size();
1758 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001759 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001760 size_t numactiveseen = 0;
1761 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001762 dprintf(fd, " of which %zu are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001763 Track::appendDumpHeader(result);
1764 for (size_t i = 0; i < numtracks; ++i) {
1765 sp<Track> track = mTracks[i];
1766 if (track != 0) {
1767 bool active = mActiveTracks.indexOf(track) >= 0;
1768 if (active) {
1769 numactiveseen++;
1770 }
1771 track->dump(buffer, SIZE, active);
1772 result.append(buffer);
1773 }
1774 }
1775 } else {
1776 result.append("\n");
1777 }
1778 if (numactiveseen != numactive) {
1779 // some tracks in the active list were not in the tracks list
1780 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1781 " not in the track list\n");
1782 result.append(buffer);
1783 Track::appendDumpHeader(result);
1784 for (size_t i = 0; i < numactive; ++i) {
1785 sp<Track> track = mActiveTracks[i].promote();
1786 if (track != 0 && mTracks.indexOf(track) < 0) {
1787 track->dump(buffer, SIZE, true);
1788 result.append(buffer);
1789 }
1790 }
1791 }
1792
1793 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001794}
1795
1796void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1797{
Glenn Kasten97b7b752014-09-28 13:04:24 -07001798 dprintf(fd, "\nOutput thread %p type %d (%s):\n", this, type(), threadTypeToString(type()));
Glenn Kasten44182c22015-03-05 17:12:23 -08001799
1800 dumpBase(fd, args);
1801
Elliott Hughes87cebad2014-05-22 10:14:43 -07001802 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001803 dprintf(fd, " Last write occurred (msecs): %llu\n",
1804 (unsigned long long) ns2ms(systemTime() - mLastWriteTime));
Elliott Hughes87cebad2014-05-22 10:14:43 -07001805 dprintf(fd, " Total writes: %d\n", mNumWrites);
1806 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1807 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1808 dprintf(fd, " Suspend count: %d\n", mSuspended);
1809 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1810 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1811 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1812 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08001813 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001814 AudioStreamOut *output = mOutput;
1815 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
1816 String8 flagsAsString = outputFlagsToString(flags);
1817 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n", output, flags, flagsAsString.string());
Eric Laurent81784c32012-11-19 14:55:58 -08001818}
1819
1820// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001821
1822void AudioFlinger::PlaybackThread::onFirstRef()
1823{
Glenn Kastend7dca052015-03-05 16:05:54 -08001824 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001825}
1826
1827// ThreadBase virtuals
1828void AudioFlinger::PlaybackThread::preExit()
1829{
1830 ALOGV(" preExit()");
1831 // FIXME this is using hard-coded strings but in the future, this functionality will be
1832 // converted to use audio HAL extensions required to support tunneling
1833 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1834}
1835
1836// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1837sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1838 const sp<AudioFlinger::Client>& client,
1839 audio_stream_type_t streamType,
1840 uint32_t sampleRate,
1841 audio_format_t format,
1842 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001843 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001844 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08001845 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07001846 audio_output_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08001847 pid_t tid,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001848 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -08001849 status_t *status)
1850{
Glenn Kasten74935e42013-12-19 08:56:45 -08001851 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001852 sp<Track> track;
1853 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07001854 audio_output_flags_t outputFlags = mOutput->flags;
1855
1856 // special case for FAST flag considered OK if fast mixer is present
1857 if (hasFastMixer()) {
1858 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
1859 }
1860
1861 // Check if requested flags are compatible with output stream flags
1862 if ((*flags & outputFlags) != *flags) {
1863 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
1864 *flags, outputFlags);
1865 *flags = (audio_output_flags_t)(*flags & outputFlags);
1866 }
Eric Laurent81784c32012-11-19 14:55:58 -08001867
Eric Laurent81784c32012-11-19 14:55:58 -08001868 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07001869 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08001870 if (
Eric Laurent81784c32012-11-19 14:55:58 -08001871 // PCM data
1872 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001873 // TODO: extract as a data library function that checks that a computationally
1874 // expensive downmixer is not required: isFastOutputChannelConversion()
Andy Hung9a592762014-07-21 21:56:01 -07001875 (channelMask == mChannelMask ||
Andy Hung1f439e12015-05-19 12:57:41 -07001876 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1877 (channelMask == AUDIO_CHANNEL_OUT_MONO
1878 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001879 // hardware sample rate
1880 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001881 // normal mixer has an associated fast mixer
1882 hasFastMixer() &&
1883 // there are sufficient fast track slots available
1884 (mFastTrackAvailMask != 0)
1885 // FIXME test that MixerThread for this fast track has a capable output HAL
1886 // FIXME add a permission test also?
1887 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07001888 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
1889 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001890 // read the fast track multiplier property the first time it is needed
1891 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1892 if (ok != 0) {
1893 ALOGE("%s pthread_once failed: %d", __func__, ok);
1894 }
Andy Hunge0a269a2016-03-23 15:13:42 -07001895 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08001896 }
Eric Laurent4c415062016-06-17 16:14:16 -07001897
1898 // check compatibility with audio effects.
1899 { // scope for mLock
1900 Mutex::Autolock _l(mLock);
1901 // do not accept RAW flag if post processing are present. Note that post processing on
1902 // a fast mixer are necessarily hardware
1903 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE);
1904 if (chain != 0) {
Eric Laurent122f7e72016-06-29 11:53:29 -07001905 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_RAW) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07001906 "AUDIO_OUTPUT_FLAG_RAW denied: post processing effect present");
1907 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_RAW);
1908 }
1909 // Do not accept FAST flag if software global effects are present
1910 chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
1911 if (chain != 0) {
Eric Laurent122f7e72016-06-29 11:53:29 -07001912 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_RAW) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07001913 "AUDIO_OUTPUT_FLAG_RAW denied: global effect present");
1914 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_RAW);
1915 if (chain->hasSoftwareEffect()) {
1916 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: software global effect present");
1917 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
1918 }
1919 }
1920 // Do not accept FAST flag if the session has software effects
1921 chain = getEffectChain_l(sessionId);
1922 if (chain != 0) {
Eric Laurent122f7e72016-06-29 11:53:29 -07001923 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_RAW) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07001924 "AUDIO_OUTPUT_FLAG_RAW denied: effect present on session");
1925 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_RAW);
1926 if (chain->hasSoftwareEffect()) {
1927 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: software effect present on session");
1928 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
1929 }
1930 }
1931 }
Eric Laurent122f7e72016-06-29 11:53:29 -07001932 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07001933 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
1934 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08001935 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001936 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
1937 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07001938 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001939 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08001940 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001941 audio_is_linear_pcm(format),
1942 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07001943 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08001944 }
1945 }
1946 // For normal PCM streaming tracks, update minimum frame count.
1947 // For compatibility with AudioTrack calculation, buffer depth is forced
1948 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1949 // This is probably too conservative, but legacy application code may depend on it.
1950 // If you change this calculation, also review the start threshold which is related.
Eric Laurent05067782016-06-01 18:27:28 -07001951 if (!(*flags & AUDIO_OUTPUT_FLAG_FAST)
Phil Burkfdb3c072016-02-09 10:47:02 -08001952 && audio_has_proportional_frames(format) && sharedBuffer == 0) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001953 // this must match AudioTrack.cpp calculateMinFrameCount().
1954 // TODO: Move to a common library
Eric Laurent81784c32012-11-19 14:55:58 -08001955 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1956 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1957 if (minBufCount < 2) {
1958 minBufCount = 2;
1959 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07001960 // For normal mixing tracks, if speed is > 1.0f (normal), AudioTrack
1961 // or the client should compute and pass in a larger buffer request.
Andy Hung0e48d252015-01-26 11:43:15 -08001962 size_t minFrameCount =
Andy Hung8edb8dc2015-03-26 19:13:55 -07001963 minBufCount * sourceFramesNeededWithTimestretch(
1964 sampleRate, mNormalFrameCount,
1965 mSampleRate, AUDIO_TIMESTRETCH_SPEED_NORMAL /*speed*/);
Andy Hung0e48d252015-01-26 11:43:15 -08001966 if (frameCount < minFrameCount) { // including frameCount == 0
Eric Laurent81784c32012-11-19 14:55:58 -08001967 frameCount = minFrameCount;
1968 }
Eric Laurent81784c32012-11-19 14:55:58 -08001969 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001970 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001971
Glenn Kastenc3df8382014-03-13 15:05:25 -07001972 switch (mType) {
1973
1974 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08001975 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08001976 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001977 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1978 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001979 sampleRate, format, channelMask, mOutput, mFormat);
1980 lStatus = BAD_VALUE;
1981 goto Exit;
1982 }
1983 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001984 break;
1985
1986 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001987 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001988 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1989 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001990 sampleRate, format, channelMask, mOutput, mFormat);
1991 lStatus = BAD_VALUE;
1992 goto Exit;
1993 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001994 break;
1995
1996 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001997 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001998 ALOGE("createTrack_l() Bad parameter: format %#x \""
1999 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002000 format, mOutput, mFormat);
2001 lStatus = BAD_VALUE;
2002 goto Exit;
2003 }
Andy Hungcd044842014-08-07 11:04:34 -07002004 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002005 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2006 lStatus = BAD_VALUE;
2007 goto Exit;
2008 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002009 break;
2010
Eric Laurent81784c32012-11-19 14:55:58 -08002011 }
2012
2013 lStatus = initCheck();
2014 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002015 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002016 goto Exit;
2017 }
2018
2019 { // scope for mLock
2020 Mutex::Autolock _l(mLock);
2021
2022 // all tracks in same audio session must share the same routing strategy otherwise
2023 // conflicts will happen when tracks are moved from one output to another by audio policy
2024 // manager
2025 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
2026 for (size_t i = 0; i < mTracks.size(); ++i) {
2027 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002028 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002029 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
2030 if (sessionId == t->sessionId() && strategy != actual) {
2031 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2032 strategy, actual);
2033 lStatus = BAD_VALUE;
2034 goto Exit;
2035 }
2036 }
2037 }
2038
Glenn Kastend79072e2016-01-06 08:41:20 -08002039 track = new Track(this, client, streamType, sampleRate, format,
2040 channelMask, frameCount, NULL, sharedBuffer,
2041 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT);
Glenn Kasten03003332013-08-06 15:40:54 -07002042
Glenn Kasten03003332013-08-06 15:40:54 -07002043 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2044 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002045 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002046 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002047 goto Exit;
2048 }
2049 mTracks.add(track);
2050
2051 sp<EffectChain> chain = getEffectChain_l(sessionId);
2052 if (chain != 0) {
2053 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2054 track->setMainBuffer(chain->inBuffer());
2055 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
2056 chain->incTrackCnt();
2057 }
2058
Eric Laurent05067782016-06-01 18:27:28 -07002059 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002060 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2061 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2062 // so ask activity manager to do this on our behalf
2063 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
2064 }
2065 }
2066
2067 lStatus = NO_ERROR;
2068
2069Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002070 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002071 return track;
2072}
2073
2074uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2075{
2076 return latency;
2077}
2078
2079uint32_t AudioFlinger::PlaybackThread::latency() const
2080{
2081 Mutex::Autolock _l(mLock);
2082 return latency_l();
2083}
2084uint32_t AudioFlinger::PlaybackThread::latency_l() const
2085{
2086 if (initCheck() == NO_ERROR) {
2087 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
2088 } else {
2089 return 0;
2090 }
2091}
2092
2093void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2094{
2095 Mutex::Autolock _l(mLock);
2096 // Don't apply master volume in SW if our HAL can do it for us.
2097 if (mOutput && mOutput->audioHwDev &&
2098 mOutput->audioHwDev->canSetMasterVolume()) {
2099 mMasterVolume = 1.0;
2100 } else {
2101 mMasterVolume = value;
2102 }
2103}
2104
2105void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2106{
2107 Mutex::Autolock _l(mLock);
2108 // Don't apply master mute in SW if our HAL can do it for us.
2109 if (mOutput && mOutput->audioHwDev &&
2110 mOutput->audioHwDev->canSetMasterMute()) {
2111 mMasterMute = false;
2112 } else {
2113 mMasterMute = muted;
2114 }
2115}
2116
2117void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2118{
2119 Mutex::Autolock _l(mLock);
2120 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002121 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002122}
2123
2124void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2125{
2126 Mutex::Autolock _l(mLock);
2127 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002128 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002129}
2130
2131float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2132{
2133 Mutex::Autolock _l(mLock);
2134 return mStreamTypes[stream].volume;
2135}
2136
2137// addTrack_l() must be called with ThreadBase::mLock held
2138status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2139{
2140 status_t status = ALREADY_EXISTS;
2141
Eric Laurent81784c32012-11-19 14:55:58 -08002142 if (mActiveTracks.indexOf(track) < 0) {
2143 // the track is newly added, make sure it fills up all its
2144 // buffers before playing. This is to ensure the client will
2145 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002146 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002147 TrackBase::track_state state = track->mState;
2148 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002149 status = AudioSystem::startOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002150 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002151 mLock.lock();
2152 // abort track was stopped/paused while we released the lock
2153 if (state != track->mState) {
2154 if (status == NO_ERROR) {
2155 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002156 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002157 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002158 mLock.lock();
2159 }
2160 return INVALID_OPERATION;
2161 }
2162 // abort if start is rejected by audio policy manager
2163 if (status != NO_ERROR) {
2164 return PERMISSION_DENIED;
2165 }
2166#ifdef ADD_BATTERY_DATA
2167 // to track the speaker usage
2168 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2169#endif
2170 }
2171
Eric Laurent51716182016-02-29 18:00:56 -08002172 // set retry count for buffer fill
2173 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002174 if (track->isStopping_1()) {
2175 track->mRetryCount = kMaxTrackStopRetriesOffload;
2176 } else {
2177 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2178 }
2179 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002180 } else {
2181 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002182 track->mFillingUpStatus =
2183 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002184 }
2185
Eric Laurent81784c32012-11-19 14:55:58 -08002186 track->mResetDone = false;
2187 track->mPresentationCompleteFrames = 0;
2188 mActiveTracks.add(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002189 mWakeLockUids.add(track->uid());
2190 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07002191 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07002192 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2193 if (chain != 0) {
2194 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2195 track->sessionId());
2196 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002197 }
2198
2199 status = NO_ERROR;
2200 }
2201
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002202 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002203 return status;
2204}
2205
Eric Laurentbfb1b832013-01-07 09:53:42 -08002206bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002207{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002208 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002209 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002210 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2211 track->mState = TrackBase::STOPPED;
2212 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002213 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002214 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002215 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002216 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002217
2218 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002219}
2220
2221void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2222{
2223 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
2224 mTracks.remove(track);
2225 deleteTrackName_l(track->name());
2226 // redundant as track is about to be destroyed, for dumpsys only
2227 track->mName = -1;
2228 if (track->isFastTrack()) {
2229 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002230 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002231 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2232 mFastTrackAvailMask |= 1 << index;
2233 // redundant as track is about to be destroyed, for dumpsys only
2234 track->mFastIndex = -1;
2235 }
2236 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2237 if (chain != 0) {
2238 chain->decTrackCnt();
2239 }
2240}
2241
Eric Laurentede6c3b2013-09-19 14:37:46 -07002242void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002243{
2244 // Thread could be blocked waiting for async
2245 // so signal it to handle state changes immediately
2246 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
2247 // be lost so we also flag to prevent it blocking on mWaitWorkCV
2248 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002249 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002250}
2251
Eric Laurent81784c32012-11-19 14:55:58 -08002252String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2253{
Eric Laurent81784c32012-11-19 14:55:58 -08002254 Mutex::Autolock _l(mLock);
2255 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07002256 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002257 }
2258
Glenn Kastend8ea6992013-07-16 14:17:15 -07002259 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
2260 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08002261 free(s);
2262 return out_s8;
2263}
2264
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002265void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002266 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2267 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002268
Eric Laurent73e26b62015-04-27 16:55:58 -07002269 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002270
2271 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002272 case AUDIO_OUTPUT_OPENED:
2273 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002274 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002275 desc->mChannelMask = mChannelMask;
2276 desc->mSamplingRate = mSampleRate;
2277 desc->mFormat = mFormat;
2278 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002279 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002280 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002281 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002282 break;
2283
Eric Laurent73e26b62015-04-27 16:55:58 -07002284 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002285 default:
2286 break;
2287 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002288 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002289}
2290
Eric Laurentbfb1b832013-01-07 09:53:42 -08002291void AudioFlinger::PlaybackThread::writeCallback()
2292{
2293 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002294 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002295}
2296
2297void AudioFlinger::PlaybackThread::drainCallback()
2298{
2299 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002300 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002301}
2302
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002303void AudioFlinger::PlaybackThread::errorCallback()
2304{
2305 ALOG_ASSERT(mCallbackThread != 0);
2306 mCallbackThread->setAsyncError();
2307}
2308
Eric Laurent3b4529e2013-09-05 18:09:19 -07002309void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002310{
2311 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002312 // reject out of sequence requests
2313 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2314 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002315 mWaitWorkCV.signal();
2316 }
2317}
2318
Eric Laurent3b4529e2013-09-05 18:09:19 -07002319void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002320{
2321 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002322 // reject out of sequence requests
2323 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
2324 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002325 mWaitWorkCV.signal();
2326 }
2327}
2328
2329// static
2330int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
Glenn Kasten0f11b512014-01-31 16:18:54 -08002331 void *param __unused,
Eric Laurentbfb1b832013-01-07 09:53:42 -08002332 void *cookie)
2333{
2334 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
2335 ALOGV("asyncCallback() event %d", event);
2336 switch (event) {
2337 case STREAM_CBK_EVENT_WRITE_READY:
2338 me->writeCallback();
2339 break;
2340 case STREAM_CBK_EVENT_DRAIN_READY:
2341 me->drainCallback();
2342 break;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002343 case STREAM_CBK_EVENT_ERROR:
2344 me->errorCallback();
2345 break;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002346 default:
2347 ALOGW("asyncCallback() unknown event %d", event);
2348 break;
2349 }
2350 return 0;
2351}
2352
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002353void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002354{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002355 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002356 mSampleRate = mOutput->getSampleRate();
2357 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002358 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002359 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002360 }
Andy Hung9a592762014-07-21 21:56:01 -07002361 if ((mType == MIXER || mType == DUPLICATING)
2362 && !isValidPcmSinkChannelMask(mChannelMask)) {
2363 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2364 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002365 }
Andy Hunge5412692014-05-16 11:25:07 -07002366 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002367
2368 // Get actual HAL format.
Andy Hung463be252014-07-10 16:56:07 -07002369 mHALFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Phil Burkca5e6142015-07-14 09:42:29 -07002370 // Get format from the shim, which will be different than the HAL format
2371 // if playing compressed audio over HDMI passthrough.
2372 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002373 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002374 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002375 }
Andy Hung6146c082014-03-18 11:56:15 -07002376 if ((mType == MIXER || mType == DUPLICATING)
2377 && !isValidPcmSinkFormat(mFormat)) {
2378 LOG_FATAL("HAL format %#x not supported for mixed output",
2379 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002380 }
Phil Burk062e67a2015-02-11 13:40:50 -08002381 mFrameSize = mOutput->getFrameSize();
Glenn Kasten70949c42013-08-06 07:40:12 -07002382 mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
2383 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002384 if (mFrameCount & 15) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002385 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002386 mFrameCount);
2387 }
2388
Eric Laurentbfb1b832013-01-07 09:53:42 -08002389 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
2390 (mOutput->stream->set_callback != NULL)) {
2391 if (mOutput->stream->set_callback(mOutput->stream,
2392 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
2393 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002394 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002395 }
2396 }
2397
Eric Laurentd1f69b02014-12-15 14:33:13 -08002398 mHwSupportsPause = false;
2399 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
2400 if (mOutput->stream->pause != NULL) {
2401 if (mOutput->stream->resume != NULL) {
2402 mHwSupportsPause = true;
2403 } else {
2404 ALOGW("direct output implements pause but not resume");
2405 }
2406 } else if (mOutput->stream->resume != NULL) {
2407 ALOGW("direct output implements resume but not pause");
2408 }
2409 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002410 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2411 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2412 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002413
Andy Hungfbfc3952015-01-15 13:33:51 -08002414 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2415 // For best precision, we use float instead of the associated output
2416 // device format (typically PCM 16 bit).
2417
2418 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2419 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2420 mBufferSize = mFrameSize * mFrameCount;
2421
2422 // TODO: We currently use the associated output device channel mask and sample rate.
2423 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2424 // (if a valid mask) to avoid premature downmix.
2425 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2426 // instead of the output device sample rate to avoid loss of high frequency information.
2427 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2428 }
2429
Andy Hung09a50072014-02-27 14:30:47 -08002430 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002431 double multiplier = 1.0;
2432 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2433 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002434 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2435 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002436
Eric Laurent81784c32012-11-19 14:55:58 -08002437 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2438 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2439 maxNormalFrameCount = maxNormalFrameCount & ~15;
2440 if (maxNormalFrameCount < minNormalFrameCount) {
2441 maxNormalFrameCount = minNormalFrameCount;
2442 }
2443 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2444 if (multiplier <= 1.0) {
2445 multiplier = 1.0;
2446 } else if (multiplier <= 2.0) {
2447 if (2 * mFrameCount <= maxNormalFrameCount) {
2448 multiplier = 2.0;
2449 } else {
2450 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2451 }
2452 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002453 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002454 }
2455 }
2456 mNormalFrameCount = multiplier * mFrameCount;
2457 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002458 if (mType == MIXER || mType == DUPLICATING) {
2459 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2460 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002461 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002462 mNormalFrameCount);
2463
Andy Hung08fb1742015-05-31 23:22:10 -07002464 // Check if we want to throttle the processing to no more than 2x normal rate
2465 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002466 mThreadThrottleTimeMs = 0;
2467 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002468 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2469
Andy Hung010a1a12014-03-13 13:57:33 -07002470 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2471 // Originally this was int16_t[] array, need to remove legacy implications.
2472 free(mSinkBuffer);
2473 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002474 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2475 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2476 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002477 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002478
Andy Hung69aed5f2014-02-25 17:24:40 -08002479 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2480 // drives the output.
2481 free(mMixerBuffer);
2482 mMixerBuffer = NULL;
2483 if (mMixerBufferEnabled) {
2484 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2485 mMixerBufferSize = mNormalFrameCount * mChannelCount
2486 * audio_bytes_per_sample(mMixerBufferFormat);
2487 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2488 }
Andy Hung98ef9782014-03-04 14:46:50 -08002489 free(mEffectBuffer);
2490 mEffectBuffer = NULL;
2491 if (mEffectBufferEnabled) {
2492 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2493 mEffectBufferSize = mNormalFrameCount * mChannelCount
2494 * audio_bytes_per_sample(mEffectBufferFormat);
2495 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2496 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002497
Eric Laurent81784c32012-11-19 14:55:58 -08002498 // force reconfiguration of effect chains and engines to take new buffer size and audio
2499 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002500 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002501 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2502 // matter.
2503 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2504 Vector< sp<EffectChain> > effectChains = mEffectChains;
2505 for (size_t i = 0; i < effectChains.size(); i ++) {
2506 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2507 }
2508}
2509
2510
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002511status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002512{
2513 if (halFrames == NULL || dspFrames == NULL) {
2514 return BAD_VALUE;
2515 }
2516 Mutex::Autolock _l(mLock);
2517 if (initCheck() != NO_ERROR) {
2518 return INVALID_OPERATION;
2519 }
Andy Hung818e7a32016-02-16 18:08:07 -08002520 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002521 *halFrames = framesWritten;
2522
2523 if (isSuspended()) {
2524 // return an estimation of rendered frames when the output is suspended
2525 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002526 *dspFrames = (uint32_t)
2527 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002528 return NO_ERROR;
2529 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002530 status_t status;
2531 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002532 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002533 *dspFrames = (size_t)frames;
2534 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002535 }
2536}
2537
Eric Laurent4c415062016-06-17 16:14:16 -07002538// hasAudioSession_l() must be called with ThreadBase::mLock held
2539uint32_t AudioFlinger::PlaybackThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08002540{
Eric Laurent81784c32012-11-19 14:55:58 -08002541 uint32_t result = 0;
2542 if (getEffectChain_l(sessionId) != 0) {
2543 result = EFFECT_SESSION;
2544 }
2545
2546 for (size_t i = 0; i < mTracks.size(); ++i) {
2547 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002548 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002549 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07002550 if (track->isFastTrack()) {
2551 result |= FAST_SESSION;
2552 }
Eric Laurent81784c32012-11-19 14:55:58 -08002553 break;
2554 }
2555 }
2556
2557 return result;
2558}
2559
Glenn Kastend848eb42016-03-08 13:42:11 -08002560uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08002561{
2562 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2563 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2564 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2565 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2566 }
2567 for (size_t i = 0; i < mTracks.size(); i++) {
2568 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002569 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002570 return AudioSystem::getStrategyForStream(track->streamType());
2571 }
2572 }
2573 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2574}
2575
2576
Phil Burk062e67a2015-02-11 13:40:50 -08002577AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002578{
2579 Mutex::Autolock _l(mLock);
2580 return mOutput;
2581}
2582
Phil Burk062e67a2015-02-11 13:40:50 -08002583AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002584{
2585 Mutex::Autolock _l(mLock);
2586 AudioStreamOut *output = mOutput;
2587 mOutput = NULL;
2588 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2589 // must push a NULL and wait for ack
2590 mOutputSink.clear();
2591 mPipeSink.clear();
2592 mNormalSink.clear();
2593 return output;
2594}
2595
2596// this method must always be called either with ThreadBase mLock held or inside the thread loop
2597audio_stream_t* AudioFlinger::PlaybackThread::stream() const
2598{
2599 if (mOutput == NULL) {
2600 return NULL;
2601 }
2602 return &mOutput->stream->common;
2603}
2604
2605uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2606{
2607 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2608}
2609
2610status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2611{
2612 if (!isValidSyncEvent(event)) {
2613 return BAD_VALUE;
2614 }
2615
2616 Mutex::Autolock _l(mLock);
2617
2618 for (size_t i = 0; i < mTracks.size(); ++i) {
2619 sp<Track> track = mTracks[i];
2620 if (event->triggerSession() == track->sessionId()) {
2621 (void) track->setSyncEvent(event);
2622 return NO_ERROR;
2623 }
2624 }
2625
2626 return NAME_NOT_FOUND;
2627}
2628
2629bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2630{
2631 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2632}
2633
2634void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2635 const Vector< sp<Track> >& tracksToRemove)
2636{
2637 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002638 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002639 for (size_t i = 0 ; i < count ; i++) {
2640 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002641 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002642 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002643 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002644#ifdef ADD_BATTERY_DATA
2645 // to track the speaker usage
2646 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2647#endif
2648 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002649 AudioSystem::releaseOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002650 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002651 }
Eric Laurent81784c32012-11-19 14:55:58 -08002652 }
2653 }
2654 }
Eric Laurent81784c32012-11-19 14:55:58 -08002655}
2656
2657void AudioFlinger::PlaybackThread::checkSilentMode_l()
2658{
2659 if (!mMasterMute) {
2660 char value[PROPERTY_VALUE_MAX];
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07002661 if (mOutDevice == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) {
2662 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
2663 return;
2664 }
Eric Laurent81784c32012-11-19 14:55:58 -08002665 if (property_get("ro.audio.silent", value, "0") > 0) {
2666 char *endptr;
2667 unsigned long ul = strtoul(value, &endptr, 0);
2668 if (*endptr == '\0' && ul != 0) {
2669 ALOGD("Silence is golden");
2670 // The setprop command will not allow a property to be changed after
2671 // the first time it is set, so we don't have to worry about un-muting.
2672 setMasterMute_l(true);
2673 }
2674 }
2675 }
2676}
2677
2678// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002679ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002680{
Eric Laurent81784c32012-11-19 14:55:58 -08002681 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002682 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002683 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002684
2685 // If an NBAIO sink is present, use it to write the normal mixer's submix
2686 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002687
Andy Hung010a1a12014-03-13 13:57:33 -07002688 const size_t count = mBytesRemaining / mFrameSize;
2689
Simon Wilson2d590962012-11-29 15:18:50 -08002690 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002691 // update the setpoint when AudioFlinger::mScreenState changes
2692 uint32_t screenState = AudioFlinger::mScreenState;
2693 if (screenState != mScreenState) {
2694 mScreenState = screenState;
2695 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2696 if (pipe != NULL) {
2697 pipe->setAvgFrames((mScreenState & 1) ?
2698 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2699 }
2700 }
Andy Hung010a1a12014-03-13 13:57:33 -07002701 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002702 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002703 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002704 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002705 } else {
2706 bytesWritten = framesWritten;
2707 }
2708 // otherwise use the HAL / AudioStreamOut directly
2709 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002710 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002711
Eric Laurentbfb1b832013-01-07 09:53:42 -08002712 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002713 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2714 mWriteAckSequence += 2;
2715 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002716 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002717 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002718 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002719 // FIXME We should have an implementation of timestamps for direct output threads.
2720 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002721 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurent51716182016-02-29 18:00:56 -08002722
Eric Laurentbfb1b832013-01-07 09:53:42 -08002723 if (mUseAsyncWrite &&
2724 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2725 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002726 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002727 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002728 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002729 }
Eric Laurent81784c32012-11-19 14:55:58 -08002730 }
2731
Eric Laurent81784c32012-11-19 14:55:58 -08002732 mNumWrites++;
2733 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002734 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002735 return bytesWritten;
2736}
2737
2738void AudioFlinger::PlaybackThread::threadLoop_drain()
2739{
2740 if (mOutput->stream->drain) {
2741 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2742 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002743 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2744 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002745 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002746 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002747 }
2748 mOutput->stream->drain(mOutput->stream,
2749 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2750 : AUDIO_DRAIN_ALL);
2751 }
2752}
2753
2754void AudioFlinger::PlaybackThread::threadLoop_exit()
2755{
Eric Laurent275e8e92014-11-30 15:14:47 -08002756 {
2757 Mutex::Autolock _l(mLock);
2758 for (size_t i = 0; i < mTracks.size(); i++) {
2759 sp<Track> track = mTracks[i];
2760 track->invalidate();
2761 }
2762 }
Eric Laurent81784c32012-11-19 14:55:58 -08002763}
2764
2765/*
2766The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002767 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002768 - mActiveSleepTimeUs from activeSleepTimeUs()
2769 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08002770 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
2771 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08002772 - maxPeriod from frame count and sample rate (MIXER only)
2773
2774The parameters that affect these derived values are:
2775 - frame count
2776 - frame size
2777 - sample rate
2778 - device type: A2DP or not
2779 - device latency
2780 - format: PCM or not
2781 - active sleep time
2782 - idle sleep time
2783*/
2784
2785void AudioFlinger::PlaybackThread::cacheParameters_l()
2786{
Andy Hung25c2dac2014-02-27 14:56:00 -08002787 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002788 mActiveSleepTimeUs = activeSleepTimeUs();
2789 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08002790
2791 // make sure standby delay is not too short when connected to an A2DP sink to avoid
2792 // truncating audio when going to standby.
2793 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
2794 if ((mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != 0) {
2795 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
2796 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
2797 }
2798 }
Eric Laurent81784c32012-11-19 14:55:58 -08002799}
2800
Eric Laurent13084622016-05-17 10:51:49 -07002801bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08002802{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002803 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08002804 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07002805 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002806 size_t size = mTracks.size();
2807 for (size_t i = 0; i < size; i++) {
2808 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07002809 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002810 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07002811 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002812 }
2813 }
Eric Laurent13084622016-05-17 10:51:49 -07002814 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08002815}
2816
Haynes Mathew George05317d22016-05-03 16:34:26 -07002817void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2818{
2819 Mutex::Autolock _l(mLock);
2820 invalidateTracks_l(streamType);
2821}
2822
Eric Laurent81784c32012-11-19 14:55:58 -08002823status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2824{
Glenn Kastend848eb42016-03-08 13:42:11 -08002825 audio_session_t session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002826 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2827 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002828 bool ownsBuffer = false;
2829
2830 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Glenn Kastend848eb42016-03-08 13:42:11 -08002831 if (session > AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002832 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002833 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002834 if (mType != DIRECT) {
2835 size_t numSamples = mNormalFrameCount * mChannelCount;
2836 buffer = new int16_t[numSamples];
2837 memset(buffer, 0, numSamples * sizeof(int16_t));
2838 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2839 ownsBuffer = true;
2840 }
2841
2842 // Attach all tracks with same session ID to this chain.
2843 for (size_t i = 0; i < mTracks.size(); ++i) {
2844 sp<Track> track = mTracks[i];
2845 if (session == track->sessionId()) {
2846 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2847 buffer);
2848 track->setMainBuffer(buffer);
2849 chain->incTrackCnt();
2850 }
2851 }
2852
2853 // indicate all active tracks in the chain
2854 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2855 sp<Track> track = mActiveTracks[i].promote();
2856 if (track == 0) {
2857 continue;
2858 }
2859 if (session == track->sessionId()) {
2860 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2861 chain->incActiveTrackCnt();
2862 }
2863 }
2864 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002865 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08002866 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002867 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2868 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002869 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Glenn Kastend848eb42016-03-08 13:42:11 -08002870 // chains list in order to be processed last as it contains output stage effects.
Eric Laurent81784c32012-11-19 14:55:58 -08002871 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2872 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08002873 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08002874 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08002875 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08002876 // Effect chain for other sessions are inserted at beginning of effect
2877 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08002878 // sessions is not important.
2879 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
2880 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX,
2881 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08002882 size_t size = mEffectChains.size();
2883 size_t i = 0;
2884 for (i = 0; i < size; i++) {
2885 if (mEffectChains[i]->sessionId() < session) {
2886 break;
2887 }
2888 }
2889 mEffectChains.insertAt(chain, i);
2890 checkSuspendOnAddEffectChain_l(chain);
2891
2892 return NO_ERROR;
2893}
2894
2895size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2896{
Glenn Kastend848eb42016-03-08 13:42:11 -08002897 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08002898
2899 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2900
2901 for (size_t i = 0; i < mEffectChains.size(); i++) {
2902 if (chain == mEffectChains[i]) {
2903 mEffectChains.removeAt(i);
2904 // detach all active tracks from the chain
2905 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2906 sp<Track> track = mActiveTracks[i].promote();
2907 if (track == 0) {
2908 continue;
2909 }
2910 if (session == track->sessionId()) {
2911 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2912 chain.get(), session);
2913 chain->decActiveTrackCnt();
2914 }
2915 }
2916
2917 // detach all tracks with same session ID from this chain
2918 for (size_t i = 0; i < mTracks.size(); ++i) {
2919 sp<Track> track = mTracks[i];
2920 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002921 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002922 chain->decTrackCnt();
2923 }
2924 }
2925 break;
2926 }
2927 }
2928 return mEffectChains.size();
2929}
2930
2931status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002932 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08002933{
2934 Mutex::Autolock _l(mLock);
2935 return attachAuxEffect_l(track, EffectId);
2936}
2937
2938status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002939 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08002940{
2941 status_t status = NO_ERROR;
2942
2943 if (EffectId == 0) {
2944 track->setAuxBuffer(0, NULL);
2945 } else {
2946 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2947 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2948 if (effect != 0) {
2949 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2950 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2951 } else {
2952 status = INVALID_OPERATION;
2953 }
2954 } else {
2955 status = BAD_VALUE;
2956 }
2957 }
2958 return status;
2959}
2960
2961void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2962{
2963 for (size_t i = 0; i < mTracks.size(); ++i) {
2964 sp<Track> track = mTracks[i];
2965 if (track->auxEffectId() == effectId) {
2966 attachAuxEffect_l(track, 0);
2967 }
2968 }
2969}
2970
2971bool AudioFlinger::PlaybackThread::threadLoop()
2972{
2973 Vector< sp<Track> > tracksToRemove;
2974
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002975 mStandbyTimeNs = systemTime();
Andy Hung69488c42016-05-16 18:43:33 -07002976 nsecs_t lastWriteFinished = -1; // time last server write completed
2977 int64_t lastFramesWritten = -1; // track changes in timestamp server frames written
Eric Laurent81784c32012-11-19 14:55:58 -08002978
2979 // MIXER
2980 nsecs_t lastWarning = 0;
2981
2982 // DUPLICATING
2983 // FIXME could this be made local to while loop?
2984 writeFrames = 0;
2985
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002986 int lastGeneration = 0;
2987
Eric Laurent81784c32012-11-19 14:55:58 -08002988 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002989 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002990
2991 if (mType == MIXER) {
2992 sleepTimeShift = 0;
2993 }
2994
2995 CpuStats cpuStats;
2996 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2997
2998 acquireWakeLock();
2999
Glenn Kasten9e58b552013-01-18 15:09:48 -08003000 // mNBLogWriter->log can only be called while thread mutex mLock is held.
3001 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3002 // and then that string will be logged at the next convenient opportunity.
3003 const char *logString = NULL;
3004
Eric Laurent664539d2013-09-23 18:24:31 -07003005 checkSilentMode_l();
3006
Eric Laurent81784c32012-11-19 14:55:58 -08003007 while (!exitPending())
3008 {
3009 cpuStats.sample(myName);
3010
3011 Vector< sp<EffectChain> > effectChains;
3012
Eric Laurent81784c32012-11-19 14:55:58 -08003013 { // scope for mLock
3014
3015 Mutex::Autolock _l(mLock);
3016
Eric Laurent021cf962014-05-13 10:18:14 -07003017 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07003018
Glenn Kasten9e58b552013-01-18 15:09:48 -08003019 if (logString != NULL) {
3020 mNBLogWriter->logTimestamp();
3021 mNBLogWriter->log(logString);
3022 logString = NULL;
3023 }
3024
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003025 // Gather the framesReleased counters for all active tracks,
Andy Hunge10393e2015-06-12 13:59:33 -07003026 // and associate with the sink frames written out. We need
3027 // this to convert the sink timestamp to the track timestamp.
Andy Hung69488c42016-05-16 18:43:33 -07003028 bool kernelLocationUpdate = false;
Andy Hunge10393e2015-06-12 13:59:33 -07003029 if (mNormalSink != 0) {
Andy Hungc54b1ff2016-02-23 14:07:07 -08003030 // Note: The DuplicatingThread may not have a mNormalSink.
Andy Hung818e7a32016-02-16 18:08:07 -08003031 // We always fetch the timestamp here because often the downstream
Andy Hung69488c42016-05-16 18:43:33 -07003032 // sink will block while writing.
Andy Hung818e7a32016-02-16 18:08:07 -08003033 ExtendedTimestamp timestamp; // use private copy to fetch
3034 (void) mNormalSink->getTimestamp(timestamp);
Andy Hung6d7b1192016-05-07 22:59:48 -07003035
3036 // We keep track of the last valid kernel position in case we are in underrun
3037 // and the normal mixer period is the same as the fast mixer period, or there
3038 // is some error from the HAL.
3039 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3040 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3041 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
3042 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3043 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
3044
3045 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3046 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
3047 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3048 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
Andy Hung69488c42016-05-16 18:43:33 -07003049 }
3050
3051 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3052 kernelLocationUpdate = true;
Andy Hung6d7b1192016-05-07 22:59:48 -07003053 } else {
Eric Laurent122f7e72016-06-29 11:53:29 -07003054 ALOGVV("getTimestamp error - no valid kernel position");
Andy Hung6d7b1192016-05-07 22:59:48 -07003055 }
3056
Andy Hung818e7a32016-02-16 18:08:07 -08003057 // copy over kernel info
3058 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
Andy Hung238fa3d2016-07-28 10:53:22 -07003059 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3060 + mSuspendedFrames; // add frames discarded when suspended
Andy Hung818e7a32016-02-16 18:08:07 -08003061 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
3062 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hungc54b1ff2016-02-23 14:07:07 -08003063 }
3064 // mFramesWritten for non-offloaded tracks are contiguous
3065 // even after standby() is called. This is useful for the track frame
3066 // to sink frame mapping.
Andy Hung69488c42016-05-16 18:43:33 -07003067 bool serverLocationUpdate = false;
3068 if (mFramesWritten != lastFramesWritten) {
3069 serverLocationUpdate = true;
3070 lastFramesWritten = mFramesWritten;
3071 }
3072 // Only update timestamps if there is a meaningful change.
3073 // Either the kernel timestamp must be valid or we have written something.
3074 if (kernelLocationUpdate || serverLocationUpdate) {
3075 if (serverLocationUpdate) {
3076 // use the time before we called the HAL write - it is a bit more accurate
3077 // to when the server last read data than the current time here.
3078 //
3079 // If we haven't written anything, mLastWriteTime will be -1
3080 // and we use systemTime().
3081 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
3082 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastWriteTime == -1
3083 ? systemTime() : mLastWriteTime;
3084 }
3085 const size_t size = mActiveTracks.size();
3086 for (size_t i = 0; i < size; ++i) {
3087 sp<Track> t = mActiveTracks[i].promote();
3088 if (t != 0 && !t->isFastTrack()) {
3089 t->updateTrackFrameInfo(
3090 t->mAudioTrackServerProxy->framesReleased(),
3091 mFramesWritten,
3092 mTimestamp);
3093 }
Andy Hunge10393e2015-06-12 13:59:33 -07003094 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07003095 }
3096
Eric Laurent81784c32012-11-19 14:55:58 -08003097 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003098 if (mSignalPending) {
3099 // A signal was raised while we were unlocked
3100 mSignalPending = false;
3101 } else if (waitingAsyncCallback_l()) {
3102 if (exitPending()) {
3103 break;
3104 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003105 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003106 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003107 releaseWakeLock_l();
3108 released = true;
Mikhail Naganove94c27a2016-08-18 17:31:46 -07003109 mWakeLockUids.clear();
3110 mActiveTracksGeneration++;
Marco Nelissen078538c2015-05-12 09:17:57 -07003111 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003112 ALOGV("wait async completion");
3113 mWaitWorkCV.wait(mLock);
3114 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003115 if (released) {
3116 acquireWakeLock_l();
3117 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003118 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3119 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003120
3121 continue;
3122 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003123 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003124 isSuspended()) {
3125 // put audio hardware into standby after short delay
3126 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003127
3128 threadLoop_standby();
3129
3130 mStandby = true;
3131 }
3132
3133 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
3134 // we're about to wait, flush the binder command buffer
3135 IPCThreadState::self()->flushCommands();
3136
3137 clearOutputTracks();
3138
3139 if (exitPending()) {
3140 break;
3141 }
3142
3143 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003144 mWakeLockUids.clear();
3145 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08003146 // wait until we have something to do...
3147 ALOGV("%s going to sleep", myName.string());
3148 mWaitWorkCV.wait(mLock);
3149 ALOGV("%s waking up", myName.string());
3150 acquireWakeLock_l();
3151
3152 mMixerStatus = MIXER_IDLE;
3153 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3154 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003155 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003156 checkSilentMode_l();
3157
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003158 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3159 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003160 if (mType == MIXER) {
3161 sleepTimeShift = 0;
3162 }
3163
3164 continue;
3165 }
3166 }
Eric Laurent81784c32012-11-19 14:55:58 -08003167 // mMixerStatusIgnoringFastTracks is also updated internally
3168 mMixerStatus = prepareTracks_l(&tracksToRemove);
3169
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003170 // compare with previously applied list
3171 if (lastGeneration != mActiveTracksGeneration) {
3172 // update wakelock
3173 updateWakeLockUids_l(mWakeLockUids);
3174 lastGeneration = mActiveTracksGeneration;
3175 }
3176
Eric Laurent81784c32012-11-19 14:55:58 -08003177 // prevent any changes in effect chain list and in each effect chain
3178 // during mixing and effect process as the audio buffers could be deleted
3179 // or modified if an effect is created or deleted
3180 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003181 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003182
Eric Laurentbfb1b832013-01-07 09:53:42 -08003183 if (mBytesRemaining == 0) {
3184 mCurrentWriteLength = 0;
3185 if (mMixerStatus == MIXER_TRACKS_READY) {
3186 // threadLoop_mix() sets mCurrentWriteLength
3187 threadLoop_mix();
3188 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3189 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003190 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003191 // must be written to HAL
3192 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003193 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003194 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003195 }
3196 }
Andy Hung98ef9782014-03-04 14:46:50 -08003197 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003198 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003199 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3200 // or mSinkBuffer (if there are no effects).
3201 //
3202 // This is done pre-effects computation; if effects change to
3203 // support higher precision, this needs to move.
3204 //
3205 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003206 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003207 if (mMixerBufferValid) {
3208 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3209 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3210
Andy Hung2ddee192015-12-18 17:34:44 -08003211 // mono blend occurs for mixer threads only (not direct or offloaded)
3212 // and is handled here if we're going directly to the sink.
3213 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003214 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3215 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003216 }
3217
Andy Hung98ef9782014-03-04 14:46:50 -08003218 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
3219 mNormalFrameCount * mChannelCount);
3220 }
3221
Eric Laurentbfb1b832013-01-07 09:53:42 -08003222 mBytesRemaining = mCurrentWriteLength;
3223 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003224 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3225 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3226 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3227 mBytesWritten += mBytesRemaining;
3228 mFramesWritten += framesRemaining;
3229 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003230 mBytesRemaining = 0;
3231 }
Eric Laurent81784c32012-11-19 14:55:58 -08003232
Eric Laurentbfb1b832013-01-07 09:53:42 -08003233 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003234 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003235 for (size_t i = 0; i < effectChains.size(); i ++) {
3236 effectChains[i]->process_l();
3237 }
Eric Laurent81784c32012-11-19 14:55:58 -08003238 }
3239 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003240 // Process effect chains for offloaded thread even if no audio
3241 // was read from audio track: process only updates effect state
3242 // and thus does have to be synchronized with audio writes but may have
3243 // to be called while waiting for async write callback
3244 if (mType == OFFLOAD) {
3245 for (size_t i = 0; i < effectChains.size(); i ++) {
3246 effectChains[i]->process_l();
3247 }
3248 }
Eric Laurent81784c32012-11-19 14:55:58 -08003249
Andy Hung98ef9782014-03-04 14:46:50 -08003250 // Only if the Effects buffer is enabled and there is data in the
3251 // Effects buffer (buffer valid), we need to
3252 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003253 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003254 if (mEffectBufferValid) {
3255 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003256
3257 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003258 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3259 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003260 }
3261
Andy Hung98ef9782014-03-04 14:46:50 -08003262 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
3263 mNormalFrameCount * mChannelCount);
3264 }
3265
Eric Laurent81784c32012-11-19 14:55:58 -08003266 // enable changes in effect chain
3267 unlockEffectChains(effectChains);
3268
Eric Laurentbfb1b832013-01-07 09:53:42 -08003269 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003270 // mSleepTimeUs == 0 means we must write to audio hardware
3271 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003272 ssize_t ret = 0;
Andy Hung69488c42016-05-16 18:43:33 -07003273 // We save lastWriteFinished here, as previousLastWriteFinished,
3274 // for throttling. On thread start, previousLastWriteFinished will be
3275 // set to -1, which properly results in no throttling after the first write.
3276 nsecs_t previousLastWriteFinished = lastWriteFinished;
3277 nsecs_t delta = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003278 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003279 // FIXME rewrite to reduce number of system calls
3280 mLastWriteTime = systemTime(); // also used for dumpsys
Andy Hung08fb1742015-05-31 23:22:10 -07003281 ret = threadLoop_write();
Andy Hung69488c42016-05-16 18:43:33 -07003282 lastWriteFinished = systemTime();
3283 delta = lastWriteFinished - mLastWriteTime;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003284 if (ret < 0) {
3285 mBytesRemaining = 0;
3286 } else {
3287 mBytesWritten += ret;
3288 mBytesRemaining -= ret;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003289 mFramesWritten += ret / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003290 }
3291 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3292 (mMixerStatus == MIXER_DRAIN_ALL)) {
3293 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003294 }
Andy Hung08fb1742015-05-31 23:22:10 -07003295 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003296 // write blocked detection
Andy Hung08fb1742015-05-31 23:22:10 -07003297 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003298 mNumDelayedWrites++;
Andy Hung69488c42016-05-16 18:43:33 -07003299 if ((lastWriteFinished - lastWarning) > kWarningThrottleNs) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003300 ATRACE_NAME("underrun");
3301 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003302 (unsigned long long) ns2ms(delta), mNumDelayedWrites, this);
Andy Hung69488c42016-05-16 18:43:33 -07003303 lastWarning = lastWriteFinished;
Glenn Kasten4944acb2013-08-19 08:39:20 -07003304 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003305 }
Andy Hung08fb1742015-05-31 23:22:10 -07003306
3307 if (mThreadThrottle
3308 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
3309 && ret > 0) { // we wrote something
3310 // Limit MixerThread data processing to no more than twice the
3311 // expected processing rate.
3312 //
3313 // This helps prevent underruns with NuPlayer and other applications
3314 // which may set up buffers that are close to the minimum size, or use
3315 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3316 //
3317 // The throttle smooths out sudden large data drains from the device,
3318 // e.g. when it comes out of standby, which often causes problems with
3319 // (1) mixer threads without a fast mixer (which has its own warm-up)
3320 // (2) minimum buffer sized tracks (even if the track is full,
3321 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07003322 //
3323 // Total time spent in last processing cycle equals time spent in
3324 // 1. threadLoop_write, as well as time spent in
3325 // 2. threadLoop_mix (significant for heavy mixing, especially
3326 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07003327
Andy Hung69488c42016-05-16 18:43:33 -07003328 // it's OK if deltaMs is an overestimate.
3329 const int32_t deltaMs =
3330 (lastWriteFinished - previousLastWriteFinished) / 1000000;
Andy Hung08fb1742015-05-31 23:22:10 -07003331 const int32_t throttleMs = mHalfBufferMs - deltaMs;
3332 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3333 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003334 // notify of throttle start on verbose log
3335 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3336 "mixer(%p) throttle begin:"
3337 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003338 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003339 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07003340 // Throttle must be attributed to the previous mixer loop's write time
3341 // to allow back-to-back throttling.
3342 lastWriteFinished += throttleMs * 1000000;
Andy Hung40eb1a12015-06-18 13:42:02 -07003343 } else {
3344 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3345 if (diff > 0) {
3346 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07003347 // but prevent spamming for bluetooth
3348 ALOGD_IF(!audio_is_a2dp_out_device(outDevice()),
3349 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07003350 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3351 }
Andy Hung08fb1742015-05-31 23:22:10 -07003352 }
3353 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003354 }
Eric Laurent81784c32012-11-19 14:55:58 -08003355
Eric Laurentbfb1b832013-01-07 09:53:42 -08003356 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003357 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07003358 Mutex::Autolock _l(mLock);
3359 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
3360 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08003361 }
Glenn Kastene7754022014-10-31 12:11:26 -07003362 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003363 }
Eric Laurent81784c32012-11-19 14:55:58 -08003364 }
3365
3366 // Finally let go of removed track(s), without the lock held
3367 // since we can't guarantee the destructors won't acquire that
3368 // same lock. This will also mutate and push a new fast mixer state.
3369 threadLoop_removeTracks(tracksToRemove);
3370 tracksToRemove.clear();
3371
3372 // FIXME I don't understand the need for this here;
3373 // it was in the original code but maybe the
3374 // assignment in saveOutputTracks() makes this unnecessary?
3375 clearOutputTracks();
3376
3377 // Effect chains will be actually deleted here if they were removed from
3378 // mEffectChains list during mixing or effects processing
3379 effectChains.clear();
3380
3381 // FIXME Note that the above .clear() is no longer necessary since effectChains
3382 // is now local to this block, but will keep it for now (at least until merge done).
3383 }
3384
Eric Laurentbfb1b832013-01-07 09:53:42 -08003385 threadLoop_exit();
3386
Eric Laurentcf817a22014-08-04 20:36:31 -07003387 if (!mStandby) {
3388 threadLoop_standby();
3389 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003390 }
3391
3392 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003393 mWakeLockUids.clear();
3394 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08003395
3396 ALOGV("Thread %p type %d exiting", this, mType);
3397 return false;
3398}
3399
Eric Laurentbfb1b832013-01-07 09:53:42 -08003400// removeTracks_l() must be called with ThreadBase::mLock held
3401void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3402{
3403 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003404 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003405 for (size_t i=0 ; i<count ; i++) {
3406 const sp<Track>& track = tracksToRemove.itemAt(i);
3407 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003408 mWakeLockUids.remove(track->uid());
3409 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003410 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3411 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3412 if (chain != 0) {
3413 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3414 track->sessionId());
3415 chain->decActiveTrackCnt();
3416 }
3417 if (track->isTerminated()) {
3418 removeTrack_l(track);
3419 }
3420 }
3421 }
3422
3423}
Eric Laurent81784c32012-11-19 14:55:58 -08003424
Eric Laurentaccc1472013-09-20 09:36:34 -07003425status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3426{
3427 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08003428 ExtendedTimestamp ets;
3429 status_t status = mNormalSink->getTimestamp(ets);
3430 if (status == NO_ERROR) {
3431 status = ets.getBestTimestamp(&timestamp);
3432 }
3433 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07003434 }
Andy Hung9a1c8892014-12-03 11:37:42 -08003435 if ((mType == OFFLOAD || mType == DIRECT)
3436 && mOutput != NULL && mOutput->stream->get_presentation_position) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003437 uint64_t position64;
Phil Burk062e67a2015-02-11 13:40:50 -08003438 int ret = mOutput->getPresentationPosition(&position64, &timestamp.mTime);
Eric Laurentaccc1472013-09-20 09:36:34 -07003439 if (ret == 0) {
3440 timestamp.mPosition = (uint32_t)position64;
3441 return NO_ERROR;
3442 }
3443 }
3444 return INVALID_OPERATION;
3445}
Eric Laurent1c333e22014-05-20 10:48:17 -07003446
Eric Laurent054d9d32015-04-24 08:48:48 -07003447status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3448 audio_patch_handle_t *handle)
3449{
Andy Hungf60abce2016-08-26 11:37:54 -07003450 status_t status;
3451 if (property_get_bool("af.patch_park", false /* default_value */)) {
3452 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3453 // or if HAL does not properly lock against access.
3454 AutoPark<FastMixer> park(mFastMixer);
3455 status = PlaybackThread::createAudioPatch_l(patch, handle);
3456 } else {
3457 status = PlaybackThread::createAudioPatch_l(patch, handle);
3458 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003459 return status;
3460}
3461
Eric Laurent1c333e22014-05-20 10:48:17 -07003462status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3463 audio_patch_handle_t *handle)
3464{
3465 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003466
3467 // store new device and send to effects
3468 audio_devices_t type = AUDIO_DEVICE_NONE;
3469 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3470 type |= patch->sinks[i].ext.device.type;
3471 }
3472
3473#ifdef ADD_BATTERY_DATA
3474 // when changing the audio output device, call addBatteryData to notify
3475 // the change
3476 if (mOutDevice != type) {
3477 uint32_t params = 0;
3478 // check whether speaker is on
3479 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3480 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003481 }
3482
Eric Laurent054d9d32015-04-24 08:48:48 -07003483 audio_devices_t deviceWithoutSpeaker
3484 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3485 // check if any other device (except speaker) is on
3486 if (type & deviceWithoutSpeaker) {
3487 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3488 }
3489
3490 if (params != 0) {
3491 addBatteryData(params);
3492 }
3493 }
3494#endif
3495
3496 for (size_t i = 0; i < mEffectChains.size(); i++) {
3497 mEffectChains[i]->setDevice_l(type);
3498 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003499
3500 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3501 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3502 bool configChanged = mPrevOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003503 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003504 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003505
3506 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003507 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3508 status = hwDevice->createAudioPatch(patch->num_sources,
3509 patch->sources,
3510 patch->num_sinks,
3511 patch->sinks,
3512 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003513 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003514 char *address;
3515 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3516 //FIXME: we only support address on first sink with HAL version < 3.0
3517 address = audio_device_address_to_parameter(
3518 patch->sinks[0].ext.device.type,
3519 patch->sinks[0].ext.device.address);
3520 } else {
3521 address = (char *)calloc(1, 1);
3522 }
3523 AudioParameter param = AudioParameter(String8(address));
3524 free(address);
3525 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), (int)type);
3526 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3527 param.toString().string());
3528 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003529 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003530 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003531 mPrevOutDevice = type;
Eric Laurente8726fe2015-06-26 09:39:24 -07003532 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3533 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003534 return status;
3535}
3536
Eric Laurent054d9d32015-04-24 08:48:48 -07003537status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3538{
Andy Hungf60abce2016-08-26 11:37:54 -07003539 status_t status;
3540 if (property_get_bool("af.patch_park", false /* default_value */)) {
3541 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3542 // or if HAL does not properly lock against access.
3543 AutoPark<FastMixer> park(mFastMixer);
3544 status = PlaybackThread::releaseAudioPatch_l(handle);
3545 } else {
3546 status = PlaybackThread::releaseAudioPatch_l(handle);
3547 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003548 return status;
3549}
3550
Eric Laurent1c333e22014-05-20 10:48:17 -07003551status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3552{
3553 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003554
3555 mOutDevice = AUDIO_DEVICE_NONE;
3556
Eric Laurent1c333e22014-05-20 10:48:17 -07003557 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003558 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3559 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003560 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003561 AudioParameter param;
3562 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
3563 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3564 param.toString().string());
Eric Laurent1c333e22014-05-20 10:48:17 -07003565 }
3566 return status;
3567}
3568
Eric Laurent83b88082014-06-20 18:31:16 -07003569void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3570{
3571 Mutex::Autolock _l(mLock);
3572 mTracks.add(track);
3573}
3574
3575void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3576{
3577 Mutex::Autolock _l(mLock);
3578 destroyTrack_l(track);
3579}
3580
3581void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3582{
3583 ThreadBase::getAudioPortConfig(config);
3584 config->role = AUDIO_PORT_ROLE_SOURCE;
3585 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3586 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3587}
3588
Eric Laurent81784c32012-11-19 14:55:58 -08003589// ----------------------------------------------------------------------------
3590
3591AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003592 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3593 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003594 // mAudioMixer below
3595 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08003596 mFastMixerFutex(0),
3597 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08003598 // mOutputSink below
3599 // mPipeSink below
3600 // mNormalSink below
3601{
3602 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003603 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%zu, "
3604 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003605 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3606 mNormalFrameCount);
3607 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3608
Andy Hungfbfc3952015-01-15 13:33:51 -08003609 if (type == DUPLICATING) {
3610 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3611 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3612 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3613 return;
3614 }
Eric Laurent81784c32012-11-19 14:55:58 -08003615 // create an NBAIO sink for the HAL output stream, and negotiate
3616 mOutputSink = new AudioStreamOutSink(output->stream);
3617 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003618 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003619#if !LOG_NDEBUG
3620 ssize_t index =
3621#else
3622 (void)
3623#endif
3624 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003625 ALOG_ASSERT(index == 0);
3626
3627 // initialize fast mixer depending on configuration
3628 bool initFastMixer;
3629 switch (kUseFastMixer) {
3630 case FastMixer_Never:
3631 initFastMixer = false;
3632 break;
3633 case FastMixer_Always:
3634 initFastMixer = true;
3635 break;
3636 case FastMixer_Static:
3637 case FastMixer_Dynamic:
3638 initFastMixer = mFrameCount < mNormalFrameCount;
3639 break;
3640 }
3641 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003642 audio_format_t fastMixerFormat;
3643 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3644 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3645 } else {
3646 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3647 }
3648 if (mFormat != fastMixerFormat) {
3649 // change our Sink format to accept our intermediate precision
3650 mFormat = fastMixerFormat;
3651 free(mSinkBuffer);
3652 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3653 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3654 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3655 }
Eric Laurent81784c32012-11-19 14:55:58 -08003656
3657 // create a MonoPipe to connect our submix to FastMixer
3658 NBAIO_Format format = mOutputSink->format();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003659#ifdef TEE_SINK
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003660 NBAIO_Format origformat = format;
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003661#endif
Andy Hung1258c1a2014-05-23 21:22:17 -07003662 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07003663 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003664 format.mFormat = fastMixerFormat;
3665 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3666
Eric Laurent81784c32012-11-19 14:55:58 -08003667 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3668 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3669 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3670 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3671 const NBAIO_Format offers[1] = {format};
3672 size_t numCounterOffers = 0;
Glenn Kastenfc302fd2016-04-11 14:11:26 -07003673#if !LOG_NDEBUG || defined(TEE_SINK)
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003674 ssize_t index =
3675#else
3676 (void)
3677#endif
3678 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003679 ALOG_ASSERT(index == 0);
3680 monoPipe->setAvgFrames((mScreenState & 1) ?
3681 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3682 mPipeSink = monoPipe;
3683
Glenn Kasten46909e72013-02-26 09:20:22 -08003684#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003685 if (mTeeSinkOutputEnabled) {
3686 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003687 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3688 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003689 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003690 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003691 ALOG_ASSERT(index == 0);
3692 mTeeSink = teeSink;
3693 PipeReader *teeSource = new PipeReader(*teeSink);
3694 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003695 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003696 ALOG_ASSERT(index == 0);
3697 mTeeSource = teeSource;
3698 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003699#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003700
3701 // create fast mixer and configure it initially with just one fast track for our submix
3702 mFastMixer = new FastMixer();
3703 FastMixerStateQueue *sq = mFastMixer->sq();
3704#ifdef STATE_QUEUE_DUMP
3705 sq->setObserverDump(&mStateQueueObserverDump);
3706 sq->setMutatorDump(&mStateQueueMutatorDump);
3707#endif
3708 FastMixerState *state = sq->begin();
3709 FastTrack *fastTrack = &state->mFastTracks[0];
3710 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3711 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3712 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003713 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3714 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003715 fastTrack->mGeneration++;
3716 state->mFastTracksGen++;
3717 state->mTrackMask = 1;
3718 // fast mixer will use the HAL output sink
3719 state->mOutputSink = mOutputSink.get();
3720 state->mOutputSinkGen++;
3721 state->mFrameCount = mFrameCount;
3722 state->mCommand = FastMixerState::COLD_IDLE;
3723 // already done in constructor initialization list
3724 //mFastMixerFutex = 0;
3725 state->mColdFutexAddr = &mFastMixerFutex;
3726 state->mColdGen++;
3727 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003728#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003729 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003730#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003731 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3732 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003733 sq->end();
3734 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3735
3736 // start the fast mixer
3737 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3738 pid_t tid = mFastMixer->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003739 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003740
3741#ifdef AUDIO_WATCHDOG
3742 // create and start the watchdog
3743 mAudioWatchdog = new AudioWatchdog();
3744 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3745 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3746 tid = mAudioWatchdog->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003747 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003748#endif
3749
Eric Laurent81784c32012-11-19 14:55:58 -08003750 }
3751
3752 switch (kUseFastMixer) {
3753 case FastMixer_Never:
3754 case FastMixer_Dynamic:
3755 mNormalSink = mOutputSink;
3756 break;
3757 case FastMixer_Always:
3758 mNormalSink = mPipeSink;
3759 break;
3760 case FastMixer_Static:
3761 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3762 break;
3763 }
3764}
3765
3766AudioFlinger::MixerThread::~MixerThread()
3767{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003768 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003769 FastMixerStateQueue *sq = mFastMixer->sq();
3770 FastMixerState *state = sq->begin();
3771 if (state->mCommand == FastMixerState::COLD_IDLE) {
3772 int32_t old = android_atomic_inc(&mFastMixerFutex);
3773 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003774 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003775 }
3776 }
3777 state->mCommand = FastMixerState::EXIT;
3778 sq->end();
3779 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3780 mFastMixer->join();
3781 // Though the fast mixer thread has exited, it's state queue is still valid.
3782 // We'll use that extract the final state which contains one remaining fast track
3783 // corresponding to our sub-mix.
3784 state = sq->begin();
3785 ALOG_ASSERT(state->mTrackMask == 1);
3786 FastTrack *fastTrack = &state->mFastTracks[0];
3787 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3788 delete fastTrack->mBufferProvider;
3789 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003790 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003791#ifdef AUDIO_WATCHDOG
3792 if (mAudioWatchdog != 0) {
3793 mAudioWatchdog->requestExit();
3794 mAudioWatchdog->requestExitAndWait();
3795 mAudioWatchdog.clear();
3796 }
3797#endif
3798 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003799 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003800 delete mAudioMixer;
3801}
3802
3803
3804uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3805{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003806 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003807 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3808 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3809 }
3810 return latency;
3811}
3812
3813
3814void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3815{
3816 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3817}
3818
Eric Laurentbfb1b832013-01-07 09:53:42 -08003819ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003820{
3821 // FIXME we should only do one push per cycle; confirm this is true
3822 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003823 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003824 FastMixerStateQueue *sq = mFastMixer->sq();
3825 FastMixerState *state = sq->begin();
3826 if (state->mCommand != FastMixerState::MIX_WRITE &&
3827 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3828 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07003829
3830 // FIXME workaround for first HAL write being CPU bound on some devices
3831 ATRACE_BEGIN("write");
3832 mOutput->write((char *)mSinkBuffer, 0);
3833 ATRACE_END();
3834
Eric Laurent81784c32012-11-19 14:55:58 -08003835 int32_t old = android_atomic_inc(&mFastMixerFutex);
3836 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003837 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003838 }
3839#ifdef AUDIO_WATCHDOG
3840 if (mAudioWatchdog != 0) {
3841 mAudioWatchdog->resume();
3842 }
3843#endif
3844 }
3845 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003846#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003847 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003848 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003849#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003850 sq->end();
3851 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3852 if (kUseFastMixer == FastMixer_Dynamic) {
3853 mNormalSink = mPipeSink;
3854 }
3855 } else {
3856 sq->end(false /*didModify*/);
3857 }
3858 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003859 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003860}
3861
3862void AudioFlinger::MixerThread::threadLoop_standby()
3863{
3864 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003865 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003866 FastMixerStateQueue *sq = mFastMixer->sq();
3867 FastMixerState *state = sq->begin();
3868 if (!(state->mCommand & FastMixerState::IDLE)) {
3869 state->mCommand = FastMixerState::COLD_IDLE;
3870 state->mColdFutexAddr = &mFastMixerFutex;
3871 state->mColdGen++;
3872 mFastMixerFutex = 0;
3873 sq->end();
3874 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3875 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3876 if (kUseFastMixer == FastMixer_Dynamic) {
3877 mNormalSink = mOutputSink;
3878 }
3879#ifdef AUDIO_WATCHDOG
3880 if (mAudioWatchdog != 0) {
3881 mAudioWatchdog->pause();
3882 }
3883#endif
3884 } else {
3885 sq->end(false /*didModify*/);
3886 }
3887 }
3888 PlaybackThread::threadLoop_standby();
3889}
3890
Eric Laurentbfb1b832013-01-07 09:53:42 -08003891bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3892{
3893 return false;
3894}
3895
3896bool AudioFlinger::PlaybackThread::shouldStandby_l()
3897{
3898 return !mStandby;
3899}
3900
3901bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3902{
3903 Mutex::Autolock _l(mLock);
3904 return waitingAsyncCallback_l();
3905}
3906
Eric Laurent81784c32012-11-19 14:55:58 -08003907// shared by MIXER and DIRECT, overridden by DUPLICATING
3908void AudioFlinger::PlaybackThread::threadLoop_standby()
3909{
3910 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08003911 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003912 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003913 // discard any pending drain or write ack by incrementing sequence
3914 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3915 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003916 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003917 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3918 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003919 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003920 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003921}
3922
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003923void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3924{
3925 ALOGV("signal playback thread");
3926 broadcast_l();
3927}
3928
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003929void AudioFlinger::PlaybackThread::onAsyncError()
3930{
3931 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
3932 invalidateTracks((audio_stream_type_t)i);
3933 }
3934}
3935
Eric Laurent81784c32012-11-19 14:55:58 -08003936void AudioFlinger::MixerThread::threadLoop_mix()
3937{
Eric Laurent81784c32012-11-19 14:55:58 -08003938 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08003939 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08003940 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003941 // increase sleep time progressively when application underrun condition clears.
3942 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3943 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3944 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003945 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003946 sleepTimeShift--;
3947 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003948 mSleepTimeUs = 0;
3949 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08003950 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003951
Eric Laurent81784c32012-11-19 14:55:58 -08003952}
3953
3954void AudioFlinger::MixerThread::threadLoop_sleepTime()
3955{
3956 // If no tracks are ready, sleep once for the duration of an output
3957 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003958 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003959 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003960 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
3961 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
3962 mSleepTimeUs = kMinThreadSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003963 }
3964 // reduce sleep time in case of consecutive application underruns to avoid
3965 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3966 // duration we would end up writing less data than needed by the audio HAL if
3967 // the condition persists.
3968 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3969 sleepTimeShift++;
3970 }
3971 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003972 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003973 }
3974 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003975 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3976 // before effects processing or output.
3977 if (mMixerBufferValid) {
3978 memset(mMixerBuffer, 0, mMixerBufferSize);
3979 } else {
3980 memset(mSinkBuffer, 0, mSinkBufferSize);
3981 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003982 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003983 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3984 "anticipated start");
3985 }
3986 // TODO add standby time extension fct of effect tail
3987}
3988
3989// prepareTracks_l() must be called with ThreadBase::mLock held
3990AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3991 Vector< sp<Track> > *tracksToRemove)
3992{
3993
3994 mixer_state mixerStatus = MIXER_IDLE;
3995 // find out which tracks need to be processed
3996 size_t count = mActiveTracks.size();
3997 size_t mixedTracks = 0;
3998 size_t tracksWithEffect = 0;
3999 // counts only _active_ fast tracks
4000 size_t fastTracks = 0;
4001 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
4002
4003 float masterVolume = mMasterVolume;
4004 bool masterMute = mMasterMute;
4005
4006 if (masterMute) {
4007 masterVolume = 0;
4008 }
4009 // Delegate master volume control to effect in output mix effect chain if needed
4010 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4011 if (chain != 0) {
4012 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
4013 chain->setVolume_l(&v, &v);
4014 masterVolume = (float)((v + (1 << 23)) >> 24);
4015 chain.clear();
4016 }
4017
4018 // prepare a new state to push
4019 FastMixerStateQueue *sq = NULL;
4020 FastMixerState *state = NULL;
4021 bool didModify = false;
4022 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004023 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004024 sq = mFastMixer->sq();
4025 state = sq->begin();
4026 }
4027
Andy Hung69aed5f2014-02-25 17:24:40 -08004028 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08004029 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08004030
Eric Laurent81784c32012-11-19 14:55:58 -08004031 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07004032 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08004033 if (t == 0) {
4034 continue;
4035 }
4036
4037 // this const just means the local variable doesn't change
4038 Track* const track = t.get();
4039
4040 // process fast tracks
4041 if (track->isFastTrack()) {
4042
4043 // It's theoretically possible (though unlikely) for a fast track to be created
4044 // and then removed within the same normal mix cycle. This is not a problem, as
4045 // the track never becomes active so it's fast mixer slot is never touched.
4046 // The converse, of removing an (active) track and then creating a new track
4047 // at the identical fast mixer slot within the same normal mix cycle,
4048 // is impossible because the slot isn't marked available until the end of each cycle.
4049 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07004050 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08004051 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
4052 FastTrack *fastTrack = &state->mFastTracks[j];
4053
4054 // Determine whether the track is currently in underrun condition,
4055 // and whether it had a recent underrun.
4056 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
4057 FastTrackUnderruns underruns = ftDump->mUnderruns;
4058 uint32_t recentFull = (underruns.mBitFields.mFull -
4059 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
4060 uint32_t recentPartial = (underruns.mBitFields.mPartial -
4061 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
4062 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
4063 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
4064 uint32_t recentUnderruns = recentPartial + recentEmpty;
4065 track->mObservedUnderruns = underruns;
4066 // don't count underruns that occur while stopping or pausing
4067 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07004068 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
4069 recentUnderruns > 0) {
4070 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
4071 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Phil Burk2812d9e2016-01-04 10:34:30 -08004072 } else {
4073 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Eric Laurent81784c32012-11-19 14:55:58 -08004074 }
4075
4076 // This is similar to the state machine for normal tracks,
4077 // with a few modifications for fast tracks.
4078 bool isActive = true;
4079 switch (track->mState) {
4080 case TrackBase::STOPPING_1:
4081 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08004082 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004083 track->mState = TrackBase::STOPPING_2;
4084 }
4085 break;
4086 case TrackBase::PAUSING:
4087 // ramp down is not yet implemented
4088 track->setPaused();
4089 break;
4090 case TrackBase::RESUMING:
4091 // ramp up is not yet implemented
4092 track->mState = TrackBase::ACTIVE;
4093 break;
4094 case TrackBase::ACTIVE:
4095 if (recentFull > 0 || recentPartial > 0) {
4096 // track has provided at least some frames recently: reset retry count
4097 track->mRetryCount = kMaxTrackRetries;
4098 }
4099 if (recentUnderruns == 0) {
4100 // no recent underruns: stay active
4101 break;
4102 }
4103 // there has recently been an underrun of some kind
4104 if (track->sharedBuffer() == 0) {
4105 // were any of the recent underruns "empty" (no frames available)?
4106 if (recentEmpty == 0) {
4107 // no, then ignore the partial underruns as they are allowed indefinitely
4108 break;
4109 }
4110 // there has recently been an "empty" underrun: decrement the retry counter
4111 if (--(track->mRetryCount) > 0) {
4112 break;
4113 }
4114 // indicate to client process that the track was disabled because of underrun;
4115 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004116 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004117 // remove from active list, but state remains ACTIVE [confusing but true]
4118 isActive = false;
4119 break;
4120 }
4121 // fall through
4122 case TrackBase::STOPPING_2:
4123 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08004124 case TrackBase::STOPPED:
4125 case TrackBase::FLUSHED: // flush() while active
4126 // Check for presentation complete if track is inactive
4127 // We have consumed all the buffers of this track.
4128 // This would be incomplete if we auto-paused on underrun
4129 {
4130 size_t audioHALFrames =
4131 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004132 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004133 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
4134 // track stays in active list until presentation is complete
4135 break;
4136 }
4137 }
4138 if (track->isStopping_2()) {
4139 track->mState = TrackBase::STOPPED;
4140 }
4141 if (track->isStopped()) {
4142 // Can't reset directly, as fast mixer is still polling this track
4143 // track->reset();
4144 // So instead mark this track as needing to be reset after push with ack
4145 resetMask |= 1 << i;
4146 }
4147 isActive = false;
4148 break;
4149 case TrackBase::IDLE:
4150 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08004151 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08004152 }
4153
4154 if (isActive) {
4155 // was it previously inactive?
4156 if (!(state->mTrackMask & (1 << j))) {
4157 ExtendedAudioBufferProvider *eabp = track;
4158 VolumeProvider *vp = track;
4159 fastTrack->mBufferProvider = eabp;
4160 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08004161 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07004162 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08004163 fastTrack->mGeneration++;
4164 state->mTrackMask |= 1 << j;
4165 didModify = true;
4166 // no acknowledgement required for newly active tracks
4167 }
4168 // cache the combined master volume and stream type volume for fast mixer; this
4169 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08004170 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08004171 ++fastTracks;
4172 } else {
4173 // was it previously active?
4174 if (state->mTrackMask & (1 << j)) {
4175 fastTrack->mBufferProvider = NULL;
4176 fastTrack->mGeneration++;
4177 state->mTrackMask &= ~(1 << j);
4178 didModify = true;
4179 // If any fast tracks were removed, we must wait for acknowledgement
4180 // because we're about to decrement the last sp<> on those tracks.
4181 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4182 } else {
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08004183 LOG_ALWAYS_FATAL("fast track %d should have been active; "
4184 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
4185 j, track->mState, state->mTrackMask, recentUnderruns,
4186 track->sharedBuffer() != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004187 }
4188 tracksToRemove->add(track);
4189 // Avoids a misleading display in dumpsys
4190 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
4191 }
4192 continue;
4193 }
4194
4195 { // local variable scope to avoid goto warning
4196
4197 audio_track_cblk_t* cblk = track->cblk();
4198
4199 // The first time a track is added we wait
4200 // for all its buffers to be filled before processing it
4201 int name = track->name();
4202 // make sure that we have enough frames to mix one full buffer.
4203 // enforce this condition only once to enable draining the buffer in case the client
4204 // app does not call stop() and relies on underrun to stop:
4205 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
4206 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004207 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07004208 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004209 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004210
4211 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004212 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004213 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
4214 // add frames already consumed but not yet released by the resampler
4215 // because mAudioTrackServerProxy->framesReady() will include these frames
4216 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
4217
Eric Laurent81784c32012-11-19 14:55:58 -08004218 uint32_t minFrames = 1;
4219 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
4220 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004221 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08004222 }
Eric Laurent13e4c962013-12-20 17:36:01 -08004223
4224 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07004225 if (ATRACE_ENABLED()) {
4226 // I wish we had formatted trace names
4227 char traceName[16];
4228 strcpy(traceName, "nRdy");
4229 int name = track->name();
4230 if (AudioMixer::TRACK0 <= name &&
4231 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
4232 name -= AudioMixer::TRACK0;
4233 traceName[4] = (name / 10) + '0';
4234 traceName[5] = (name % 10) + '0';
4235 } else {
4236 traceName[4] = '?';
4237 traceName[5] = '?';
4238 }
4239 traceName[6] = '\0';
4240 ATRACE_INT(traceName, framesReady);
4241 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004242 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08004243 !track->isPaused() && !track->isTerminated())
4244 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004245 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004246
4247 mixedTracks++;
4248
Andy Hung69aed5f2014-02-25 17:24:40 -08004249 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
4250 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08004251 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08004252 if (track->mainBuffer() != mSinkBuffer &&
4253 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004254 if (mEffectBufferEnabled) {
4255 mEffectBufferValid = true; // Later can set directly.
4256 }
Eric Laurent81784c32012-11-19 14:55:58 -08004257 chain = getEffectChain_l(track->sessionId());
4258 // Delegate volume control to effect in track effect chain if needed
4259 if (chain != 0) {
4260 tracksWithEffect++;
4261 } else {
4262 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
4263 "session %d",
4264 name, track->sessionId());
4265 }
4266 }
4267
4268
4269 int param = AudioMixer::VOLUME;
4270 if (track->mFillingUpStatus == Track::FS_FILLED) {
4271 // no ramp for the first volume setting
4272 track->mFillingUpStatus = Track::FS_ACTIVE;
4273 if (track->mState == TrackBase::RESUMING) {
4274 track->mState = TrackBase::ACTIVE;
4275 param = AudioMixer::RAMP_VOLUME;
4276 }
4277 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004278 // FIXME should not make a decision based on mServer
4279 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004280 // If the track is stopped before the first frame was mixed,
4281 // do not apply ramp
4282 param = AudioMixer::RAMP_VOLUME;
4283 }
4284
4285 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07004286 uint32_t vl, vr; // in U8.24 integer format
4287 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08004288 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07004289 vl = vr = 0;
4290 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08004291 if (track->isPausing()) {
4292 track->setPaused();
4293 }
4294 } else {
4295
4296 // read original volumes with volume control
4297 float typeVolume = mStreamTypes[track->streamType()].volume;
4298 float v = masterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07004299 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004300 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07004301 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
4302 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08004303 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07004304 if (vlf > GAIN_FLOAT_UNITY) {
4305 ALOGV("Track left volume out of range: %.3g", vlf);
4306 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004307 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07004308 if (vrf > GAIN_FLOAT_UNITY) {
4309 ALOGV("Track right volume out of range: %.3g", vrf);
4310 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004311 }
4312 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07004313 vlf *= v;
4314 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08004315 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07004316 // then derive vl and vr as U8.24 versions for the effect chain
4317 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
4318 vl = (uint32_t) (scaleto8_24 * vlf);
4319 vr = (uint32_t) (scaleto8_24 * vrf);
4320 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08004321 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08004322 // send level comes from shared memory and so may be corrupt
4323 if (sendLevel > MAX_GAIN_INT) {
4324 ALOGV("Track send level out of range: %04X", sendLevel);
4325 sendLevel = MAX_GAIN_INT;
4326 }
Andy Hung6be49402014-05-30 10:42:03 -07004327 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4328 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08004329 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004330
Eric Laurent81784c32012-11-19 14:55:58 -08004331 // Delegate volume control to effect in track effect chain if needed
4332 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4333 // Do not ramp volume if volume is controlled by effect
4334 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08004335 // Update remaining floating point volume levels
4336 vlf = (float)vl / (1 << 24);
4337 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004338 track->mHasVolumeController = true;
4339 } else {
4340 // force no volume ramp when volume controller was just disabled or removed
4341 // from effect chain to avoid volume spike
4342 if (track->mHasVolumeController) {
4343 param = AudioMixer::VOLUME;
4344 }
4345 track->mHasVolumeController = false;
4346 }
4347
Eric Laurent81784c32012-11-19 14:55:58 -08004348 // XXX: these things DON'T need to be done each time
4349 mAudioMixer->setBufferProvider(name, track);
4350 mAudioMixer->enable(name);
4351
Andy Hung6be49402014-05-30 10:42:03 -07004352 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
4353 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
4354 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004355 mAudioMixer->setParameter(
4356 name,
4357 AudioMixer::TRACK,
4358 AudioMixer::FORMAT, (void *)track->format());
4359 mAudioMixer->setParameter(
4360 name,
4361 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004362 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004363 mAudioMixer->setParameter(
4364 name,
4365 AudioMixer::TRACK,
4366 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004367 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004368 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004369 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004370 if (reqSampleRate == 0) {
4371 reqSampleRate = mSampleRate;
4372 } else if (reqSampleRate > maxSampleRate) {
4373 reqSampleRate = maxSampleRate;
4374 }
Eric Laurent81784c32012-11-19 14:55:58 -08004375 mAudioMixer->setParameter(
4376 name,
4377 AudioMixer::RESAMPLE,
4378 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004379 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004380
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004381 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004382 mAudioMixer->setParameter(
4383 name,
4384 AudioMixer::TIMESTRETCH,
4385 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004386 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004387
Andy Hung69aed5f2014-02-25 17:24:40 -08004388 /*
4389 * Select the appropriate output buffer for the track.
4390 *
Andy Hung98ef9782014-03-04 14:46:50 -08004391 * Tracks with effects go into their own effects chain buffer
4392 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004393 *
4394 * Other tracks can use mMixerBuffer for higher precision
4395 * channel accumulation. If this buffer is enabled
4396 * (mMixerBufferEnabled true), then selected tracks will accumulate
4397 * into it.
4398 *
4399 */
4400 if (mMixerBufferEnabled
4401 && (track->mainBuffer() == mSinkBuffer
4402 || track->mainBuffer() == mMixerBuffer)) {
4403 mAudioMixer->setParameter(
4404 name,
4405 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004406 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004407 mAudioMixer->setParameter(
4408 name,
4409 AudioMixer::TRACK,
4410 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4411 // TODO: override track->mainBuffer()?
4412 mMixerBufferValid = true;
4413 } else {
4414 mAudioMixer->setParameter(
4415 name,
4416 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004417 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004418 mAudioMixer->setParameter(
4419 name,
4420 AudioMixer::TRACK,
4421 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4422 }
Eric Laurent81784c32012-11-19 14:55:58 -08004423 mAudioMixer->setParameter(
4424 name,
4425 AudioMixer::TRACK,
4426 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4427
4428 // reset retry count
4429 track->mRetryCount = kMaxTrackRetries;
4430
4431 // If one track is ready, set the mixer ready if:
4432 // - the mixer was not ready during previous round OR
4433 // - no other track is not ready
4434 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4435 mixerStatus != MIXER_TRACKS_ENABLED) {
4436 mixerStatus = MIXER_TRACKS_READY;
4437 }
4438 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004439 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hung08fb1742015-05-31 23:22:10 -07004440 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)",
4441 track, framesReady, desiredFrames);
Glenn Kasten82aaf942013-07-17 16:05:07 -07004442 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08004443 } else {
4444 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004445 }
Phil Burk2812d9e2016-01-04 10:34:30 -08004446
Eric Laurent81784c32012-11-19 14:55:58 -08004447 // clear effect chain input buffer if an active track underruns to avoid sending
4448 // previous audio buffer again to effects
4449 chain = getEffectChain_l(track->sessionId());
4450 if (chain != 0) {
4451 chain->clearInputBuffer();
4452 }
4453
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004454 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004455 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4456 track->isStopped() || track->isPaused()) {
4457 // We have consumed all the buffers of this track.
4458 // Remove it from the list of active tracks.
4459 // TODO: use actual buffer filling status instead of latency when available from
4460 // audio HAL
4461 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004462 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004463 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4464 if (track->isStopped()) {
4465 track->reset();
4466 }
4467 tracksToRemove->add(track);
4468 }
4469 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004470 // No buffers for this track. Give it a few chances to
4471 // fill a buffer, then remove it from active list.
4472 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004473 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004474 tracksToRemove->add(track);
4475 // indicate to client process that the track was disabled because of underrun;
4476 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004477 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004478 // If one track is not ready, mark the mixer also not ready if:
4479 // - the mixer was ready during previous round OR
4480 // - no other track is ready
4481 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4482 mixerStatus != MIXER_TRACKS_READY) {
4483 mixerStatus = MIXER_TRACKS_ENABLED;
4484 }
4485 }
4486 mAudioMixer->disable(name);
4487 }
4488
4489 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08004490
4491 }
4492
4493 // Push the new FastMixer state if necessary
4494 bool pauseAudioWatchdog = false;
4495 if (didModify) {
4496 state->mFastTracksGen++;
4497 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4498 if (kUseFastMixer == FastMixer_Dynamic &&
4499 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4500 state->mCommand = FastMixerState::COLD_IDLE;
4501 state->mColdFutexAddr = &mFastMixerFutex;
4502 state->mColdGen++;
4503 mFastMixerFutex = 0;
4504 if (kUseFastMixer == FastMixer_Dynamic) {
4505 mNormalSink = mOutputSink;
4506 }
4507 // If we go into cold idle, need to wait for acknowledgement
4508 // so that fast mixer stops doing I/O.
4509 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4510 pauseAudioWatchdog = true;
4511 }
Eric Laurent81784c32012-11-19 14:55:58 -08004512 }
4513 if (sq != NULL) {
4514 sq->end(didModify);
4515 sq->push(block);
4516 }
4517#ifdef AUDIO_WATCHDOG
4518 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4519 mAudioWatchdog->pause();
4520 }
4521#endif
4522
4523 // Now perform the deferred reset on fast tracks that have stopped
4524 while (resetMask != 0) {
4525 size_t i = __builtin_ctz(resetMask);
4526 ALOG_ASSERT(i < count);
4527 resetMask &= ~(1 << i);
4528 sp<Track> t = mActiveTracks[i].promote();
4529 if (t == 0) {
4530 continue;
4531 }
4532 Track* track = t.get();
4533 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4534 track->reset();
4535 }
4536
4537 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004538 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004539
Eric Laurent97d547d2014-09-02 14:45:53 -07004540 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4541 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004542 }
4543
4544 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004545 // as long as there are effects we should clear the effects buffer, to avoid
4546 // passing a non-clean buffer to the effect chain
4547 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004548 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004549 // sink or mix buffer must be cleared if all tracks are connected to an
4550 // effect chain as in this case the mixer will not write to the sink or mix buffer
4551 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004552 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4553 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004554 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004555 if (mMixerBufferValid) {
4556 memset(mMixerBuffer, 0, mMixerBufferSize);
4557 // TODO: In testing, mSinkBuffer below need not be cleared because
4558 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4559 // after mixing.
4560 //
4561 // To enforce this guarantee:
4562 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4563 // (mixedTracks == 0 && fastTracks > 0))
4564 // must imply MIXER_TRACKS_READY.
4565 // Later, we may clear buffers regardless, and skip much of this logic.
4566 }
Andy Hung98ef9782014-03-04 14:46:50 -08004567 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004568 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004569 }
4570
4571 // if any fast tracks, then status is ready
4572 mMixerStatusIgnoringFastTracks = mixerStatus;
4573 if (fastTracks > 0) {
4574 mixerStatus = MIXER_TRACKS_READY;
4575 }
4576 return mixerStatus;
4577}
4578
4579// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07004580int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
Glenn Kastend848eb42016-03-08 13:42:11 -08004581 audio_format_t format, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08004582{
Andy Hunge8a1ced2014-05-09 15:02:21 -07004583 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08004584}
4585
4586// deleteTrackName_l() must be called with ThreadBase::mLock held
4587void AudioFlinger::MixerThread::deleteTrackName_l(int name)
4588{
4589 ALOGV("remove track (%d) and delete from mixer", name);
4590 mAudioMixer->deleteTrackName(name);
4591}
4592
Eric Laurent10351942014-05-08 18:49:52 -07004593// checkForNewParameter_l() must be called with ThreadBase::mLock held
4594bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4595 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004596{
Eric Laurent81784c32012-11-19 14:55:58 -08004597 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08004598 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004599
Eric Laurent10351942014-05-08 18:49:52 -07004600 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004601
Glenn Kastenc05b8d72016-03-24 09:48:17 -07004602 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004603
Eric Laurent10351942014-05-08 18:49:52 -07004604 AudioParameter param = AudioParameter(keyValuePair);
4605 int value;
4606 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4607 reconfig = true;
4608 }
4609 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004610 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004611 status = BAD_VALUE;
4612 } else {
4613 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004614 reconfig = true;
4615 }
Eric Laurent10351942014-05-08 18:49:52 -07004616 }
4617 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004618 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004619 status = BAD_VALUE;
4620 } else {
4621 // no need to save value, since it's constant
4622 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004623 }
Eric Laurent10351942014-05-08 18:49:52 -07004624 }
4625 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4626 // do not accept frame count changes if tracks are open as the track buffer
4627 // size depends on frame count and correct behavior would not be guaranteed
4628 // if frame count is changed after track creation
4629 if (!mTracks.isEmpty()) {
4630 status = INVALID_OPERATION;
4631 } else {
4632 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004633 }
Eric Laurent10351942014-05-08 18:49:52 -07004634 }
4635 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004636#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004637 // when changing the audio output device, call addBatteryData to notify
4638 // the change
4639 if (mOutDevice != value) {
4640 uint32_t params = 0;
4641 // check whether speaker is on
4642 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4643 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004644 }
Eric Laurent10351942014-05-08 18:49:52 -07004645
4646 audio_devices_t deviceWithoutSpeaker
4647 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4648 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07004649 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07004650 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4651 }
4652
4653 if (params != 0) {
4654 addBatteryData(params);
4655 }
4656 }
Eric Laurent81784c32012-11-19 14:55:58 -08004657#endif
4658
Eric Laurent10351942014-05-08 18:49:52 -07004659 // forward device change to effects that have requested to be
4660 // aware of attached audio device.
4661 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08004662 a2dpDeviceChanged =
4663 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07004664 mOutDevice = value;
4665 for (size_t i = 0; i < mEffectChains.size(); i++) {
4666 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004667 }
4668 }
Eric Laurent10351942014-05-08 18:49:52 -07004669 }
Eric Laurent81784c32012-11-19 14:55:58 -08004670
Eric Laurent10351942014-05-08 18:49:52 -07004671 if (status == NO_ERROR) {
4672 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4673 keyValuePair.string());
4674 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004675 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004676 mStandby = true;
4677 mBytesWritten = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004678 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Eric Laurent10351942014-05-08 18:49:52 -07004679 keyValuePair.string());
Eric Laurent81784c32012-11-19 14:55:58 -08004680 }
Eric Laurent10351942014-05-08 18:49:52 -07004681 if (status == NO_ERROR && reconfig) {
4682 readOutputParameters_l();
4683 delete mAudioMixer;
4684 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4685 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004686 int name = getTrackName_l(mTracks[i]->mChannelMask,
4687 mTracks[i]->mFormat, mTracks[i]->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07004688 if (name < 0) {
4689 break;
4690 }
4691 mTracks[i]->mName = name;
4692 }
Eric Laurent73e26b62015-04-27 16:55:58 -07004693 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004694 }
Eric Laurent81784c32012-11-19 14:55:58 -08004695 }
4696
Eric Laurent42537be2016-01-08 17:16:42 -08004697 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08004698}
4699
4700
4701void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4702{
Eric Laurent81784c32012-11-19 14:55:58 -08004703 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07004704 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Elliott Hughes87cebad2014-05-22 10:14:43 -07004705 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Andy Hung2ddee192015-12-18 17:34:44 -08004706 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent81784c32012-11-19 14:55:58 -08004707
4708 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten2f90c512015-12-02 11:40:09 -08004709 // while we are dumping it. It may be inconsistent, but it won't mutate!
4710 // This is a large object so we place it on the heap.
4711 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
4712 const FastMixerDumpState *copy = new FastMixerDumpState(mFastMixerDumpState);
4713 copy->dump(fd);
4714 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08004715
4716#ifdef STATE_QUEUE_DUMP
4717 // Similar for state queue
4718 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4719 observerCopy.dump(fd);
4720 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4721 mutatorCopy.dump(fd);
4722#endif
4723
Glenn Kasten46909e72013-02-26 09:20:22 -08004724#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004725 // Write the tee output to a .wav file
4726 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08004727#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004728
4729#ifdef AUDIO_WATCHDOG
4730 if (mAudioWatchdog != 0) {
4731 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4732 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4733 wdCopy.dump(fd);
4734 }
4735#endif
4736}
4737
4738uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4739{
4740 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4741}
4742
4743uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4744{
4745 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4746}
4747
4748void AudioFlinger::MixerThread::cacheParameters_l()
4749{
4750 PlaybackThread::cacheParameters_l();
4751
4752 // FIXME: Relaxed timing because of a certain device that can't meet latency
4753 // Should be reduced to 2x after the vendor fixes the driver issue
4754 // increase threshold again due to low power audio mode. The way this warning
4755 // threshold is calculated and its usefulness should be reconsidered anyway.
4756 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4757}
4758
4759// ----------------------------------------------------------------------------
4760
4761AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07004762 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady)
4763 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08004764 // mLeftVolFloat, mRightVolFloat
4765{
4766}
4767
Eric Laurentbfb1b832013-01-07 09:53:42 -08004768AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4769 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurente93cc032016-05-05 10:15:10 -07004770 ThreadBase::type_t type, bool systemReady)
4771 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004772 // mLeftVolFloat, mRightVolFloat
4773{
4774}
4775
Eric Laurent81784c32012-11-19 14:55:58 -08004776AudioFlinger::DirectOutputThread::~DirectOutputThread()
4777{
4778}
4779
Eric Laurentbfb1b832013-01-07 09:53:42 -08004780void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
4781{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004782 float left, right;
4783
4784 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4785 left = right = 0;
4786 } else {
4787 float typeVolume = mStreamTypes[track->streamType()].volume;
4788 float v = mMasterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07004789 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004790 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4791 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4792 if (left > GAIN_FLOAT_UNITY) {
4793 left = GAIN_FLOAT_UNITY;
4794 }
4795 left *= v;
4796 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4797 if (right > GAIN_FLOAT_UNITY) {
4798 right = GAIN_FLOAT_UNITY;
4799 }
4800 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004801 }
4802
4803 if (lastTrack) {
4804 if (left != mLeftVolFloat || right != mRightVolFloat) {
4805 mLeftVolFloat = left;
4806 mRightVolFloat = right;
4807
4808 // Convert volumes from float to 8.24
4809 uint32_t vl = (uint32_t)(left * (1 << 24));
4810 uint32_t vr = (uint32_t)(right * (1 << 24));
4811
4812 // Delegate volume control to effect in track effect chain if needed
4813 // only one effect chain can be present on DirectOutputThread, so if
4814 // there is one, the track is connected to it
4815 if (!mEffectChains.isEmpty()) {
4816 mEffectChains[0]->setVolume_l(&vl, &vr);
4817 left = (float)vl / (1 << 24);
4818 right = (float)vr / (1 << 24);
4819 }
4820 if (mOutput->stream->set_volume) {
4821 mOutput->stream->set_volume(mOutput->stream, left, right);
4822 }
4823 }
4824 }
4825}
4826
Phil Burk43b4dcc2015-06-09 16:53:44 -07004827void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
4828{
4829 sp<Track> previousTrack = mPreviousTrack.promote();
4830 sp<Track> latestTrack = mLatestActiveTrack.promote();
4831
Eric Laurent0f0631e2015-07-06 18:01:25 -07004832 if (previousTrack != 0 && latestTrack != 0) {
4833 if (mType == DIRECT) {
4834 if (previousTrack.get() != latestTrack.get()) {
4835 mFlushPending = true;
4836 }
4837 } else /* mType == OFFLOAD */ {
4838 if (previousTrack->sessionId() != latestTrack->sessionId()) {
4839 mFlushPending = true;
4840 }
4841 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004842 }
4843 PlaybackThread::onAddNewTrack_l();
4844}
Eric Laurentbfb1b832013-01-07 09:53:42 -08004845
Eric Laurent81784c32012-11-19 14:55:58 -08004846AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4847 Vector< sp<Track> > *tracksToRemove
4848)
4849{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004850 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004851 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004852 bool doHwPause = false;
4853 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004854
4855 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07004856 for (size_t i = 0; i < count; i++) {
4857 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08004858 // The track died recently
4859 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004860 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08004861 }
4862
Phil Burk43b4dcc2015-06-09 16:53:44 -07004863 if (t->isInvalid()) {
4864 ALOGW("An invalidated track shouldn't be in active list");
4865 tracksToRemove->add(t);
4866 continue;
4867 }
4868
Eric Laurent81784c32012-11-19 14:55:58 -08004869 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004870#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08004871 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004872#endif
Eric Laurentfd477972013-10-25 18:10:40 -07004873 // Only consider last track started for volume and mixer state control.
4874 // In theory an older track could underrun and restart after the new one starts
4875 // but as we only care about the transition phase between two tracks on a
4876 // direct output, it is not a problem to ignore the underrun case.
4877 sp<Track> l = mLatestActiveTrack.promote();
4878 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004879
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004880 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004881 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004882 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004883 doHwPause = true;
4884 mHwPaused = true;
4885 }
4886 tracksToRemove->add(track);
4887 } else if (track->isFlushPending()) {
4888 track->flushAck();
4889 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004890 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004891 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004892 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004893 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07004894 if (last) {
4895 mLeftVolFloat = mRightVolFloat = -1.0;
4896 if (mHwPaused) {
4897 doHwResume = true;
4898 mHwPaused = false;
4899 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004900 }
4901 }
4902
Eric Laurent81784c32012-11-19 14:55:58 -08004903 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004904 // for all its buffers to be filled before processing it.
4905 // Allow draining the buffer in case the client
4906 // app does not call stop() and relies on underrun to stop:
4907 // hence the test on (track->mRetryCount > 1).
4908 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07004909 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08004910 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004911 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08004912 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004913 minFrames = mNormalFrameCount;
4914 } else {
4915 minFrames = 1;
4916 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004917
Eric Laurentab5cdba2014-06-09 17:22:27 -07004918 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4919 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004920 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004921 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004922
4923 if (track->mFillingUpStatus == Track::FS_FILLED) {
4924 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07004925 if (last) {
4926 // make sure processVolume_l() will apply new volume even if 0
4927 mLeftVolFloat = mRightVolFloat = -1.0;
4928 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004929 if (!mHwSupportsPause) {
4930 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004931 }
4932 }
4933
4934 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004935 processVolume_l(track, last);
4936 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004937 sp<Track> previousTrack = mPreviousTrack.promote();
4938 if (previousTrack != 0) {
4939 if (track != previousTrack.get()) {
4940 // Flush any data still being written from last track
4941 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07004942 // Invalidate previous track to force a seek when resuming.
4943 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004944 }
4945 }
4946 mPreviousTrack = track;
4947
Eric Laurentd595b7c2013-04-03 17:27:56 -07004948 // reset retry count
4949 track->mRetryCount = kMaxTrackRetriesDirect;
4950 mActiveTrack = t;
4951 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07004952 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004953 doHwResume = true;
4954 mHwPaused = false;
4955 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004956 }
Eric Laurent81784c32012-11-19 14:55:58 -08004957 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004958 // clear effect chain input buffer if the last active track started underruns
4959 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004960 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004961 mEffectChains[0]->clearInputBuffer();
4962 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004963 if (track->isStopping_1()) {
4964 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07004965 if (last && mHwPaused) {
4966 doHwResume = true;
4967 mHwPaused = false;
4968 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004969 }
4970 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4971 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004972 // We have consumed all the buffers of this track.
4973 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004974 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08004975 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004976 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4977 } else {
4978 audioHALFrames = 0;
4979 }
4980
Andy Hung818e7a32016-02-16 18:08:07 -08004981 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004982 if (mStandby || !last ||
4983 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004984 if (track->isStopping_2()) {
4985 track->mState = TrackBase::STOPPED;
4986 }
Eric Laurent81784c32012-11-19 14:55:58 -08004987 if (track->isStopped()) {
4988 track->reset();
4989 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004990 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004991 }
4992 } else {
4993 // No buffers for this track. Give it a few chances to
4994 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004995 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004996 if (--(track->mRetryCount) <= 0) {
4997 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004998 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004999 // indicate to client process that the track was disabled because of underrun;
5000 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005001 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005002 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07005003 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
5004 "minFrames = %u, mFormat = %#x",
5005 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08005006 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07005007 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005008 doHwPause = true;
5009 mHwPaused = true;
5010 }
Eric Laurent81784c32012-11-19 14:55:58 -08005011 }
5012 }
5013 }
5014 }
5015
Eric Laurentd1f69b02014-12-15 14:33:13 -08005016 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07005017 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005018 for (size_t i = 0; i < mTracks.size(); i++) {
5019 if (mTracks[i]->isFlushPending()) {
5020 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005021 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005022 }
5023 }
5024 }
5025
5026 // make sure the pause/flush/resume sequence is executed in the right order.
5027 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5028 // before flush and then resume HW. This can happen in case of pause/flush/resume
5029 // if resume is received before pause is executed.
5030 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07005031 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005032 mOutput->stream->pause(mOutput->stream);
5033 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005034 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005035 flushHw_l();
5036 }
5037 if (mHwSupportsPause && !mStandby && doHwResume) {
5038 mOutput->stream->resume(mOutput->stream);
5039 }
Eric Laurent81784c32012-11-19 14:55:58 -08005040 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005041 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005042
5043 return mixerStatus;
5044}
5045
5046void AudioFlinger::DirectOutputThread::threadLoop_mix()
5047{
Eric Laurent81784c32012-11-19 14:55:58 -08005048 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08005049 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005050 // output audio to hardware
5051 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07005052 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005053 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08005054 status_t status = mActiveTrack->getNextBuffer(&buffer);
5055 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08005056 // no need to pad with 0 for compressed audio
5057 if (audio_has_proportional_frames(mFormat)) {
5058 memset(curBuf, 0, frameCount * mFrameSize);
5059 }
Eric Laurent81784c32012-11-19 14:55:58 -08005060 break;
5061 }
5062 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
5063 frameCount -= buffer.frameCount;
5064 curBuf += buffer.frameCount * mFrameSize;
5065 mActiveTrack->releaseBuffer(&buffer);
5066 }
Andy Hung2098f272014-02-27 14:00:06 -08005067 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005068 mSleepTimeUs = 0;
5069 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005070 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005071}
5072
5073void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
5074{
Eric Laurentd1f69b02014-12-15 14:33:13 -08005075 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005076 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005077 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005078 return;
5079 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005080 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005081 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurente93cc032016-05-05 10:15:10 -07005082 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005083 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005084 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005085 }
Phil Burkfdb3c072016-02-09 10:47:02 -08005086 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08005087 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005088 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005089 }
5090}
5091
Eric Laurentd1f69b02014-12-15 14:33:13 -08005092void AudioFlinger::DirectOutputThread::threadLoop_exit()
5093{
5094 {
5095 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005096 for (size_t i = 0; i < mTracks.size(); i++) {
5097 if (mTracks[i]->isFlushPending()) {
5098 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005099 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005100 }
5101 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005102 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005103 flushHw_l();
5104 }
5105 }
5106 PlaybackThread::threadLoop_exit();
5107}
5108
5109// must be called with thread mutex locked
5110bool AudioFlinger::DirectOutputThread::shouldStandby_l()
5111{
5112 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07005113 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005114
vivek mehta9cd7ad12016-03-17 00:18:29 -07005115 if ((mType == DIRECT) && audio_is_linear_pcm(mFormat) && !usesHwAvSync()) {
5116 return !mStandby;
5117 }
5118
Eric Laurentd1f69b02014-12-15 14:33:13 -08005119 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
5120 // after a timeout and we will enter standby then.
5121 if (mTracks.size() > 0) {
5122 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07005123 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
5124 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005125 }
5126
Eric Laurent5cff4032015-05-26 13:49:58 -07005127 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08005128}
5129
Eric Laurent81784c32012-11-19 14:55:58 -08005130// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005131int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Glenn Kastend848eb42016-03-08 13:42:11 -08005132 audio_format_t format __unused, audio_session_t sessionId __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005133{
5134 return 0;
5135}
5136
5137// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005138void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005139{
5140}
5141
Eric Laurent10351942014-05-08 18:49:52 -07005142// checkForNewParameter_l() must be called with ThreadBase::mLock held
5143bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
5144 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005145{
5146 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005147 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005148
Eric Laurent10351942014-05-08 18:49:52 -07005149 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005150
Eric Laurent10351942014-05-08 18:49:52 -07005151 AudioParameter param = AudioParameter(keyValuePair);
5152 int value;
5153 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5154 // forward device change to effects that have requested to be
5155 // aware of attached audio device.
5156 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005157 a2dpDeviceChanged =
5158 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005159 mOutDevice = value;
5160 for (size_t i = 0; i < mEffectChains.size(); i++) {
5161 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07005162 }
5163 }
Eric Laurent81784c32012-11-19 14:55:58 -08005164 }
Eric Laurent10351942014-05-08 18:49:52 -07005165 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5166 // do not accept frame count changes if tracks are open as the track buffer
5167 // size depends on frame count and correct behavior would not be garantied
5168 // if frame count is changed after track creation
5169 if (!mTracks.isEmpty()) {
5170 status = INVALID_OPERATION;
5171 } else {
5172 reconfig = true;
5173 }
5174 }
5175 if (status == NO_ERROR) {
5176 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
5177 keyValuePair.string());
5178 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005179 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005180 mStandby = true;
5181 mBytesWritten = 0;
5182 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
5183 keyValuePair.string());
5184 }
5185 if (status == NO_ERROR && reconfig) {
5186 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07005187 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005188 }
5189 }
5190
Eric Laurent42537be2016-01-08 17:16:42 -08005191 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005192}
5193
5194uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
5195{
5196 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005197 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005198 time = PlaybackThread::activeSleepTimeUs();
5199 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005200 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005201 }
5202 return time;
5203}
5204
5205uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
5206{
5207 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005208 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005209 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
5210 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005211 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005212 }
5213 return time;
5214}
5215
5216uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
5217{
5218 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005219 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005220 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
5221 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005222 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005223 }
5224 return time;
5225}
5226
5227void AudioFlinger::DirectOutputThread::cacheParameters_l()
5228{
5229 PlaybackThread::cacheParameters_l();
5230
5231 // use shorter standby delay as on normal output to release
5232 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07005233 // no delay on outputs with HW A/V sync
5234 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005235 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08005236 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005237 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07005238 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005239 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07005240 }
Eric Laurent81784c32012-11-19 14:55:58 -08005241}
5242
Eric Laurente659ef42014-09-29 13:06:46 -07005243void AudioFlinger::DirectOutputThread::flushHw_l()
5244{
Phil Burk062e67a2015-02-11 13:40:50 -08005245 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08005246 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005247 mFlushPending = false;
Eric Laurente659ef42014-09-29 13:06:46 -07005248}
5249
Eric Laurent81784c32012-11-19 14:55:58 -08005250// ----------------------------------------------------------------------------
5251
Eric Laurentbfb1b832013-01-07 09:53:42 -08005252AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07005253 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005254 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07005255 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07005256 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005257 mDrainSequence(0),
5258 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005259{
5260}
5261
5262AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
5263{
5264}
5265
5266void AudioFlinger::AsyncCallbackThread::onFirstRef()
5267{
5268 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
5269}
5270
5271bool AudioFlinger::AsyncCallbackThread::threadLoop()
5272{
5273 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005274 uint32_t writeAckSequence;
5275 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005276 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005277
5278 {
5279 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005280 while (!((mWriteAckSequence & 1) ||
5281 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005282 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005283 exitPending())) {
5284 mWaitWorkCV.wait(mLock);
5285 }
5286
Eric Laurentbfb1b832013-01-07 09:53:42 -08005287 if (exitPending()) {
5288 break;
5289 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005290 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
5291 mWriteAckSequence, mDrainSequence);
5292 writeAckSequence = mWriteAckSequence;
5293 mWriteAckSequence &= ~1;
5294 drainSequence = mDrainSequence;
5295 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005296 asyncError = mAsyncError;
5297 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005298 }
5299 {
Eric Laurent4de95592013-09-26 15:28:21 -07005300 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
5301 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005302 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005303 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005304 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005305 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005306 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005307 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005308 if (asyncError) {
5309 playbackThread->onAsyncError();
5310 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005311 }
5312 }
5313 }
5314 return false;
5315}
5316
5317void AudioFlinger::AsyncCallbackThread::exit()
5318{
5319 ALOGV("AsyncCallbackThread::exit");
5320 Mutex::Autolock _l(mLock);
5321 requestExit();
5322 mWaitWorkCV.broadcast();
5323}
5324
Eric Laurent3b4529e2013-09-05 18:09:19 -07005325void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005326{
5327 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005328 // bit 0 is cleared
5329 mWriteAckSequence = sequence << 1;
5330}
5331
5332void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5333{
5334 Mutex::Autolock _l(mLock);
5335 // ignore unexpected callbacks
5336 if (mWriteAckSequence & 2) {
5337 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005338 mWaitWorkCV.signal();
5339 }
5340}
5341
Eric Laurent3b4529e2013-09-05 18:09:19 -07005342void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005343{
5344 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005345 // bit 0 is cleared
5346 mDrainSequence = sequence << 1;
5347}
5348
5349void AudioFlinger::AsyncCallbackThread::resetDraining()
5350{
5351 Mutex::Autolock _l(mLock);
5352 // ignore unexpected callbacks
5353 if (mDrainSequence & 2) {
5354 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005355 mWaitWorkCV.signal();
5356 }
5357}
5358
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005359void AudioFlinger::AsyncCallbackThread::setAsyncError()
5360{
5361 Mutex::Autolock _l(mLock);
5362 mAsyncError = true;
5363 mWaitWorkCV.signal();
5364}
5365
Eric Laurentbfb1b832013-01-07 09:53:42 -08005366
5367// ----------------------------------------------------------------------------
5368AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07005369 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
5370 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07005371 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
5372 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005373{
Eric Laurentfd477972013-10-25 18:10:40 -07005374 //FIXME: mStandby should be set to true by ThreadBase constructor
5375 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07005376 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005377}
5378
Eric Laurentbfb1b832013-01-07 09:53:42 -08005379void AudioFlinger::OffloadThread::threadLoop_exit()
5380{
5381 if (mFlushPending || mHwPaused) {
5382 // If a flush is pending or track was paused, just discard buffered data
5383 flushHw_l();
5384 } else {
5385 mMixerStatus = MIXER_DRAIN_ALL;
5386 threadLoop_drain();
5387 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005388 if (mUseAsyncWrite) {
5389 ALOG_ASSERT(mCallbackThread != 0);
5390 mCallbackThread->exit();
5391 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005392 PlaybackThread::threadLoop_exit();
5393}
5394
5395AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5396 Vector< sp<Track> > *tracksToRemove
5397)
5398{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005399 size_t count = mActiveTracks.size();
5400
5401 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005402 bool doHwPause = false;
5403 bool doHwResume = false;
5404
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005405 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07005406
Eric Laurentbfb1b832013-01-07 09:53:42 -08005407 // find out which tracks need to be processed
5408 for (size_t i = 0; i < count; i++) {
5409 sp<Track> t = mActiveTracks[i].promote();
5410 // The track died recently
5411 if (t == 0) {
5412 continue;
5413 }
5414 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005415#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08005416 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005417#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005418 // Only consider last track started for volume and mixer state control.
5419 // In theory an older track could underrun and restart after the new one starts
5420 // but as we only care about the transition phase between two tracks on a
5421 // direct output, it is not a problem to ignore the underrun case.
5422 sp<Track> l = mLatestActiveTrack.promote();
5423 bool last = l.get() == track;
5424
Haynes Mathew George7844f672014-01-15 12:32:55 -08005425 if (track->isInvalid()) {
5426 ALOGW("An invalidated track shouldn't be in active list");
5427 tracksToRemove->add(track);
5428 continue;
5429 }
5430
5431 if (track->mState == TrackBase::IDLE) {
5432 ALOGW("An idle track shouldn't be in active list");
5433 continue;
5434 }
5435
Eric Laurentbfb1b832013-01-07 09:53:42 -08005436 if (track->isPausing()) {
5437 track->setPaused();
5438 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005439 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005440 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005441 mHwPaused = true;
5442 }
5443 // If we were part way through writing the mixbuffer to
5444 // the HAL we must save this until we resume
5445 // BUG - this will be wrong if a different track is made active,
5446 // in that case we want to discard the pending data in the
5447 // mixbuffer and tell the client to present it again when the
5448 // track is resumed
5449 mPausedWriteLength = mCurrentWriteLength;
5450 mPausedBytesRemaining = mBytesRemaining;
5451 mBytesRemaining = 0; // stop writing
5452 }
5453 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005454 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005455 if (track->isStopping_1()) {
5456 track->mRetryCount = kMaxTrackStopRetriesOffload;
5457 } else {
5458 track->mRetryCount = kMaxTrackRetriesOffload;
5459 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08005460 track->flushAck();
5461 if (last) {
5462 mFlushPending = true;
5463 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005464 } else if (track->isResumePending()){
5465 track->resumeAck();
5466 if (last) {
5467 if (mPausedBytesRemaining) {
5468 // Need to continue write that was interrupted
5469 mCurrentWriteLength = mPausedWriteLength;
5470 mBytesRemaining = mPausedBytesRemaining;
5471 mPausedBytesRemaining = 0;
5472 }
5473 if (mHwPaused) {
5474 doHwResume = true;
5475 mHwPaused = false;
5476 // threadLoop_mix() will handle the case that we need to
5477 // resume an interrupted write
5478 }
5479 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005480 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005481
Eric Laurent3df841a2016-07-15 15:15:40 -07005482 mLeftVolFloat = mRightVolFloat = -1.0;
5483
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005484 // Do not handle new data in this iteration even if track->framesReady()
5485 mixerStatus = MIXER_TRACKS_ENABLED;
5486 }
5487 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005488 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005489 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005490 if (track->mFillingUpStatus == Track::FS_FILLED) {
5491 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005492 if (last) {
5493 // make sure processVolume_l() will apply new volume even if 0
5494 mLeftVolFloat = mRightVolFloat = -1.0;
5495 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005496 }
5497
5498 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005499 sp<Track> previousTrack = mPreviousTrack.promote();
5500 if (previousTrack != 0) {
5501 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005502 // Flush any data still being written from last track
5503 mBytesRemaining = 0;
5504 if (mPausedBytesRemaining) {
5505 // Last track was paused so we also need to flush saved
5506 // mixbuffer state and invalidate track so that it will
5507 // re-submit that unwritten data when it is next resumed
5508 mPausedBytesRemaining = 0;
5509 // Invalidate is a bit drastic - would be more efficient
5510 // to have a flag to tell client that some of the
5511 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005512 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005513 }
5514 // flush data already sent to the DSP if changing audio session as audio
5515 // comes from a different source. Also invalidate previous track to force a
5516 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005517 if (previousTrack->sessionId() != track->sessionId()) {
5518 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005519 }
5520 }
5521 }
5522 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005523 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07005524 if (track->isStopping_1()) {
5525 track->mRetryCount = kMaxTrackStopRetriesOffload;
5526 } else {
5527 track->mRetryCount = kMaxTrackRetriesOffload;
5528 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005529 mActiveTrack = t;
5530 mixerStatus = MIXER_TRACKS_READY;
5531 }
5532 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005533 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005534 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005535 if (--(track->mRetryCount) <= 0) {
5536 // Hardware buffer can hold a large amount of audio so we must
5537 // wait for all current track's data to drain before we say
5538 // that the track is stopped.
5539 if (mBytesRemaining == 0) {
5540 // Only start draining when all data in mixbuffer
5541 // has been written
5542 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5543 track->mState = TrackBase::STOPPING_2; // so presentation completes after
5544 // drain do not drain if no data was ever sent to HAL (mStandby == true)
5545 if (last && !mStandby) {
5546 // do not modify drain sequence if we are already draining. This happens
5547 // when resuming from pause after drain.
5548 if ((mDrainSequence & 1) == 0) {
5549 mSleepTimeUs = 0;
5550 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
5551 mixerStatus = MIXER_DRAIN_TRACK;
5552 mDrainSequence += 2;
5553 }
5554 if (mHwPaused) {
5555 // It is possible to move from PAUSED to STOPPING_1 without
5556 // a resume so we must ensure hardware is running
5557 doHwResume = true;
5558 mHwPaused = false;
5559 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005560 }
5561 }
Eric Laurente93cc032016-05-05 10:15:10 -07005562 } else if (last) {
5563 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
5564 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005565 }
5566 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005567 // Drain has completed or we are in standby, signal presentation complete
5568 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005569 track->mState = TrackBase::STOPPED;
5570 size_t audioHALFrames =
5571 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005572 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005573 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005574 track->presentationComplete(framesWritten, audioHALFrames);
5575 track->reset();
5576 tracksToRemove->add(track);
5577 }
5578 } else {
5579 // No buffers for this track. Give it a few chances to
5580 // fill a buffer, then remove it from active list.
5581 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07005582 bool running = false;
5583 if (mOutput->stream->get_presentation_position != nullptr) {
5584 uint64_t position = 0;
5585 struct timespec unused;
5586 // The running check restarts the retry counter at least once.
5587 int ret = mOutput->stream->get_presentation_position(
5588 mOutput->stream, &position, &unused);
5589 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
5590 running = true;
5591 mOffloadUnderrunPosition = position;
5592 }
5593 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
5594 (long long)position, (long long)mOffloadUnderrunPosition);
5595 }
5596 if (running) { // still running, give us more time.
5597 track->mRetryCount = kMaxTrackRetriesOffload;
5598 } else {
5599 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5600 track->name());
5601 tracksToRemove->add(track);
5602 // indicate to client process that the track was disabled because of underrun;
5603 // it will then automatically call start() when data is available
5604 track->disable();
5605 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005606 } else if (last){
5607 mixerStatus = MIXER_TRACKS_ENABLED;
5608 }
5609 }
5610 }
5611 // compute volume for this track
5612 processVolume_l(track, last);
5613 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005614
Eric Laurentea0fade2013-10-04 16:23:48 -07005615 // make sure the pause/flush/resume sequence is executed in the right order.
5616 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5617 // before flush and then resume HW. This can happen in case of pause/flush/resume
5618 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07005619 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07005620 mOutput->stream->pause(mOutput->stream);
5621 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005622 if (mFlushPending) {
5623 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005624 }
Eric Laurentfd477972013-10-25 18:10:40 -07005625 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07005626 mOutput->stream->resume(mOutput->stream);
5627 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005628
Eric Laurentbfb1b832013-01-07 09:53:42 -08005629 // remove all the tracks that need to be...
5630 removeTracks_l(*tracksToRemove);
5631
5632 return mixerStatus;
5633}
5634
Eric Laurentbfb1b832013-01-07 09:53:42 -08005635// must be called with thread mutex locked
5636bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5637{
Eric Laurent3b4529e2013-09-05 18:09:19 -07005638 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5639 mWriteAckSequence, mDrainSequence);
5640 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005641 return true;
5642 }
5643 return false;
5644}
5645
Eric Laurentbfb1b832013-01-07 09:53:42 -08005646bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5647{
5648 Mutex::Autolock _l(mLock);
5649 return waitingAsyncCallback_l();
5650}
5651
5652void AudioFlinger::OffloadThread::flushHw_l()
5653{
Eric Laurente659ef42014-09-29 13:06:46 -07005654 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005655 // Flush anything still waiting in the mixbuffer
5656 mCurrentWriteLength = 0;
5657 mBytesRemaining = 0;
5658 mPausedWriteLength = 0;
5659 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07005660 // reset bytes written count to reflect that DSP buffers are empty after flush.
5661 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07005662 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08005663
Eric Laurentbfb1b832013-01-07 09:53:42 -08005664 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005665 // discard any pending drain or write ack by incrementing sequence
5666 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5667 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005668 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005669 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5670 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005671 }
5672}
5673
Haynes Mathew George05317d22016-05-03 16:34:26 -07005674void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
5675{
5676 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07005677 if (PlaybackThread::invalidateTracks_l(streamType)) {
5678 mFlushPending = true;
5679 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07005680}
5681
Eric Laurentbfb1b832013-01-07 09:53:42 -08005682// ----------------------------------------------------------------------------
5683
Eric Laurent81784c32012-11-19 14:55:58 -08005684AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005685 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005686 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07005687 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08005688 mWaitTimeMs(UINT_MAX)
5689{
5690 addOutputTrack(mainThread);
5691}
5692
5693AudioFlinger::DuplicatingThread::~DuplicatingThread()
5694{
5695 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5696 mOutputTracks[i]->destroy();
5697 }
5698}
5699
5700void AudioFlinger::DuplicatingThread::threadLoop_mix()
5701{
5702 // mix buffers...
5703 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08005704 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08005705 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005706 if (mMixerBufferValid) {
5707 memset(mMixerBuffer, 0, mMixerBufferSize);
5708 } else {
5709 memset(mSinkBuffer, 0, mSinkBufferSize);
5710 }
Eric Laurent81784c32012-11-19 14:55:58 -08005711 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005712 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005713 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005714 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005715 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005716}
5717
5718void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5719{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005720 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005721 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005722 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005723 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005724 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005725 }
5726 } else if (mBytesWritten != 0) {
5727 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5728 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005729 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005730 } else {
5731 // flush remaining overflow buffers in output tracks
5732 writeFrames = 0;
5733 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005734 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005735 }
5736}
5737
Eric Laurentbfb1b832013-01-07 09:53:42 -08005738ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005739{
5740 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005741 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005742 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005743 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005744 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005745}
5746
5747void AudioFlinger::DuplicatingThread::threadLoop_standby()
5748{
5749 // DuplicatingThread implements standby by stopping all tracks
5750 for (size_t i = 0; i < outputTracks.size(); i++) {
5751 outputTracks[i]->stop();
5752 }
5753}
5754
5755void AudioFlinger::DuplicatingThread::saveOutputTracks()
5756{
5757 outputTracks = mOutputTracks;
5758}
5759
5760void AudioFlinger::DuplicatingThread::clearOutputTracks()
5761{
5762 outputTracks.clear();
5763}
5764
5765void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5766{
5767 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005768 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5769 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5770 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5771 const size_t frameCount =
5772 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5773 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5774 // from different OutputTracks and their associated MixerThreads (e.g. one may
5775 // nearly empty and the other may be dropping data).
5776
5777 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005778 this,
5779 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005780 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005781 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005782 frameCount,
5783 IPCThreadState::self()->getCallingUid());
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07005784 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
5785 if (status != NO_ERROR) {
5786 ALOGE("addOutputTrack() initCheck failed %d", status);
5787 return;
Eric Laurent81784c32012-11-19 14:55:58 -08005788 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07005789 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
5790 mOutputTracks.add(outputTrack);
5791 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
5792 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005793}
5794
5795void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5796{
5797 Mutex::Autolock _l(mLock);
5798 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5799 if (mOutputTracks[i]->thread() == thread) {
5800 mOutputTracks[i]->destroy();
5801 mOutputTracks.removeAt(i);
5802 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07005803 if (thread->getOutput() == mOutput) {
5804 mOutput = NULL;
5805 }
Eric Laurent81784c32012-11-19 14:55:58 -08005806 return;
5807 }
5808 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07005809 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005810}
5811
5812// caller must hold mLock
5813void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5814{
5815 mWaitTimeMs = UINT_MAX;
5816 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5817 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5818 if (strong != 0) {
5819 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5820 if (waitTimeMs < mWaitTimeMs) {
5821 mWaitTimeMs = waitTimeMs;
5822 }
5823 }
5824 }
5825}
5826
5827
5828bool AudioFlinger::DuplicatingThread::outputsReady(
5829 const SortedVector< sp<OutputTrack> > &outputTracks)
5830{
5831 for (size_t i = 0; i < outputTracks.size(); i++) {
5832 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5833 if (thread == 0) {
5834 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5835 outputTracks[i].get());
5836 return false;
5837 }
5838 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5839 // see note at standby() declaration
5840 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5841 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5842 thread.get());
5843 return false;
5844 }
5845 }
5846 return true;
5847}
5848
5849uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5850{
5851 return (mWaitTimeMs * 1000) / 2;
5852}
5853
5854void AudioFlinger::DuplicatingThread::cacheParameters_l()
5855{
5856 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5857 updateWaitTime_l();
5858
5859 MixerThread::cacheParameters_l();
5860}
5861
5862// ----------------------------------------------------------------------------
5863// Record
5864// ----------------------------------------------------------------------------
5865
5866AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5867 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005868 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005869 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07005870 audio_devices_t inDevice,
5871 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08005872#ifdef TEE_SINK
5873 , const sp<NBAIO_Sink>& teeSink
5874#endif
5875 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07005876 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005877 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005878 // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005879 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005880#ifdef TEE_SINK
5881 , mTeeSink(teeSink)
5882#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005883 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5884 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005885 // mFastCapture below
5886 , mFastCaptureFutex(0)
5887 // mInputSource
5888 // mPipeSink
5889 // mPipeSource
5890 , mPipeFramesP2(0)
5891 // mPipeMemory
5892 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005893 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005894{
Glenn Kastend7dca052015-03-05 16:05:54 -08005895 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5896 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08005897
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005898 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005899
5900 // create an NBAIO source for the HAL input stream, and negotiate
5901 mInputSource = new AudioStreamInSource(input->stream);
5902 size_t numCounterOffers = 0;
5903 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005904#if !LOG_NDEBUG
5905 ssize_t index =
5906#else
5907 (void)
5908#endif
5909 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005910 ALOG_ASSERT(index == 0);
5911
5912 // initialize fast capture depending on configuration
5913 bool initFastCapture;
5914 switch (kUseFastCapture) {
5915 case FastCapture_Never:
5916 initFastCapture = false;
5917 break;
5918 case FastCapture_Always:
5919 initFastCapture = true;
5920 break;
5921 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07005922 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005923 break;
5924 // case FastCapture_Dynamic:
5925 }
5926
5927 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07005928 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005929 NBAIO_Format format = mInputSource->format();
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005930 size_t pipeFramesP2 = roundup(mSampleRate / 25); // double-buffering of 20 ms each
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005931 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5932 void *pipeBuffer;
5933 const sp<MemoryDealer> roHeap(readOnlyHeap());
5934 sp<IMemory> pipeMemory;
5935 if ((roHeap == 0) ||
5936 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5937 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5938 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5939 goto failed;
5940 }
5941 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5942 memset(pipeBuffer, 0, pipeSize);
5943 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5944 const NBAIO_Format offers[1] = {format};
5945 size_t numCounterOffers = 0;
5946 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5947 ALOG_ASSERT(index == 0);
5948 mPipeSink = pipe;
5949 PipeReader *pipeReader = new PipeReader(*pipe);
5950 numCounterOffers = 0;
5951 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5952 ALOG_ASSERT(index == 0);
5953 mPipeSource = pipeReader;
5954 mPipeFramesP2 = pipeFramesP2;
5955 mPipeMemory = pipeMemory;
5956
5957 // create fast capture
5958 mFastCapture = new FastCapture();
5959 FastCaptureStateQueue *sq = mFastCapture->sq();
5960#ifdef STATE_QUEUE_DUMP
5961 // FIXME
5962#endif
5963 FastCaptureState *state = sq->begin();
5964 state->mCblk = NULL;
5965 state->mInputSource = mInputSource.get();
5966 state->mInputSourceGen++;
5967 state->mPipeSink = pipe;
5968 state->mPipeSinkGen++;
5969 state->mFrameCount = mFrameCount;
5970 state->mCommand = FastCaptureState::COLD_IDLE;
5971 // already done in constructor initialization list
5972 //mFastCaptureFutex = 0;
5973 state->mColdFutexAddr = &mFastCaptureFutex;
5974 state->mColdGen++;
5975 state->mDumpState = &mFastCaptureDumpState;
5976#ifdef TEE_SINK
5977 // FIXME
5978#endif
5979 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
5980 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
5981 sq->end();
5982 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5983
5984 // start the fast capture
5985 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
5986 pid_t tid = mFastCapture->getTid();
Glenn Kasten8379b722016-03-18 14:54:17 -07005987 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005988#ifdef AUDIO_WATCHDOG
5989 // FIXME
5990#endif
5991
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005992 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005993 }
5994failed: ;
5995
5996 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08005997}
5998
Eric Laurent81784c32012-11-19 14:55:58 -08005999AudioFlinger::RecordThread::~RecordThread()
6000{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006001 if (mFastCapture != 0) {
6002 FastCaptureStateQueue *sq = mFastCapture->sq();
6003 FastCaptureState *state = sq->begin();
6004 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6005 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6006 if (old == -1) {
6007 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6008 }
6009 }
6010 state->mCommand = FastCaptureState::EXIT;
6011 sq->end();
6012 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6013 mFastCapture->join();
6014 mFastCapture.clear();
6015 }
6016 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07006017 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07006018 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08006019}
6020
6021void AudioFlinger::RecordThread::onFirstRef()
6022{
Glenn Kastend7dca052015-03-05 16:05:54 -08006023 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08006024}
6025
Eric Laurent81784c32012-11-19 14:55:58 -08006026bool AudioFlinger::RecordThread::threadLoop()
6027{
Eric Laurent81784c32012-11-19 14:55:58 -08006028 nsecs_t lastWarning = 0;
6029
6030 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006031
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006032reacquire_wakelock:
6033 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08006034 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006035 {
6036 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006037 size_t size = mActiveTracks.size();
6038 activeTracksGen = mActiveTracksGen;
6039 if (size > 0) {
6040 // FIXME an arbitrary choice
6041 activeTrack = mActiveTracks[0];
6042 acquireWakeLock_l(activeTrack->uid());
6043 if (size > 1) {
6044 SortedVector<int> tmp;
6045 for (size_t i = 0; i < size; i++) {
6046 tmp.add(mActiveTracks[i]->uid());
6047 }
6048 updateWakeLockUids_l(tmp);
6049 }
6050 } else {
6051 acquireWakeLock_l(-1);
6052 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006053 }
6054
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006055 // used to request a deferred sleep, to be executed later while mutex is unlocked
6056 uint32_t sleepUs = 0;
6057
6058 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006059 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006060 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07006061
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006062 // activeTracks accumulates a copy of a subset of mActiveTracks
6063 Vector< sp<RecordTrack> > activeTracks;
6064
Glenn Kasten735f45f2014-08-18 15:51:59 -07006065 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006066 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07006067
Glenn Kasten735f45f2014-08-18 15:51:59 -07006068 // reference to a fast track which is about to be removed
6069 sp<RecordTrack> fastTrackToRemove;
6070
Eric Laurent81784c32012-11-19 14:55:58 -08006071 { // scope for mLock
6072 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08006073
Eric Laurent021cf962014-05-13 10:18:14 -07006074 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006075
Eric Laurent000a4192014-01-29 15:17:32 -08006076 // check exitPending here because checkForNewParameters_l() and
6077 // checkForNewParameters_l() can temporarily release mLock
6078 if (exitPending()) {
6079 break;
6080 }
6081
Eric Laurent5c25d562016-07-13 17:17:45 -07006082 // sleep with mutex unlocked
6083 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07006084 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07006085 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
6086 ATRACE_END();
6087 sleepUs = 0;
6088 continue;
6089 }
6090
Glenn Kasten2b806402013-11-20 16:37:38 -08006091 // if no active track(s), then standby and release wakelock
6092 size_t size = mActiveTracks.size();
6093 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07006094 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006095 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08006096 releaseWakeLock_l();
6097 ALOGV("RecordThread: loop stopping");
6098 // go to sleep
6099 mWaitWorkCV.wait(mLock);
6100 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006101 goto reacquire_wakelock;
6102 }
6103
Glenn Kasten2b806402013-11-20 16:37:38 -08006104 if (mActiveTracksGen != activeTracksGen) {
6105 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006106 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08006107 for (size_t i = 0; i < size; i++) {
6108 tmp.add(mActiveTracks[i]->uid());
6109 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006110 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08006111 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006112
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006113 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07006114 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006115 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07006116
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006117 activeTrack = mActiveTracks[i];
6118 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07006119 if (activeTrack->isFastTrack()) {
6120 ALOG_ASSERT(fastTrackToRemove == 0);
6121 fastTrackToRemove = activeTrack;
6122 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006123 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08006124 mActiveTracks.remove(activeTrack);
6125 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006126 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07006127 continue;
6128 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006129
6130 TrackBase::track_state activeTrackState = activeTrack->mState;
6131 switch (activeTrackState) {
6132
6133 case TrackBase::PAUSING:
6134 mActiveTracks.remove(activeTrack);
6135 mActiveTracksGen++;
6136 doBroadcast = true;
6137 size--;
6138 continue;
6139
6140 case TrackBase::STARTING_1:
6141 sleepUs = 10000;
6142 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07006143 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006144 continue;
6145
6146 case TrackBase::STARTING_2:
6147 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006148 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07006149 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07006150 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006151 break;
6152
6153 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07006154 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006155 break;
6156
6157 case TrackBase::IDLE:
6158 i++;
6159 continue;
6160
6161 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08006162 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07006163 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006164
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006165 activeTracks.add(activeTrack);
6166 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07006167
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006168 if (activeTrack->isFastTrack()) {
6169 ALOG_ASSERT(!mFastTrackAvail);
6170 ALOG_ASSERT(fastTrack == 0);
6171 fastTrack = activeTrack;
6172 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006173 }
Eric Laurent5c25d562016-07-13 17:17:45 -07006174
6175 if (allStopped) {
6176 standbyIfNotAlreadyInStandby();
6177 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006178 if (doBroadcast) {
6179 mStartStopCond.broadcast();
6180 }
6181
6182 // sleep if there are no active tracks to process
6183 if (activeTracks.size() == 0) {
6184 if (sleepUs == 0) {
6185 sleepUs = kRecordThreadSleepUs;
6186 }
6187 continue;
6188 }
6189 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07006190
Eric Laurent81784c32012-11-19 14:55:58 -08006191 lockEffectChains_l(effectChains);
6192 }
6193
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006194 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07006195
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006196 size_t size = effectChains.size();
6197 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006198 // thread mutex is not locked, but effect chain is locked
6199 effectChains[i]->process_l();
6200 }
6201
Glenn Kasten735f45f2014-08-18 15:51:59 -07006202 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006203 if (mFastCapture != 0) {
6204 FastCaptureStateQueue *sq = mFastCapture->sq();
6205 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07006206 bool didModify = false;
6207 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006208 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
6209 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
6210 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6211 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6212 if (old == -1) {
6213 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6214 }
6215 }
6216 state->mCommand = FastCaptureState::READ_WRITE;
6217#if 0 // FIXME
6218 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08006219 FastThreadDumpState::kSamplingNforLowRamDevice :
6220 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006221#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07006222 didModify = true;
6223 }
6224 audio_track_cblk_t *cblkOld = state->mCblk;
6225 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
6226 if (cblkNew != cblkOld) {
6227 state->mCblk = cblkNew;
6228 // block until acked if removing a fast track
6229 if (cblkOld != NULL) {
6230 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
6231 }
6232 didModify = true;
6233 }
6234 sq->end(didModify);
6235 if (didModify) {
6236 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006237#if 0
6238 if (kUseFastCapture == FastCapture_Dynamic) {
6239 mNormalSource = mPipeSource;
6240 }
6241#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006242 }
6243 }
6244
Glenn Kasten735f45f2014-08-18 15:51:59 -07006245 // now run the fast track destructor with thread mutex unlocked
6246 fastTrackToRemove.clear();
6247
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006248 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
6249 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
6250 // slow, then this RecordThread will overrun by not calling HAL read often enough.
6251 // If destination is non-contiguous, first read past the nominal end of buffer, then
6252 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006253
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006254 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006255 ssize_t framesRead;
6256
6257 // If an NBAIO source is present, use it to read the normal capture's data
6258 if (mPipeSource != 0) {
6259 size_t framesToRead = mBufferSize / mFrameSize;
Andy Hung57446612015-04-19 23:56:46 -07006260 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
Glenn Kastend79072e2016-01-06 08:41:20 -08006261 framesToRead);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006262 if (framesRead == 0) {
6263 // since pipe is non-blocking, simulate blocking input
6264 sleepUs = (framesToRead * 1000000LL) / mSampleRate;
6265 }
6266 // otherwise use the HAL / AudioStreamIn directly
6267 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07006268 ATRACE_BEGIN("read");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006269 ssize_t bytesRead = mInput->stream->read(mInput->stream,
Andy Hung57446612015-04-19 23:56:46 -07006270 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize);
Glenn Kastenec6a7032016-03-14 07:40:23 -07006271 ATRACE_END();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006272 if (bytesRead < 0) {
6273 framesRead = bytesRead;
6274 } else {
6275 framesRead = bytesRead / mFrameSize;
6276 }
6277 }
6278
Andy Hung3f0c9022016-01-15 17:49:46 -08006279 // Update server timestamp with server stats
6280 // systemTime() is optional if the hardware supports timestamps.
6281 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
6282 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6283
6284 // Update server timestamp with kernel stats
Andy Hung69ce44d2016-07-18 12:14:25 -07006285 if (mInput->stream->get_capture_position != nullptr
6286 && mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08006287 int64_t position, time;
6288 int ret = mInput->stream->get_capture_position(mInput->stream, &position, &time);
6289 if (ret == NO_ERROR) {
6290 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
6291 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
6292 // Note: In general record buffers should tend to be empty in
6293 // a properly running pipeline.
6294 //
6295 // Also, it is not advantageous to call get_presentation_position during the read
6296 // as the read obtains a lock, preventing the timestamp call from executing.
6297 }
6298 }
6299 // Use this to track timestamp information
6300 // ALOGD("%s", mTimestamp.toString().c_str());
6301
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006302 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006303 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006304 // Force input into standby so that it tries to recover at next read attempt
6305 inputStandBy();
6306 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006307 }
6308 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006309 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006310 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006311 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006312
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006313 if (mTeeSink != 0) {
Andy Hung57446612015-04-19 23:56:46 -07006314 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006315 }
6316 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006317 {
6318 size_t part1 = mRsmpInFramesP2 - rear;
6319 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07006320 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006321 (framesRead - part1) * mFrameSize);
6322 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006323 }
6324 rear = mRsmpInRear += framesRead;
6325
6326 size = activeTracks.size();
6327 // loop over each active track
6328 for (size_t i = 0; i < size; i++) {
6329 activeTrack = activeTracks[i];
6330
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006331 // skip fast tracks, as those are handled directly by FastCapture
6332 if (activeTrack->isFastTrack()) {
6333 continue;
6334 }
6335
Andy Hung73c02e42015-03-29 01:13:58 -07006336 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07006337 // TODO: Update the activeTrack buffer converter in case of reconfigure.
6338
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006339 enum {
6340 OVERRUN_UNKNOWN,
6341 OVERRUN_TRUE,
6342 OVERRUN_FALSE
6343 } overrun = OVERRUN_UNKNOWN;
6344
6345 // loop over getNextBuffer to handle circular sink
6346 for (;;) {
6347
6348 activeTrack->mSink.frameCount = ~0;
6349 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
6350 size_t framesOut = activeTrack->mSink.frameCount;
6351 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
6352
Andy Hung73c02e42015-03-29 01:13:58 -07006353 // check available frames and handle overrun conditions
6354 // if the record track isn't draining fast enough.
6355 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006356 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07006357 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
6358 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006359 overrun = OVERRUN_TRUE;
6360 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006361 if (framesOut == 0 || framesIn == 0) {
6362 break;
6363 }
6364
Andy Hung6770c6f2015-04-07 13:43:36 -07006365 // Don't allow framesOut to be larger than what is possible with resampling
6366 // from framesIn.
6367 // This isn't strictly necessary but helps limit buffer resizing in
6368 // RecordBufferConverter. TODO: remove when no longer needed.
6369 framesOut = min(framesOut,
6370 destinationFramesPossible(
6371 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07006372 // process frames from the RecordThread buffer provider to the RecordTrack buffer
6373 framesOut = activeTrack->mRecordBufferConverter->convert(
6374 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006375
6376 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
6377 overrun = OVERRUN_FALSE;
6378 }
6379
6380 if (activeTrack->mFramesToDrop == 0) {
6381 if (framesOut > 0) {
6382 activeTrack->mSink.frameCount = framesOut;
6383 activeTrack->releaseBuffer(&activeTrack->mSink);
6384 }
6385 } else {
6386 // FIXME could do a partial drop of framesOut
6387 if (activeTrack->mFramesToDrop > 0) {
6388 activeTrack->mFramesToDrop -= framesOut;
6389 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006390 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006391 }
6392 } else {
6393 activeTrack->mFramesToDrop += framesOut;
6394 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
6395 activeTrack->mSyncStartEvent->isCancelled()) {
6396 ALOGW("Synced record %s, session %d, trigger session %d",
6397 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
6398 activeTrack->sessionId(),
6399 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08006400 activeTrack->mSyncStartEvent->triggerSession() :
6401 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006402 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006403 }
6404 }
6405 }
6406
6407 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006408 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006409 }
6410 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006411
6412 switch (overrun) {
6413 case OVERRUN_TRUE:
6414 // client isn't retrieving buffers fast enough
6415 if (!activeTrack->setOverflow()) {
6416 nsecs_t now = systemTime();
6417 // FIXME should lastWarning per track?
6418 if ((now - lastWarning) > kWarningThrottleNs) {
6419 ALOGW("RecordThread: buffer overflow");
6420 lastWarning = now;
6421 }
6422 }
6423 break;
6424 case OVERRUN_FALSE:
6425 activeTrack->clearOverflow();
6426 break;
6427 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006428 break;
6429 }
6430
Andy Hung3f0c9022016-01-15 17:49:46 -08006431 // update frame information and push timestamp out
6432 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08006433 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08006434 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
6435 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006436 }
6437
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006438unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08006439 // enable changes in effect chain
6440 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006441 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08006442 }
6443
Glenn Kasten93e471f2013-08-19 08:40:07 -07006444 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08006445
6446 {
6447 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07006448 for (size_t i = 0; i < mTracks.size(); i++) {
6449 sp<RecordTrack> track = mTracks[i];
6450 track->invalidate();
6451 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006452 mActiveTracks.clear();
6453 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08006454 mStartStopCond.broadcast();
6455 }
6456
6457 releaseWakeLock();
6458
6459 ALOGV("RecordThread %p exiting", this);
6460 return false;
6461}
6462
Glenn Kasten93e471f2013-08-19 08:40:07 -07006463void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08006464{
6465 if (!mStandby) {
6466 inputStandBy();
6467 mStandby = true;
6468 }
6469}
6470
6471void AudioFlinger::RecordThread::inputStandBy()
6472{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006473 // Idle the fast capture if it's currently running
6474 if (mFastCapture != 0) {
6475 FastCaptureStateQueue *sq = mFastCapture->sq();
6476 FastCaptureState *state = sq->begin();
6477 if (!(state->mCommand & FastCaptureState::IDLE)) {
6478 state->mCommand = FastCaptureState::COLD_IDLE;
6479 state->mColdFutexAddr = &mFastCaptureFutex;
6480 state->mColdGen++;
6481 mFastCaptureFutex = 0;
6482 sq->end();
6483 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
6484 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
6485#if 0
6486 if (kUseFastCapture == FastCapture_Dynamic) {
6487 // FIXME
6488 }
6489#endif
6490#ifdef AUDIO_WATCHDOG
6491 // FIXME
6492#endif
6493 } else {
6494 sq->end(false /*didModify*/);
6495 }
6496 }
Eric Laurent81784c32012-11-19 14:55:58 -08006497 mInput->stream->common.standby(&mInput->stream->common);
Andy Hungad6d52d2016-07-18 13:42:03 -07006498
6499 // If going into standby, flush the pipe source.
6500 if (mPipeSource.get() != nullptr) {
6501 const ssize_t flushed = mPipeSource->flush();
6502 if (flushed > 0) {
6503 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
6504 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
6505 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6506 }
6507 }
Eric Laurent81784c32012-11-19 14:55:58 -08006508}
6509
Glenn Kasten05997e22014-03-13 15:08:33 -07006510// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07006511sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08006512 const sp<AudioFlinger::Client>& client,
6513 uint32_t sampleRate,
6514 audio_format_t format,
6515 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08006516 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08006517 audio_session_t sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07006518 size_t *notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006519 int uid,
Eric Laurent05067782016-06-01 18:27:28 -07006520 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08006521 pid_t tid,
6522 status_t *status)
6523{
Glenn Kasten74935e42013-12-19 08:56:45 -08006524 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08006525 sp<RecordTrack> track;
6526 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07006527 audio_input_flags_t inputFlags = mInput->flags;
6528
6529 // special case for FAST flag considered OK if fast capture is present
6530 if (hasFastCapture()) {
6531 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
6532 }
6533
6534 // Check if requested flags are compatible with output stream flags
6535 if ((*flags & inputFlags) != *flags) {
6536 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
6537 " input flags (%08x)",
6538 *flags, inputFlags);
6539 *flags = (audio_input_flags_t)(*flags & inputFlags);
6540 }
Eric Laurent81784c32012-11-19 14:55:58 -08006541
Glenn Kasten90e58b12013-07-31 16:16:02 -07006542 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07006543 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006544 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07006545 // we formerly checked for a callback handler (non-0 tid),
6546 // but that is no longer required for TRANSFER_OBTAIN mode
6547 //
Glenn Kasten74105912014-07-03 12:28:53 -07006548 // frame count is not specified, or is exactly the pipe depth
6549 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006550 // PCM data
6551 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006552 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006553 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006554 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006555 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006556 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07006557 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006558 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006559 hasFastCapture() &&
6560 // there are sufficient fast track slots available
6561 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07006562 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07006563 // check compatibility with audio effects.
6564 Mutex::Autolock _l(mLock);
6565 // Do not accept FAST flag if the session has software effects
6566 sp<EffectChain> chain = getEffectChain_l(sessionId);
6567 if (chain != 0) {
Eric Laurent122f7e72016-06-29 11:53:29 -07006568 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_RAW) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07006569 "AUDIO_INPUT_FLAG_RAW denied: effect present on session");
6570 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_RAW);
6571 if (chain->hasSoftwareEffect()) {
6572 ALOGV("AUDIO_INPUT_FLAG_FAST denied: software effect present on session");
6573 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
6574 }
6575 }
Eric Laurent122f7e72016-06-29 11:53:29 -07006576 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07006577 "AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
6578 frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006579 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006580 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
Glenn Kasten74105912014-07-03 12:28:53 -07006581 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006582 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07006583 frameCount, mFrameCount, mPipeFramesP2,
6584 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
6585 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07006586 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07006587 }
6588 }
6589
6590 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07006591 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07006592 // fast track: frame count is exactly the pipe depth
6593 frameCount = mPipeFramesP2;
6594 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
6595 *notificationFrames = mFrameCount;
6596 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006597 // not fast track: max notification period is resampled equivalent of one HAL buffer time
6598 // or 20 ms if there is a fast capture
6599 // TODO This could be a roundupRatio inline, and const
6600 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
6601 * sampleRate + mSampleRate - 1) / mSampleRate;
6602 // minimum number of notification periods is at least kMinNotifications,
6603 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
6604 static const size_t kMinNotifications = 3;
6605 static const uint32_t kMinMs = 30;
6606 // TODO This could be a roundupRatio inline
6607 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
6608 // TODO This could be a roundupRatio inline
6609 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
6610 maxNotificationFrames;
6611 const size_t minFrameCount = maxNotificationFrames *
6612 max(kMinNotifications, minNotificationsByMs);
6613 frameCount = max(frameCount, minFrameCount);
6614 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
6615 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07006616 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07006617 }
Glenn Kasten74935e42013-12-19 08:56:45 -08006618 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07006619
Glenn Kasten15e57982013-09-24 11:52:37 -07006620 lStatus = initCheck();
6621 if (lStatus != NO_ERROR) {
6622 ALOGE("createRecordTrack_l() audio driver not initialized");
6623 goto Exit;
6624 }
Eric Laurent81784c32012-11-19 14:55:58 -08006625
6626 { // scope for mLock
6627 Mutex::Autolock _l(mLock);
6628
6629 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07006630 format, channelMask, frameCount, NULL, sessionId, uid,
6631 *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08006632
Glenn Kasten03003332013-08-06 15:40:54 -07006633 lStatus = track->initCheck();
6634 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07006635 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08006636 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08006637 goto Exit;
6638 }
6639 mTracks.add(track);
6640
6641 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6642 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6643 mAudioFlinger->btNrecIsOff();
6644 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6645 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006646
Eric Laurent05067782016-06-01 18:27:28 -07006647 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006648 pid_t callingPid = IPCThreadState::self()->getCallingPid();
6649 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
6650 // so ask activity manager to do this on our behalf
6651 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
6652 }
Eric Laurent81784c32012-11-19 14:55:58 -08006653 }
Glenn Kasten05997e22014-03-13 15:08:33 -07006654
Eric Laurent81784c32012-11-19 14:55:58 -08006655 lStatus = NO_ERROR;
6656
6657Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07006658 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08006659 return track;
6660}
6661
6662status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6663 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08006664 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08006665{
6666 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6667 sp<ThreadBase> strongMe = this;
6668 status_t status = NO_ERROR;
6669
6670 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006671 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006672 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006673 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08006674 triggerSession,
6675 recordTrack->sessionId(),
6676 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006677 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08006678 // Sync event can be cancelled by the trigger session if the track is not in a
6679 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006680 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006681 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006682 } else {
6683 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006684 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006685 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08006686 }
6687 }
6688
6689 {
Glenn Kasten47c20702013-08-13 15:37:35 -07006690 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08006691 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006692 if (mActiveTracks.indexOf(recordTrack) >= 0) {
6693 if (recordTrack->mState == TrackBase::PAUSING) {
6694 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006695 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006696 } else {
6697 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08006698 }
6699 return status;
6700 }
6701
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006702 // TODO consider other ways of handling this, such as changing the state to :STARTING and
6703 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6704 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006705 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08006706 mActiveTracks.add(recordTrack);
6707 mActiveTracksGen++;
Eric Laurent83b88082014-06-20 18:31:16 -07006708 status_t status = NO_ERROR;
6709 if (recordTrack->isExternalTrack()) {
6710 mLock.unlock();
Glenn Kastend848eb42016-03-08 13:42:11 -08006711 status = AudioSystem::startInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006712 mLock.lock();
6713 // FIXME should verify that recordTrack is still in mActiveTracks
6714 if (status != NO_ERROR) {
6715 mActiveTracks.remove(recordTrack);
6716 mActiveTracksGen++;
6717 recordTrack->clearSyncStartEvent();
6718 ALOGV("RecordThread::start error %d", status);
6719 return status;
6720 }
Eric Laurent81784c32012-11-19 14:55:58 -08006721 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006722 // Catch up with current buffer indices if thread is already running.
6723 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
6724 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6725 // see previously buffered data before it called start(), but with greater risk of overrun.
6726
Andy Hung73c02e42015-03-29 01:13:58 -07006727 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07006728 // clear any converter state as new data will be discontinuous
6729 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006730 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08006731 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08006732 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08006733 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006734 ALOGV("Record failed to start");
6735 status = BAD_VALUE;
6736 goto startError;
6737 }
Eric Laurent81784c32012-11-19 14:55:58 -08006738 return status;
6739 }
Glenn Kasten7c027242012-12-26 14:43:16 -08006740
Eric Laurent81784c32012-11-19 14:55:58 -08006741startError:
Eric Laurent83b88082014-06-20 18:31:16 -07006742 if (recordTrack->isExternalTrack()) {
Glenn Kastend848eb42016-03-08 13:42:11 -08006743 AudioSystem::stopInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006744 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006745 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006746 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08006747 return status;
6748}
6749
Eric Laurent81784c32012-11-19 14:55:58 -08006750void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6751{
6752 sp<SyncEvent> strongEvent = event.promote();
6753
6754 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08006755 sp<RefBase> ptr = strongEvent->cookie().promote();
6756 if (ptr != 0) {
6757 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6758 recordTrack->handleSyncStartEvent(strongEvent);
6759 }
Eric Laurent81784c32012-11-19 14:55:58 -08006760 }
6761}
6762
Glenn Kastena8356f62013-07-25 14:37:52 -07006763bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08006764 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07006765 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006766 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08006767 return false;
6768 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006769 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006770 recordTrack->mState = TrackBase::PAUSING;
Eric Laurent5c25d562016-07-13 17:17:45 -07006771 // signal thread to stop
6772 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08006773 // do not wait for mStartStopCond if exiting
6774 if (exitPending()) {
6775 return true;
6776 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006777 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08006778 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006779 // if we have been restarted, recordTrack is in mActiveTracks here
6780 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006781 ALOGV("Record stopped OK");
6782 return true;
6783 }
6784 return false;
6785}
6786
Glenn Kasten0f11b512014-01-31 16:18:54 -08006787bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08006788{
6789 return false;
6790}
6791
Glenn Kasten0f11b512014-01-31 16:18:54 -08006792status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006793{
6794#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6795 if (!isValidSyncEvent(event)) {
6796 return BAD_VALUE;
6797 }
6798
Glenn Kastend848eb42016-03-08 13:42:11 -08006799 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08006800 status_t ret = NAME_NOT_FOUND;
6801
6802 Mutex::Autolock _l(mLock);
6803
6804 for (size_t i = 0; i < mTracks.size(); i++) {
6805 sp<RecordTrack> track = mTracks[i];
6806 if (eventSession == track->sessionId()) {
6807 (void) track->setSyncEvent(event);
6808 ret = NO_ERROR;
6809 }
6810 }
6811 return ret;
6812#else
6813 return BAD_VALUE;
6814#endif
6815}
6816
6817// destroyTrack_l() must be called with ThreadBase::mLock held
6818void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6819{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006820 track->terminate();
6821 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006822 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006823 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006824 removeTrack_l(track);
6825 }
6826}
6827
6828void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6829{
6830 mTracks.remove(track);
6831 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006832 if (track->isFastTrack()) {
6833 ALOG_ASSERT(!mFastTrackAvail);
6834 mFastTrackAvail = true;
6835 }
Eric Laurent81784c32012-11-19 14:55:58 -08006836}
6837
6838void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6839{
6840 dumpInternals(fd, args);
6841 dumpTracks(fd, args);
6842 dumpEffectChains(fd, args);
6843}
6844
6845void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6846{
Elliott Hughes87cebad2014-05-22 10:14:43 -07006847 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08006848
Glenn Kasten44182c22015-03-05 17:12:23 -08006849 dumpBase(fd, args);
6850
6851 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006852 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006853 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006854 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006855 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08006856
Glenn Kasten2f90c512015-12-02 11:40:09 -08006857 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
6858 // while we are dumping it. It may be inconsistent, but it won't mutate!
6859 // This is a large object so we place it on the heap.
6860 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
6861 const FastCaptureDumpState *copy = new FastCaptureDumpState(mFastCaptureDumpState);
6862 copy->dump(fd);
6863 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08006864}
6865
Glenn Kasten0f11b512014-01-31 16:18:54 -08006866void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006867{
6868 const size_t SIZE = 256;
6869 char buffer[SIZE];
6870 String8 result;
6871
Marco Nelissenb2208842014-02-07 14:00:50 -08006872 size_t numtracks = mTracks.size();
6873 size_t numactive = mActiveTracks.size();
6874 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006875 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006876 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006877 dprintf(fd, " of which %zu are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006878 RecordTrack::appendDumpHeader(result);
6879 for (size_t i = 0; i < numtracks ; ++i) {
6880 sp<RecordTrack> track = mTracks[i];
6881 if (track != 0) {
6882 bool active = mActiveTracks.indexOf(track) >= 0;
6883 if (active) {
6884 numactiveseen++;
6885 }
6886 track->dump(buffer, SIZE, active);
6887 result.append(buffer);
6888 }
Eric Laurent81784c32012-11-19 14:55:58 -08006889 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006890 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006891 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006892 }
6893
Marco Nelissenb2208842014-02-07 14:00:50 -08006894 if (numactiveseen != numactive) {
6895 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6896 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006897 result.append(buffer);
6898 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006899 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006900 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006901 if (mTracks.indexOf(track) < 0) {
6902 track->dump(buffer, SIZE, true);
6903 result.append(buffer);
6904 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006905 }
Eric Laurent81784c32012-11-19 14:55:58 -08006906
6907 }
6908 write(fd, result.string(), result.size());
6909}
6910
Andy Hung73c02e42015-03-29 01:13:58 -07006911
6912void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
6913{
6914 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6915 RecordThread *recordThread = (RecordThread *) threadBase.get();
6916 mRsmpInFront = recordThread->mRsmpInRear;
6917 mRsmpInUnrel = 0;
6918}
6919
6920void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
6921 size_t *framesAvailable, bool *hasOverrun)
6922{
6923 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6924 RecordThread *recordThread = (RecordThread *) threadBase.get();
6925 const int32_t rear = recordThread->mRsmpInRear;
6926 const int32_t front = mRsmpInFront;
6927 const ssize_t filled = rear - front;
6928
6929 size_t framesIn;
6930 bool overrun = false;
6931 if (filled < 0) {
6932 // should not happen, but treat like a massive overrun and re-sync
6933 framesIn = 0;
6934 mRsmpInFront = rear;
6935 overrun = true;
6936 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
6937 framesIn = (size_t) filled;
6938 } else {
6939 // client is not keeping up with server, but give it latest data
6940 framesIn = recordThread->mRsmpInFrames;
6941 mRsmpInFront = /* front = */ rear - framesIn;
6942 overrun = true;
6943 }
6944 if (framesAvailable != NULL) {
6945 *framesAvailable = framesIn;
6946 }
6947 if (hasOverrun != NULL) {
6948 *hasOverrun = overrun;
6949 }
6950}
6951
Eric Laurent81784c32012-11-19 14:55:58 -08006952// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006953status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08006954 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006955{
Andy Hung73c02e42015-03-29 01:13:58 -07006956 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006957 if (threadBase == 0) {
6958 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006959 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006960 return NOT_ENOUGH_DATA;
6961 }
6962 RecordThread *recordThread = (RecordThread *) threadBase.get();
6963 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07006964 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07006965 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006966 // FIXME should not be P2 (don't want to increase latency)
6967 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006968 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07006969 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006970 front &= recordThread->mRsmpInFramesP2 - 1;
6971 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07006972 if (part1 > (size_t) filled) {
6973 part1 = filled;
6974 }
6975 size_t ask = buffer->frameCount;
6976 ALOG_ASSERT(ask > 0);
6977 if (part1 > ask) {
6978 part1 = ask;
6979 }
6980 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07006981 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07006982 buffer->raw = NULL;
6983 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07006984 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07006985 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08006986 }
6987
Andy Hung57446612015-04-19 23:56:46 -07006988 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07006989 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07006990 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08006991 return NO_ERROR;
6992}
6993
6994// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006995void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
6996 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006997{
Glenn Kasten85948432013-08-19 12:09:05 -07006998 size_t stepCount = buffer->frameCount;
6999 if (stepCount == 0) {
7000 return;
7001 }
Andy Hung73c02e42015-03-29 01:13:58 -07007002 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
7003 mRsmpInUnrel -= stepCount;
7004 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07007005 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08007006 buffer->frameCount = 0;
7007}
7008
Andy Hung97a893e2015-03-29 01:03:07 -07007009AudioFlinger::RecordThread::RecordBufferConverter::RecordBufferConverter(
7010 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
7011 uint32_t srcSampleRate,
7012 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
7013 uint32_t dstSampleRate) :
7014 mSrcChannelMask(AUDIO_CHANNEL_INVALID), // updateParameters will set following vars
7015 // mSrcFormat
7016 // mSrcSampleRate
7017 // mDstChannelMask
7018 // mDstFormat
7019 // mDstSampleRate
7020 // mSrcChannelCount
7021 // mDstChannelCount
7022 // mDstFrameSize
7023 mBuf(NULL), mBufFrames(0), mBufFrameSize(0),
Andy Hungd330ee42015-04-20 13:23:41 -07007024 mResampler(NULL),
7025 mIsLegacyDownmix(false),
7026 mIsLegacyUpmix(false),
7027 mRequiresFloat(false),
7028 mInputConverterProvider(NULL)
Andy Hung97a893e2015-03-29 01:03:07 -07007029{
7030 (void)updateParameters(srcChannelMask, srcFormat, srcSampleRate,
7031 dstChannelMask, dstFormat, dstSampleRate);
7032}
7033
7034AudioFlinger::RecordThread::RecordBufferConverter::~RecordBufferConverter() {
7035 free(mBuf);
7036 delete mResampler;
Andy Hungd330ee42015-04-20 13:23:41 -07007037 delete mInputConverterProvider;
Andy Hung97a893e2015-03-29 01:03:07 -07007038}
7039
7040size_t AudioFlinger::RecordThread::RecordBufferConverter::convert(void *dst,
7041 AudioBufferProvider *provider, size_t frames)
7042{
Andy Hungd330ee42015-04-20 13:23:41 -07007043 if (mInputConverterProvider != NULL) {
7044 mInputConverterProvider->setBufferProvider(provider);
7045 provider = mInputConverterProvider;
7046 }
7047
7048 if (mResampler == NULL) {
Andy Hung97a893e2015-03-29 01:03:07 -07007049 ALOGVV("NO RESAMPLING sampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
7050 mSrcSampleRate, mSrcFormat, mDstFormat);
7051
7052 AudioBufferProvider::Buffer buffer;
7053 for (size_t i = frames; i > 0; ) {
7054 buffer.frameCount = i;
Glenn Kastend79072e2016-01-06 08:41:20 -08007055 status_t status = provider->getNextBuffer(&buffer);
Andy Hung97a893e2015-03-29 01:03:07 -07007056 if (status != OK || buffer.frameCount == 0) {
7057 frames -= i; // cannot fill request.
7058 break;
7059 }
Andy Hungd330ee42015-04-20 13:23:41 -07007060 // format convert to destination buffer
7061 convertNoResampler(dst, buffer.raw, buffer.frameCount);
Andy Hung97a893e2015-03-29 01:03:07 -07007062
7063 dst = (int8_t*)dst + buffer.frameCount * mDstFrameSize;
7064 i -= buffer.frameCount;
7065 provider->releaseBuffer(&buffer);
7066 }
7067 } else {
7068 ALOGVV("RESAMPLING mSrcSampleRate:%u mDstSampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
7069 mSrcSampleRate, mDstSampleRate, mSrcFormat, mDstFormat);
7070
Andy Hungd330ee42015-04-20 13:23:41 -07007071 // reallocate buffer if needed
7072 if (mBufFrameSize != 0 && mBufFrames < frames) {
7073 free(mBuf);
7074 mBufFrames = frames;
7075 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
7076 }
Andy Hung97a893e2015-03-29 01:03:07 -07007077 // resampler accumulates, but we only have one source track
Andy Hungd330ee42015-04-20 13:23:41 -07007078 memset(mBuf, 0, frames * mBufFrameSize);
7079 frames = mResampler->resample((int32_t*)mBuf, frames, provider);
7080 // format convert to destination buffer
7081 convertResampler(dst, mBuf, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07007082 }
7083 return frames;
7084}
7085
7086status_t AudioFlinger::RecordThread::RecordBufferConverter::updateParameters(
7087 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
7088 uint32_t srcSampleRate,
7089 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
7090 uint32_t dstSampleRate)
7091{
7092 // quick evaluation if there is any change.
7093 if (mSrcFormat == srcFormat
7094 && mSrcChannelMask == srcChannelMask
7095 && mSrcSampleRate == srcSampleRate
7096 && mDstFormat == dstFormat
7097 && mDstChannelMask == dstChannelMask
7098 && mDstSampleRate == dstSampleRate) {
7099 return NO_ERROR;
7100 }
7101
Andy Hungdb4c0312015-05-06 08:46:52 -07007102 ALOGV("RecordBufferConverter updateParameters srcMask:%#x dstMask:%#x"
7103 " srcFormat:%#x dstFormat:%#x srcRate:%u dstRate:%u",
7104 srcChannelMask, dstChannelMask, srcFormat, dstFormat, srcSampleRate, dstSampleRate);
Andy Hung97a893e2015-03-29 01:03:07 -07007105 const bool valid =
7106 audio_is_input_channel(srcChannelMask)
7107 && audio_is_input_channel(dstChannelMask)
7108 && audio_is_valid_format(srcFormat) && audio_is_linear_pcm(srcFormat)
7109 && audio_is_valid_format(dstFormat) && audio_is_linear_pcm(dstFormat)
7110 && (srcSampleRate <= dstSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX)
7111 ; // no upsampling checks for now
7112 if (!valid) {
7113 return BAD_VALUE;
7114 }
7115
7116 mSrcFormat = srcFormat;
7117 mSrcChannelMask = srcChannelMask;
7118 mSrcSampleRate = srcSampleRate;
7119 mDstFormat = dstFormat;
7120 mDstChannelMask = dstChannelMask;
7121 mDstSampleRate = dstSampleRate;
7122
7123 // compute derived parameters
7124 mSrcChannelCount = audio_channel_count_from_in_mask(srcChannelMask);
7125 mDstChannelCount = audio_channel_count_from_in_mask(dstChannelMask);
7126 mDstFrameSize = mDstChannelCount * audio_bytes_per_sample(mDstFormat);
7127
Andy Hungd330ee42015-04-20 13:23:41 -07007128 // do we need to resample?
7129 delete mResampler;
7130 mResampler = NULL;
7131 if (mSrcSampleRate != mDstSampleRate) {
7132 mResampler = AudioResampler::create(AUDIO_FORMAT_PCM_FLOAT,
7133 mSrcChannelCount, mDstSampleRate);
7134 mResampler->setSampleRate(mSrcSampleRate);
7135 mResampler->setVolume(AudioMixer::UNITY_GAIN_FLOAT, AudioMixer::UNITY_GAIN_FLOAT);
7136 }
7137
7138 // are we running legacy channel conversion modes?
7139 mIsLegacyDownmix = (mSrcChannelMask == AUDIO_CHANNEL_IN_STEREO
7140 || mSrcChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK)
7141 && mDstChannelMask == AUDIO_CHANNEL_IN_MONO;
7142 mIsLegacyUpmix = mSrcChannelMask == AUDIO_CHANNEL_IN_MONO
7143 && (mDstChannelMask == AUDIO_CHANNEL_IN_STEREO
7144 || mDstChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK);
7145
7146 // do we need to process in float?
7147 mRequiresFloat = mResampler != NULL || mIsLegacyDownmix || mIsLegacyUpmix;
7148
7149 // do we need a staging buffer to convert for destination (we can still optimize this)?
7150 // we use mBufFrameSize > 0 to indicate both frame size as well as buffer necessity
7151 if (mResampler != NULL) {
7152 mBufFrameSize = max(mSrcChannelCount, FCC_2)
7153 * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
Andy Hunga97630b2015-07-22 23:27:24 -07007154 } else if (mIsLegacyUpmix || mIsLegacyDownmix) { // legacy modes always float
Andy Hungd330ee42015-04-20 13:23:41 -07007155 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
7156 } else if (mSrcChannelMask != mDstChannelMask && mDstFormat != mSrcFormat) {
Andy Hung97a893e2015-03-29 01:03:07 -07007157 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(mSrcFormat);
7158 } else {
7159 mBufFrameSize = 0;
7160 }
7161 mBufFrames = 0; // force the buffer to be resized.
7162
Andy Hungd330ee42015-04-20 13:23:41 -07007163 // do we need an input converter buffer provider to give us float?
7164 delete mInputConverterProvider;
7165 mInputConverterProvider = NULL;
7166 if (mRequiresFloat && mSrcFormat != AUDIO_FORMAT_PCM_FLOAT) {
7167 mInputConverterProvider = new ReformatBufferProvider(
7168 audio_channel_count_from_in_mask(mSrcChannelMask),
7169 mSrcFormat,
7170 AUDIO_FORMAT_PCM_FLOAT,
7171 256 /* provider buffer frame count */);
7172 }
7173
7174 // do we need a remixer to do channel mask conversion
7175 if (!mIsLegacyDownmix && !mIsLegacyUpmix && mSrcChannelMask != mDstChannelMask) {
7176 (void) memcpy_by_index_array_initialization_from_channel_mask(
7177 mIdxAry, ARRAY_SIZE(mIdxAry), mDstChannelMask, mSrcChannelMask);
Andy Hung97a893e2015-03-29 01:03:07 -07007178 }
7179 return NO_ERROR;
7180}
7181
Andy Hungd330ee42015-04-20 13:23:41 -07007182void AudioFlinger::RecordThread::RecordBufferConverter::convertNoResampler(
7183 void *dst, const void *src, size_t frames)
Andy Hung97a893e2015-03-29 01:03:07 -07007184{
Andy Hungd330ee42015-04-20 13:23:41 -07007185 // src is native type unless there is legacy upmix or downmix, whereupon it is float.
Andy Hung97a893e2015-03-29 01:03:07 -07007186 if (mBufFrameSize != 0 && mBufFrames < frames) {
7187 free(mBuf);
7188 mBufFrames = frames;
7189 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
7190 }
Andy Hungd330ee42015-04-20 13:23:41 -07007191 // do we need to do legacy upmix and downmix?
7192 if (mIsLegacyUpmix || mIsLegacyDownmix) {
Andy Hung97a893e2015-03-29 01:03:07 -07007193 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07007194 if (mIsLegacyUpmix) {
7195 upmix_to_stereo_float_from_mono_float((float *)dstBuf,
7196 (const float *)src, frames);
7197 } else /*mIsLegacyDownmix */ {
7198 downmix_to_mono_float_from_stereo_float((float *)dstBuf,
7199 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07007200 }
Andy Hungd330ee42015-04-20 13:23:41 -07007201 if (mBuf != NULL) {
7202 memcpy_by_audio_format(dst, mDstFormat, mBuf, AUDIO_FORMAT_PCM_FLOAT,
7203 frames * mDstChannelCount);
7204 }
7205 return;
7206 }
7207 // do we need to do channel mask conversion?
7208 if (mSrcChannelMask != mDstChannelMask) {
Andy Hung97a893e2015-03-29 01:03:07 -07007209 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07007210 memcpy_by_index_array(dstBuf, mDstChannelCount,
7211 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mSrcFormat), frames);
7212 if (dstBuf == dst) {
7213 return; // format is the same
7214 }
7215 }
7216 // convert to destination buffer
7217 const void *convertBuf = mBuf != NULL ? mBuf : src;
7218 memcpy_by_audio_format(dst, mDstFormat, convertBuf, mSrcFormat,
7219 frames * mDstChannelCount);
7220}
7221
7222void AudioFlinger::RecordThread::RecordBufferConverter::convertResampler(
7223 void *dst, /*not-a-const*/ void *src, size_t frames)
7224{
7225 // src buffer format is ALWAYS float when entering this routine
7226 if (mIsLegacyUpmix) {
7227 ; // mono to stereo already handled by resampler
7228 } else if (mIsLegacyDownmix
7229 || (mSrcChannelMask == mDstChannelMask && mSrcChannelCount == 1)) {
7230 // the resampler outputs stereo for mono input channel (a feature?)
7231 // must convert to mono
7232 downmix_to_mono_float_from_stereo_float((float *)src,
7233 (const float *)src, frames);
7234 } else if (mSrcChannelMask != mDstChannelMask) {
7235 // convert to mono channel again for channel mask conversion (could be skipped
7236 // with further optimization).
Andy Hung97a893e2015-03-29 01:03:07 -07007237 if (mSrcChannelCount == 1) {
Andy Hungd330ee42015-04-20 13:23:41 -07007238 downmix_to_mono_float_from_stereo_float((float *)src,
7239 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07007240 }
Andy Hungd330ee42015-04-20 13:23:41 -07007241 // convert to destination format (in place, OK as float is larger than other types)
7242 if (mDstFormat != AUDIO_FORMAT_PCM_FLOAT) {
7243 memcpy_by_audio_format(src, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
7244 frames * mSrcChannelCount);
7245 }
7246 // channel convert and save to dst
7247 memcpy_by_index_array(dst, mDstChannelCount,
7248 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mDstFormat), frames);
7249 return;
Andy Hung97a893e2015-03-29 01:03:07 -07007250 }
Andy Hungd330ee42015-04-20 13:23:41 -07007251 // convert to destination format and save to dst
7252 memcpy_by_audio_format(dst, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
7253 frames * mDstChannelCount);
Andy Hung97a893e2015-03-29 01:03:07 -07007254}
7255
Eric Laurent10351942014-05-08 18:49:52 -07007256bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
7257 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007258{
7259 bool reconfig = false;
7260
Eric Laurent10351942014-05-08 18:49:52 -07007261 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007262
Eric Laurent10351942014-05-08 18:49:52 -07007263 audio_format_t reqFormat = mFormat;
7264 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07007265 // 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 -07007266 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
7267
7268 AudioParameter param = AudioParameter(keyValuePair);
7269 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07007270
7271 // scope for AutoPark extends to end of method
7272 AutoPark<FastCapture> park(mFastCapture);
7273
Eric Laurent10351942014-05-08 18:49:52 -07007274 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
7275 // channel count change can be requested. Do we mandate the first client defines the
7276 // HAL sampling rate and channel count or do we allow changes on the fly?
7277 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
7278 samplingRate = value;
7279 reconfig = true;
7280 }
7281 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07007282 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07007283 status = BAD_VALUE;
7284 } else {
7285 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08007286 reconfig = true;
7287 }
Eric Laurent10351942014-05-08 18:49:52 -07007288 }
7289 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
7290 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07007291 if (!audio_is_input_channel(mask) ||
7292 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007293 status = BAD_VALUE;
7294 } else {
7295 channelMask = mask;
7296 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007297 }
Eric Laurent10351942014-05-08 18:49:52 -07007298 }
7299 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7300 // do not accept frame count changes if tracks are open as the track buffer
7301 // size depends on frame count and correct behavior would not be guaranteed
7302 // if frame count is changed after track creation
7303 if (mActiveTracks.size() > 0) {
7304 status = INVALID_OPERATION;
7305 } else {
7306 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007307 }
Eric Laurent10351942014-05-08 18:49:52 -07007308 }
7309 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7310 // forward device change to effects that have requested to be
7311 // aware of attached audio device.
7312 for (size_t i = 0; i < mEffectChains.size(); i++) {
7313 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08007314 }
Eric Laurent81784c32012-11-19 14:55:58 -08007315
Eric Laurent10351942014-05-08 18:49:52 -07007316 // store input device and output device but do not forward output device to audio HAL.
7317 // Note that status is ignored by the caller for output device
7318 // (see AudioFlinger::setParameters()
7319 if (audio_is_output_devices(value)) {
7320 mOutDevice = value;
7321 status = BAD_VALUE;
7322 } else {
7323 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07007324 if (value != AUDIO_DEVICE_NONE) {
7325 mPrevInDevice = value;
7326 }
Eric Laurent10351942014-05-08 18:49:52 -07007327 // disable AEC and NS if the device is a BT SCO headset supporting those
7328 // pre processings
7329 if (mTracks.size() > 0) {
7330 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7331 mAudioFlinger->btNrecIsOff();
7332 for (size_t i = 0; i < mTracks.size(); i++) {
7333 sp<RecordTrack> track = mTracks[i];
7334 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7335 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08007336 }
7337 }
7338 }
Eric Laurent10351942014-05-08 18:49:52 -07007339 }
7340 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
7341 mAudioSource != (audio_source_t)value) {
7342 // forward device change to effects that have requested to be
7343 // aware of attached audio device.
7344 for (size_t i = 0; i < mEffectChains.size(); i++) {
7345 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08007346 }
Eric Laurent10351942014-05-08 18:49:52 -07007347 mAudioSource = (audio_source_t)value;
7348 }
Glenn Kastene198c362013-08-13 09:13:36 -07007349
Eric Laurent10351942014-05-08 18:49:52 -07007350 if (status == NO_ERROR) {
7351 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7352 keyValuePair.string());
7353 if (status == INVALID_OPERATION) {
7354 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08007355 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7356 keyValuePair.string());
Eric Laurent10351942014-05-08 18:49:52 -07007357 }
7358 if (reconfig) {
7359 if (status == BAD_VALUE &&
Andy Hung97a893e2015-03-29 01:03:07 -07007360 audio_is_linear_pcm(mInput->stream->common.get_format(&mInput->stream->common)) &&
7361 audio_is_linear_pcm(reqFormat) &&
Eric Laurent10351942014-05-08 18:49:52 -07007362 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
Andy Hung97a893e2015-03-29 01:03:07 -07007363 <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate)) &&
Andy Hunge5412692014-05-16 11:25:07 -07007364 audio_channel_count_from_in_mask(
Andy Hungd1abb8f2015-05-05 23:42:34 -07007365 mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007366 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007367 }
Eric Laurent10351942014-05-08 18:49:52 -07007368 if (status == NO_ERROR) {
7369 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007370 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08007371 }
7372 }
Eric Laurent81784c32012-11-19 14:55:58 -08007373 }
Eric Laurent10351942014-05-08 18:49:52 -07007374
Eric Laurent81784c32012-11-19 14:55:58 -08007375 return reconfig;
7376}
7377
7378String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
7379{
Eric Laurent81784c32012-11-19 14:55:58 -08007380 Mutex::Autolock _l(mLock);
7381 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07007382 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08007383 }
7384
Glenn Kastend8ea6992013-07-16 14:17:15 -07007385 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
7386 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08007387 free(s);
7388 return out_s8;
7389}
7390
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007391void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007392 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7393
7394 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08007395
7396 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007397 case AUDIO_INPUT_OPENED:
7398 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07007399 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07007400 desc->mChannelMask = mChannelMask;
7401 desc->mSamplingRate = mSampleRate;
7402 desc->mFormat = mFormat;
7403 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07007404 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07007405 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007406 break;
7407
Eric Laurent73e26b62015-04-27 16:55:58 -07007408 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08007409 default:
7410 break;
7411 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007412 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08007413}
7414
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007415void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007416{
Eric Laurent81784c32012-11-19 14:55:58 -08007417 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
7418 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Andy Hunge5412692014-05-16 11:25:07 -07007419 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Andy Hungd330ee42015-04-20 13:23:41 -07007420 if (mChannelCount > FCC_8) {
7421 ALOGE("HAL channel count %d > %d", mChannelCount, FCC_8);
7422 }
Andy Hung463be252014-07-10 16:56:07 -07007423 mHALFormat = mInput->stream->common.get_format(&mInput->stream->common);
7424 mFormat = mHALFormat;
Andy Hungd330ee42015-04-20 13:23:41 -07007425 if (!audio_is_linear_pcm(mFormat)) {
7426 ALOGE("HAL format %#x is not linear pcm", mFormat);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07007427 }
Eric Laurent665470b2014-07-03 16:37:08 -07007428 mFrameSize = audio_stream_in_frame_size(mInput->stream);
Glenn Kasten548efc92012-11-29 08:48:51 -08007429 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
7430 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007431 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08007432 // 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 -07007433 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08007434 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007435 // A larger value should allow more old data to be read after a track calls start(),
7436 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07007437 //
7438 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08007439 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07007440 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07007441 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07007442 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007443
7444 // TODO optimize audio capture buffer sizes ...
7445 // Here we calculate the size of the sliding buffer used as a source
7446 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
7447 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
7448 // be better to have it derived from the pipe depth in the long term.
7449 // The current value is higher than necessary. However it should not add to latency.
7450
Glenn Kasten85948432013-08-19 12:09:05 -07007451 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Andy Hung0a01c2f2015-09-21 12:44:54 -07007452 size_t bufferSize = (mRsmpInFramesP2 + mFrameCount - 1) * mFrameSize;
7453 (void)posix_memalign(&mRsmpInBuffer, 32, bufferSize);
7454 memset(mRsmpInBuffer, 0, bufferSize); // if posix_memalign fails, will segv here.
Eric Laurent81784c32012-11-19 14:55:58 -08007455
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007456 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
7457 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08007458}
7459
Glenn Kasten5f972c02014-01-13 09:59:31 -08007460uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08007461{
7462 Mutex::Autolock _l(mLock);
7463 if (initCheck() != NO_ERROR) {
7464 return 0;
7465 }
7466
7467 return mInput->stream->get_input_frames_lost(mInput->stream);
7468}
7469
Eric Laurent4c415062016-06-17 16:14:16 -07007470// hasAudioSession_l() must be called with ThreadBase::mLock held
7471uint32_t AudioFlinger::RecordThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08007472{
Eric Laurent81784c32012-11-19 14:55:58 -08007473 uint32_t result = 0;
7474 if (getEffectChain_l(sessionId) != 0) {
7475 result = EFFECT_SESSION;
7476 }
7477
7478 for (size_t i = 0; i < mTracks.size(); ++i) {
7479 if (sessionId == mTracks[i]->sessionId()) {
7480 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07007481 if (mTracks[i]->isFastTrack()) {
7482 result |= FAST_SESSION;
7483 }
Eric Laurent81784c32012-11-19 14:55:58 -08007484 break;
7485 }
7486 }
7487
7488 return result;
7489}
7490
Glenn Kastend848eb42016-03-08 13:42:11 -08007491KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08007492{
Glenn Kastend848eb42016-03-08 13:42:11 -08007493 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08007494 Mutex::Autolock _l(mLock);
7495 for (size_t j = 0; j < mTracks.size(); ++j) {
7496 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08007497 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08007498 if (ids.indexOfKey(sessionId) < 0) {
7499 ids.add(sessionId, true);
7500 }
7501 }
7502 return ids;
7503}
7504
7505AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7506{
7507 Mutex::Autolock _l(mLock);
7508 AudioStreamIn *input = mInput;
7509 mInput = NULL;
7510 return input;
7511}
7512
7513// this method must always be called either with ThreadBase mLock held or inside the thread loop
7514audio_stream_t* AudioFlinger::RecordThread::stream() const
7515{
7516 if (mInput == NULL) {
7517 return NULL;
7518 }
7519 return &mInput->stream->common;
7520}
7521
7522status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7523{
7524 // only one chain per input thread
7525 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07007526 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08007527 return INVALID_OPERATION;
7528 }
7529 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07007530 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08007531 chain->setInBuffer(NULL);
7532 chain->setOutBuffer(NULL);
7533
7534 checkSuspendOnAddEffectChain_l(chain);
7535
Eric Laurent1b928682014-10-02 19:41:47 -07007536 // make sure enabled pre processing effects state is communicated to the HAL as we
7537 // just moved them to a new input stream.
7538 chain->syncHalEffectsState();
7539
Eric Laurent81784c32012-11-19 14:55:58 -08007540 mEffectChains.add(chain);
7541
7542 return NO_ERROR;
7543}
7544
7545size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7546{
7547 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7548 ALOGW_IF(mEffectChains.size() != 1,
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007549 "removeEffectChain_l() %p invalid chain size %zu on thread %p",
Eric Laurent81784c32012-11-19 14:55:58 -08007550 chain.get(), mEffectChains.size(), this);
7551 if (mEffectChains.size() == 1) {
7552 mEffectChains.removeAt(0);
7553 }
7554 return 0;
7555}
7556
Eric Laurent1c333e22014-05-20 10:48:17 -07007557status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7558 audio_patch_handle_t *handle)
7559{
7560 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007561
7562 // store new device and send to effects
7563 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07007564 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07007565 for (size_t i = 0; i < mEffectChains.size(); i++) {
7566 mEffectChains[i]->setDevice_l(mInDevice);
7567 }
7568
7569 // disable AEC and NS if the device is a BT SCO headset supporting those
7570 // pre processings
7571 if (mTracks.size() > 0) {
7572 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7573 mAudioFlinger->btNrecIsOff();
7574 for (size_t i = 0; i < mTracks.size(); i++) {
7575 sp<RecordTrack> track = mTracks[i];
7576 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7577 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
7578 }
7579 }
7580
7581 // store new source and send to effects
7582 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7583 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07007584 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07007585 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07007586 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007587 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007588
Eric Laurent054d9d32015-04-24 08:48:48 -07007589 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007590 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7591 status = hwDevice->createAudioPatch(patch->num_sources,
7592 patch->sources,
7593 patch->num_sinks,
7594 patch->sinks,
7595 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007596 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007597 char *address;
7598 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7599 address = audio_device_address_to_parameter(
7600 patch->sources[0].ext.device.type,
7601 patch->sources[0].ext.device.address);
7602 } else {
7603 address = (char *)calloc(1, 1);
7604 }
7605 AudioParameter param = AudioParameter(String8(address));
7606 free(address);
7607 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING),
7608 (int)patch->sources[0].ext.device.type);
7609 param.addInt(String8(AUDIO_PARAMETER_STREAM_INPUT_SOURCE),
7610 (int)patch->sinks[0].ext.mix.usecase.source);
7611 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7612 param.toString().string());
7613 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07007614 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007615
Eric Laurente8726fe2015-06-26 09:39:24 -07007616 if (mInDevice != mPrevInDevice) {
7617 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7618 mPrevInDevice = mInDevice;
7619 }
Eric Laurent296fb132015-05-01 11:38:42 -07007620
Eric Laurent1c333e22014-05-20 10:48:17 -07007621 return status;
7622}
7623
7624status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7625{
7626 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007627
7628 mInDevice = AUDIO_DEVICE_NONE;
7629
Eric Laurent1c333e22014-05-20 10:48:17 -07007630 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007631 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7632 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007633 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007634 AudioParameter param;
7635 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
7636 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7637 param.toString().string());
Eric Laurent1c333e22014-05-20 10:48:17 -07007638 }
7639 return status;
7640}
7641
Eric Laurent83b88082014-06-20 18:31:16 -07007642void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
7643{
7644 Mutex::Autolock _l(mLock);
7645 mTracks.add(record);
7646}
7647
7648void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
7649{
7650 Mutex::Autolock _l(mLock);
7651 destroyTrack_l(record);
7652}
7653
7654void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
7655{
7656 ThreadBase::getAudioPortConfig(config);
7657 config->role = AUDIO_PORT_ROLE_SINK;
7658 config->ext.mix.hw_module = mInput->audioHwDev->handle();
7659 config->ext.mix.usecase.source = mAudioSource;
7660}
Eric Laurent1c333e22014-05-20 10:48:17 -07007661
Glenn Kasten63238ef2015-03-02 15:50:29 -08007662} // namespace android