blob: 20b259a6c61cfea11a3aae9c0b5fb234edd4ce6c [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++) {
1156 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1157 for (int j = 0; j < desc->mRefCount; j++) {
1158 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1159 chain->setEffectSuspendedAll_l(true);
1160 } else {
1161 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1162 desc->mType.timeLow);
1163 chain->setEffectSuspended_l(&desc->mType, true);
1164 }
1165 }
1166 }
1167}
1168
1169void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1170 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001171 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001172{
1173 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1174
1175 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1176
1177 if (suspend) {
1178 if (index >= 0) {
1179 sessionEffects = mSuspendedSessions.valueAt(index);
1180 } else {
1181 mSuspendedSessions.add(sessionId, sessionEffects);
1182 }
1183 } else {
1184 if (index < 0) {
1185 return;
1186 }
1187 sessionEffects = mSuspendedSessions.valueAt(index);
1188 }
1189
1190
1191 int key = EffectChain::kKeyForSuspendAll;
1192 if (type != NULL) {
1193 key = type->timeLow;
1194 }
1195 index = sessionEffects.indexOfKey(key);
1196
1197 sp<SuspendedSessionDesc> desc;
1198 if (suspend) {
1199 if (index >= 0) {
1200 desc = sessionEffects.valueAt(index);
1201 } else {
1202 desc = new SuspendedSessionDesc();
1203 if (type != NULL) {
1204 desc->mType = *type;
1205 }
1206 sessionEffects.add(key, desc);
1207 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1208 }
1209 desc->mRefCount++;
1210 } else {
1211 if (index < 0) {
1212 return;
1213 }
1214 desc = sessionEffects.valueAt(index);
1215 if (--desc->mRefCount == 0) {
1216 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1217 sessionEffects.removeItemsAt(index);
1218 if (sessionEffects.isEmpty()) {
1219 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1220 sessionId);
1221 mSuspendedSessions.removeItem(sessionId);
1222 }
1223 }
1224 }
1225 if (!sessionEffects.isEmpty()) {
1226 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1227 }
1228}
1229
1230void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1231 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001232 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001233{
1234 Mutex::Autolock _l(mLock);
1235 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1236}
1237
1238void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1239 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001240 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001241{
1242 if (mType != RECORD) {
1243 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1244 // another session. This gives the priority to well behaved effect control panels
1245 // and applications not using global effects.
1246 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1247 // global effects
1248 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1249 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1250 }
1251 }
1252
1253 sp<EffectChain> chain = getEffectChain_l(sessionId);
1254 if (chain != 0) {
1255 chain->checkSuspendOnEffectEnabled(effect, enabled);
1256 }
1257}
1258
1259// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1260sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1261 const sp<AudioFlinger::Client>& client,
1262 const sp<IEffectClient>& effectClient,
1263 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001264 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001265 effect_descriptor_t *desc,
1266 int *enabled,
Glenn Kasten9156ef32013-08-06 15:39:08 -07001267 status_t *status)
Eric Laurent81784c32012-11-19 14:55:58 -08001268{
1269 sp<EffectModule> effect;
1270 sp<EffectHandle> handle;
1271 status_t lStatus;
1272 sp<EffectChain> chain;
1273 bool chainCreated = false;
1274 bool effectCreated = false;
1275 bool effectRegistered = false;
1276
1277 lStatus = initCheck();
1278 if (lStatus != NO_ERROR) {
1279 ALOGW("createEffect_l() Audio driver not initialized.");
1280 goto Exit;
1281 }
1282
Andy Hung98ef9782014-03-04 14:46:50 -08001283 // Reject any effect on Direct output threads for now, since the format of
1284 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1285 if (mType == DIRECT) {
1286 ALOGW("createEffect_l() Cannot add effect %s on Direct output type thread %s",
Glenn Kastend7dca052015-03-05 16:05:54 -08001287 desc->name, mThreadName);
Andy Hung98ef9782014-03-04 14:46:50 -08001288 lStatus = BAD_VALUE;
1289 goto Exit;
1290 }
1291
Andy Hung389cfdb2014-08-07 17:49:53 -07001292 // Reject any effect on mixer or duplicating multichannel sinks.
Andy Hung9a592762014-07-21 21:56:01 -07001293 // TODO: fix both format and multichannel issues with effects.
Andy Hung389cfdb2014-08-07 17:49:53 -07001294 if ((mType == MIXER || mType == DUPLICATING) && mChannelCount != FCC_2) {
1295 ALOGW("createEffect_l() Cannot add effect %s for multichannel(%d) %s threads",
1296 desc->name, mChannelCount, mType == MIXER ? "MIXER" : "DUPLICATING");
Andy Hung9a592762014-07-21 21:56:01 -07001297 lStatus = BAD_VALUE;
1298 goto Exit;
1299 }
1300
Eric Laurent5baf2af2013-09-12 17:37:00 -07001301 // Allow global effects only on offloaded and mixer threads
1302 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1303 switch (mType) {
1304 case MIXER:
1305 case OFFLOAD:
1306 break;
1307 case DIRECT:
1308 case DUPLICATING:
1309 case RECORD:
1310 default:
Glenn Kastend7dca052015-03-05 16:05:54 -08001311 ALOGW("createEffect_l() Cannot add global effect %s on thread %s",
1312 desc->name, mThreadName);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001313 lStatus = BAD_VALUE;
1314 goto Exit;
1315 }
Eric Laurent81784c32012-11-19 14:55:58 -08001316 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001317
Eric Laurent81784c32012-11-19 14:55:58 -08001318 // Only Pre processor effects are allowed on input threads and only on input threads
1319 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
1320 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
1321 desc->name, desc->flags, mType);
1322 lStatus = BAD_VALUE;
1323 goto Exit;
1324 }
1325
1326 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1327
1328 { // scope for mLock
1329 Mutex::Autolock _l(mLock);
1330
1331 // check for existing effect chain with the requested audio session
1332 chain = getEffectChain_l(sessionId);
1333 if (chain == 0) {
1334 // create a new chain for this session
1335 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1336 chain = new EffectChain(this, sessionId);
1337 addEffectChain_l(chain);
1338 chain->setStrategy(getStrategyForSession_l(sessionId));
1339 chainCreated = true;
1340 } else {
1341 effect = chain->getEffectFromDesc_l(desc);
1342 }
1343
1344 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1345
1346 if (effect == 0) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08001347 audio_unique_id_t id = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001348 // Check CPU and memory usage
1349 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
1350 if (lStatus != NO_ERROR) {
1351 goto Exit;
1352 }
1353 effectRegistered = true;
1354 // create a new effect module if none present in the chain
1355 effect = new EffectModule(this, chain, desc, id, sessionId);
1356 lStatus = effect->status();
1357 if (lStatus != NO_ERROR) {
1358 goto Exit;
1359 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001360 effect->setOffloaded(mType == OFFLOAD, mId);
1361
Eric Laurent81784c32012-11-19 14:55:58 -08001362 lStatus = chain->addEffect_l(effect);
1363 if (lStatus != NO_ERROR) {
1364 goto Exit;
1365 }
1366 effectCreated = true;
1367
1368 effect->setDevice(mOutDevice);
1369 effect->setDevice(mInDevice);
1370 effect->setMode(mAudioFlinger->getMode());
1371 effect->setAudioSource(mAudioSource);
1372 }
1373 // create effect handle and connect it to effect module
1374 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001375 lStatus = handle->initCheck();
1376 if (lStatus == OK) {
1377 lStatus = effect->addHandle(handle.get());
1378 }
Eric Laurent81784c32012-11-19 14:55:58 -08001379 if (enabled != NULL) {
1380 *enabled = (int)effect->isEnabled();
1381 }
1382 }
1383
1384Exit:
1385 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1386 Mutex::Autolock _l(mLock);
1387 if (effectCreated) {
1388 chain->removeEffect_l(effect);
1389 }
1390 if (effectRegistered) {
1391 AudioSystem::unregisterEffect(effect->id());
1392 }
1393 if (chainCreated) {
1394 removeEffectChain_l(chain);
1395 }
1396 handle.clear();
1397 }
1398
Glenn Kasten9156ef32013-08-06 15:39:08 -07001399 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001400 return handle;
1401}
1402
Glenn Kastend848eb42016-03-08 13:42:11 -08001403sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1404 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001405{
1406 Mutex::Autolock _l(mLock);
1407 return getEffect_l(sessionId, effectId);
1408}
1409
Glenn Kastend848eb42016-03-08 13:42:11 -08001410sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1411 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001412{
1413 sp<EffectChain> chain = getEffectChain_l(sessionId);
1414 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1415}
1416
1417// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1418// PlaybackThread::mLock held
1419status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1420{
1421 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001422 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001423 sp<EffectChain> chain = getEffectChain_l(sessionId);
1424 bool chainCreated = false;
1425
Eric Laurent5baf2af2013-09-12 17:37:00 -07001426 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1427 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1428 this, effect->desc().name, effect->desc().flags);
1429
Eric Laurent81784c32012-11-19 14:55:58 -08001430 if (chain == 0) {
1431 // create a new chain for this session
1432 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1433 chain = new EffectChain(this, sessionId);
1434 addEffectChain_l(chain);
1435 chain->setStrategy(getStrategyForSession_l(sessionId));
1436 chainCreated = true;
1437 }
1438 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1439
1440 if (chain->getEffectFromId_l(effect->id()) != 0) {
1441 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1442 this, effect->desc().name, chain.get());
1443 return BAD_VALUE;
1444 }
1445
Eric Laurent5baf2af2013-09-12 17:37:00 -07001446 effect->setOffloaded(mType == OFFLOAD, mId);
1447
Eric Laurent81784c32012-11-19 14:55:58 -08001448 status_t status = chain->addEffect_l(effect);
1449 if (status != NO_ERROR) {
1450 if (chainCreated) {
1451 removeEffectChain_l(chain);
1452 }
1453 return status;
1454 }
1455
1456 effect->setDevice(mOutDevice);
1457 effect->setDevice(mInDevice);
1458 effect->setMode(mAudioFlinger->getMode());
1459 effect->setAudioSource(mAudioSource);
1460 return NO_ERROR;
1461}
1462
1463void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
1464
1465 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
1466 effect_descriptor_t desc = effect->desc();
1467 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1468 detachAuxEffect_l(effect->id());
1469 }
1470
1471 sp<EffectChain> chain = effect->chain().promote();
1472 if (chain != 0) {
1473 // remove effect chain if removing last effect
1474 if (chain->removeEffect_l(effect) == 0) {
1475 removeEffectChain_l(chain);
1476 }
1477 } else {
1478 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1479 }
1480}
1481
1482void AudioFlinger::ThreadBase::lockEffectChains_l(
1483 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1484{
1485 effectChains = mEffectChains;
1486 for (size_t i = 0; i < mEffectChains.size(); i++) {
1487 mEffectChains[i]->lock();
1488 }
1489}
1490
1491void AudioFlinger::ThreadBase::unlockEffectChains(
1492 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1493{
1494 for (size_t i = 0; i < effectChains.size(); i++) {
1495 effectChains[i]->unlock();
1496 }
1497}
1498
Glenn Kastend848eb42016-03-08 13:42:11 -08001499sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001500{
1501 Mutex::Autolock _l(mLock);
1502 return getEffectChain_l(sessionId);
1503}
1504
Glenn Kastend848eb42016-03-08 13:42:11 -08001505sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1506 const
Eric Laurent81784c32012-11-19 14:55:58 -08001507{
1508 size_t size = mEffectChains.size();
1509 for (size_t i = 0; i < size; i++) {
1510 if (mEffectChains[i]->sessionId() == sessionId) {
1511 return mEffectChains[i];
1512 }
1513 }
1514 return 0;
1515}
1516
1517void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1518{
1519 Mutex::Autolock _l(mLock);
1520 size_t size = mEffectChains.size();
1521 for (size_t i = 0; i < size; i++) {
1522 mEffectChains[i]->setMode_l(mode);
1523 }
1524}
1525
Eric Laurent83b88082014-06-20 18:31:16 -07001526void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1527{
1528 config->type = AUDIO_PORT_TYPE_MIX;
1529 config->ext.mix.handle = mId;
1530 config->sample_rate = mSampleRate;
1531 config->format = mFormat;
1532 config->channel_mask = mChannelMask;
1533 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1534 AUDIO_PORT_CONFIG_FORMAT;
1535}
1536
Eric Laurent72e3f392015-05-20 14:43:50 -07001537void AudioFlinger::ThreadBase::systemReady()
1538{
1539 Mutex::Autolock _l(mLock);
1540 if (mSystemReady) {
1541 return;
1542 }
1543 mSystemReady = true;
1544
1545 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1546 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1547 }
1548 mPendingConfigEvents.clear();
1549}
1550
Eric Laurent83b88082014-06-20 18:31:16 -07001551
Eric Laurent81784c32012-11-19 14:55:58 -08001552// ----------------------------------------------------------------------------
1553// Playback
1554// ----------------------------------------------------------------------------
1555
1556AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1557 AudioStreamOut* output,
1558 audio_io_handle_t id,
1559 audio_devices_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07001560 type_t type,
Eric Laurente93cc032016-05-05 10:15:10 -07001561 bool systemReady)
Eric Laurent72e3f392015-05-20 14:43:50 -07001562 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001563 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001564 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001565 mMixerBuffer(NULL),
1566 mMixerBufferSize(0),
1567 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1568 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001569 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001570 mEffectBuffer(NULL),
1571 mEffectBufferSize(0),
1572 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1573 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001574 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001575 mFramesWritten(0),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001576 mActiveTracksGeneration(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001577 // mStreamTypes[] initialized in constructor body
1578 mOutput(output),
Andy Hung69488c42016-05-16 18:43:33 -07001579 mLastWriteTime(-1), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001580 mMixerStatus(MIXER_IDLE),
1581 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001582 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001583 mBytesRemaining(0),
1584 mCurrentWriteLength(0),
1585 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001586 mWriteAckSequence(0),
1587 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001588 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001589 mScreenState(AudioFlinger::mScreenState),
1590 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001591 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Andy Hunge10393e2015-06-12 13:59:33 -07001592 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001593{
Glenn Kastend7dca052015-03-05 16:05:54 -08001594 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1595 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001596
1597 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1598 // it would be safer to explicitly pass initial masterVolume/masterMute as
1599 // parameter.
1600 //
1601 // If the HAL we are using has support for master volume or master mute,
1602 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1603 // and the mute set to false).
1604 mMasterVolume = audioFlinger->masterVolume_l();
1605 mMasterMute = audioFlinger->masterMute_l();
1606 if (mOutput && mOutput->audioHwDev) {
1607 if (mOutput->audioHwDev->canSetMasterVolume()) {
1608 mMasterVolume = 1.0;
1609 }
1610
1611 if (mOutput->audioHwDev->canSetMasterMute()) {
1612 mMasterMute = false;
1613 }
1614 }
1615
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001616 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001617
Eric Laurent223fd5c2014-11-11 13:43:36 -08001618 // ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001619 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001620 stream = (audio_stream_type_t) (stream + 1)) {
1621 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1622 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1623 }
Eric Laurent81784c32012-11-19 14:55:58 -08001624}
1625
1626AudioFlinger::PlaybackThread::~PlaybackThread()
1627{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001628 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001629 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001630 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001631 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001632}
1633
1634void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1635{
1636 dumpInternals(fd, args);
1637 dumpTracks(fd, args);
1638 dumpEffectChains(fd, args);
1639}
1640
Glenn Kasten0f11b512014-01-31 16:18:54 -08001641void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001642{
1643 const size_t SIZE = 256;
1644 char buffer[SIZE];
1645 String8 result;
1646
Marco Nelissenb2208842014-02-07 14:00:50 -08001647 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001648 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1649 const stream_type_t *st = &mStreamTypes[i];
1650 if (i > 0) {
1651 result.appendFormat(", ");
1652 }
1653 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1654 if (st->mute) {
1655 result.append("M");
1656 }
1657 }
1658 result.append("\n");
1659 write(fd, result.string(), result.length());
1660 result.clear();
1661
Eric Laurent81784c32012-11-19 14:55:58 -08001662 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1663 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001664 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001665 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001666
1667 size_t numtracks = mTracks.size();
1668 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001669 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001670 size_t numactiveseen = 0;
1671 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001672 dprintf(fd, " of which %zu are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001673 Track::appendDumpHeader(result);
1674 for (size_t i = 0; i < numtracks; ++i) {
1675 sp<Track> track = mTracks[i];
1676 if (track != 0) {
1677 bool active = mActiveTracks.indexOf(track) >= 0;
1678 if (active) {
1679 numactiveseen++;
1680 }
1681 track->dump(buffer, SIZE, active);
1682 result.append(buffer);
1683 }
1684 }
1685 } else {
1686 result.append("\n");
1687 }
1688 if (numactiveseen != numactive) {
1689 // some tracks in the active list were not in the tracks list
1690 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1691 " not in the track list\n");
1692 result.append(buffer);
1693 Track::appendDumpHeader(result);
1694 for (size_t i = 0; i < numactive; ++i) {
1695 sp<Track> track = mActiveTracks[i].promote();
1696 if (track != 0 && mTracks.indexOf(track) < 0) {
1697 track->dump(buffer, SIZE, true);
1698 result.append(buffer);
1699 }
1700 }
1701 }
1702
1703 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001704}
1705
1706void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1707{
Glenn Kasten97b7b752014-09-28 13:04:24 -07001708 dprintf(fd, "\nOutput thread %p type %d (%s):\n", this, type(), threadTypeToString(type()));
Glenn Kasten44182c22015-03-05 17:12:23 -08001709
1710 dumpBase(fd, args);
1711
Elliott Hughes87cebad2014-05-22 10:14:43 -07001712 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001713 dprintf(fd, " Last write occurred (msecs): %llu\n",
1714 (unsigned long long) ns2ms(systemTime() - mLastWriteTime));
Elliott Hughes87cebad2014-05-22 10:14:43 -07001715 dprintf(fd, " Total writes: %d\n", mNumWrites);
1716 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1717 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1718 dprintf(fd, " Suspend count: %d\n", mSuspended);
1719 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1720 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1721 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1722 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08001723 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001724 AudioStreamOut *output = mOutput;
1725 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
1726 String8 flagsAsString = outputFlagsToString(flags);
1727 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n", output, flags, flagsAsString.string());
Eric Laurent81784c32012-11-19 14:55:58 -08001728}
1729
1730// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001731
1732void AudioFlinger::PlaybackThread::onFirstRef()
1733{
Glenn Kastend7dca052015-03-05 16:05:54 -08001734 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001735}
1736
1737// ThreadBase virtuals
1738void AudioFlinger::PlaybackThread::preExit()
1739{
1740 ALOGV(" preExit()");
1741 // FIXME this is using hard-coded strings but in the future, this functionality will be
1742 // converted to use audio HAL extensions required to support tunneling
1743 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1744}
1745
1746// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1747sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1748 const sp<AudioFlinger::Client>& client,
1749 audio_stream_type_t streamType,
1750 uint32_t sampleRate,
1751 audio_format_t format,
1752 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001753 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001754 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08001755 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07001756 audio_output_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08001757 pid_t tid,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001758 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -08001759 status_t *status)
1760{
Glenn Kasten74935e42013-12-19 08:56:45 -08001761 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001762 sp<Track> track;
1763 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07001764 audio_output_flags_t outputFlags = mOutput->flags;
1765
1766 // special case for FAST flag considered OK if fast mixer is present
1767 if (hasFastMixer()) {
1768 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
1769 }
1770
1771 // Check if requested flags are compatible with output stream flags
1772 if ((*flags & outputFlags) != *flags) {
1773 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
1774 *flags, outputFlags);
1775 *flags = (audio_output_flags_t)(*flags & outputFlags);
1776 }
Eric Laurent81784c32012-11-19 14:55:58 -08001777
Eric Laurent81784c32012-11-19 14:55:58 -08001778 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07001779 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08001780 if (
Eric Laurent81784c32012-11-19 14:55:58 -08001781 // PCM data
1782 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001783 // TODO: extract as a data library function that checks that a computationally
1784 // expensive downmixer is not required: isFastOutputChannelConversion()
Andy Hung9a592762014-07-21 21:56:01 -07001785 (channelMask == mChannelMask ||
Andy Hung1f439e12015-05-19 12:57:41 -07001786 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1787 (channelMask == AUDIO_CHANNEL_OUT_MONO
1788 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001789 // hardware sample rate
1790 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001791 // normal mixer has an associated fast mixer
1792 hasFastMixer() &&
1793 // there are sufficient fast track slots available
1794 (mFastTrackAvailMask != 0)
1795 // FIXME test that MixerThread for this fast track has a capable output HAL
1796 // FIXME add a permission test also?
1797 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07001798 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
1799 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001800 // read the fast track multiplier property the first time it is needed
1801 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1802 if (ok != 0) {
1803 ALOGE("%s pthread_once failed: %d", __func__, ok);
1804 }
Andy Hunge0a269a2016-03-23 15:13:42 -07001805 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08001806 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001807 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08001808 frameCount, mFrameCount);
1809 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001810 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
1811 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07001812 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001813 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08001814 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001815 audio_is_linear_pcm(format),
1816 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent05067782016-06-01 18:27:28 -07001817 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08001818 }
1819 }
1820 // For normal PCM streaming tracks, update minimum frame count.
1821 // For compatibility with AudioTrack calculation, buffer depth is forced
1822 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1823 // This is probably too conservative, but legacy application code may depend on it.
1824 // If you change this calculation, also review the start threshold which is related.
Eric Laurent05067782016-06-01 18:27:28 -07001825 if (!(*flags & AUDIO_OUTPUT_FLAG_FAST)
Phil Burkfdb3c072016-02-09 10:47:02 -08001826 && audio_has_proportional_frames(format) && sharedBuffer == 0) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001827 // this must match AudioTrack.cpp calculateMinFrameCount().
1828 // TODO: Move to a common library
Eric Laurent81784c32012-11-19 14:55:58 -08001829 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1830 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1831 if (minBufCount < 2) {
1832 minBufCount = 2;
1833 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07001834 // For normal mixing tracks, if speed is > 1.0f (normal), AudioTrack
1835 // or the client should compute and pass in a larger buffer request.
Andy Hung0e48d252015-01-26 11:43:15 -08001836 size_t minFrameCount =
Andy Hung8edb8dc2015-03-26 19:13:55 -07001837 minBufCount * sourceFramesNeededWithTimestretch(
1838 sampleRate, mNormalFrameCount,
1839 mSampleRate, AUDIO_TIMESTRETCH_SPEED_NORMAL /*speed*/);
Andy Hung0e48d252015-01-26 11:43:15 -08001840 if (frameCount < minFrameCount) { // including frameCount == 0
Eric Laurent81784c32012-11-19 14:55:58 -08001841 frameCount = minFrameCount;
1842 }
Eric Laurent81784c32012-11-19 14:55:58 -08001843 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001844 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001845
Glenn Kastenc3df8382014-03-13 15:05:25 -07001846 switch (mType) {
1847
1848 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08001849 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08001850 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001851 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1852 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001853 sampleRate, format, channelMask, mOutput, mFormat);
1854 lStatus = BAD_VALUE;
1855 goto Exit;
1856 }
1857 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001858 break;
1859
1860 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001861 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001862 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1863 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001864 sampleRate, format, channelMask, mOutput, mFormat);
1865 lStatus = BAD_VALUE;
1866 goto Exit;
1867 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001868 break;
1869
1870 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001871 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001872 ALOGE("createTrack_l() Bad parameter: format %#x \""
1873 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001874 format, mOutput, mFormat);
1875 lStatus = BAD_VALUE;
1876 goto Exit;
1877 }
Andy Hungcd044842014-08-07 11:04:34 -07001878 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08001879 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1880 lStatus = BAD_VALUE;
1881 goto Exit;
1882 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001883 break;
1884
Eric Laurent81784c32012-11-19 14:55:58 -08001885 }
1886
1887 lStatus = initCheck();
1888 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001889 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08001890 goto Exit;
1891 }
1892
1893 { // scope for mLock
1894 Mutex::Autolock _l(mLock);
1895
1896 // all tracks in same audio session must share the same routing strategy otherwise
1897 // conflicts will happen when tracks are moved from one output to another by audio policy
1898 // manager
1899 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1900 for (size_t i = 0; i < mTracks.size(); ++i) {
1901 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07001902 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001903 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1904 if (sessionId == t->sessionId() && strategy != actual) {
1905 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1906 strategy, actual);
1907 lStatus = BAD_VALUE;
1908 goto Exit;
1909 }
1910 }
1911 }
1912
Glenn Kastend79072e2016-01-06 08:41:20 -08001913 track = new Track(this, client, streamType, sampleRate, format,
1914 channelMask, frameCount, NULL, sharedBuffer,
1915 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT);
Glenn Kasten03003332013-08-06 15:40:54 -07001916
Glenn Kasten03003332013-08-06 15:40:54 -07001917 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1918 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08001919 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001920 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08001921 goto Exit;
1922 }
1923 mTracks.add(track);
1924
1925 sp<EffectChain> chain = getEffectChain_l(sessionId);
1926 if (chain != 0) {
1927 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1928 track->setMainBuffer(chain->inBuffer());
1929 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1930 chain->incTrackCnt();
1931 }
1932
Eric Laurent05067782016-06-01 18:27:28 -07001933 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001934 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1935 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1936 // so ask activity manager to do this on our behalf
1937 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1938 }
1939 }
1940
1941 lStatus = NO_ERROR;
1942
1943Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001944 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001945 return track;
1946}
1947
1948uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1949{
1950 return latency;
1951}
1952
1953uint32_t AudioFlinger::PlaybackThread::latency() const
1954{
1955 Mutex::Autolock _l(mLock);
1956 return latency_l();
1957}
1958uint32_t AudioFlinger::PlaybackThread::latency_l() const
1959{
1960 if (initCheck() == NO_ERROR) {
1961 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1962 } else {
1963 return 0;
1964 }
1965}
1966
1967void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1968{
1969 Mutex::Autolock _l(mLock);
1970 // Don't apply master volume in SW if our HAL can do it for us.
1971 if (mOutput && mOutput->audioHwDev &&
1972 mOutput->audioHwDev->canSetMasterVolume()) {
1973 mMasterVolume = 1.0;
1974 } else {
1975 mMasterVolume = value;
1976 }
1977}
1978
1979void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1980{
1981 Mutex::Autolock _l(mLock);
1982 // Don't apply master mute in SW if our HAL can do it for us.
1983 if (mOutput && mOutput->audioHwDev &&
1984 mOutput->audioHwDev->canSetMasterMute()) {
1985 mMasterMute = false;
1986 } else {
1987 mMasterMute = muted;
1988 }
1989}
1990
1991void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1992{
1993 Mutex::Autolock _l(mLock);
1994 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001995 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001996}
1997
1998void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1999{
2000 Mutex::Autolock _l(mLock);
2001 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002002 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002003}
2004
2005float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2006{
2007 Mutex::Autolock _l(mLock);
2008 return mStreamTypes[stream].volume;
2009}
2010
2011// addTrack_l() must be called with ThreadBase::mLock held
2012status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2013{
2014 status_t status = ALREADY_EXISTS;
2015
Eric Laurent81784c32012-11-19 14:55:58 -08002016 if (mActiveTracks.indexOf(track) < 0) {
2017 // the track is newly added, make sure it fills up all its
2018 // buffers before playing. This is to ensure the client will
2019 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002020 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002021 TrackBase::track_state state = track->mState;
2022 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002023 status = AudioSystem::startOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002024 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002025 mLock.lock();
2026 // abort track was stopped/paused while we released the lock
2027 if (state != track->mState) {
2028 if (status == NO_ERROR) {
2029 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002030 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002031 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002032 mLock.lock();
2033 }
2034 return INVALID_OPERATION;
2035 }
2036 // abort if start is rejected by audio policy manager
2037 if (status != NO_ERROR) {
2038 return PERMISSION_DENIED;
2039 }
2040#ifdef ADD_BATTERY_DATA
2041 // to track the speaker usage
2042 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2043#endif
2044 }
2045
Eric Laurent51716182016-02-29 18:00:56 -08002046 // set retry count for buffer fill
2047 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002048 if (track->isStopping_1()) {
2049 track->mRetryCount = kMaxTrackStopRetriesOffload;
2050 } else {
2051 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2052 }
2053 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002054 } else {
2055 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002056 track->mFillingUpStatus =
2057 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002058 }
2059
Eric Laurent81784c32012-11-19 14:55:58 -08002060 track->mResetDone = false;
2061 track->mPresentationCompleteFrames = 0;
2062 mActiveTracks.add(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002063 mWakeLockUids.add(track->uid());
2064 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07002065 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07002066 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2067 if (chain != 0) {
2068 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2069 track->sessionId());
2070 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002071 }
2072
2073 status = NO_ERROR;
2074 }
2075
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002076 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002077 return status;
2078}
2079
Eric Laurentbfb1b832013-01-07 09:53:42 -08002080bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002081{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002082 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002083 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002084 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2085 track->mState = TrackBase::STOPPED;
2086 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002087 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002088 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002089 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002090 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002091
2092 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002093}
2094
2095void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2096{
2097 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
2098 mTracks.remove(track);
2099 deleteTrackName_l(track->name());
2100 // redundant as track is about to be destroyed, for dumpsys only
2101 track->mName = -1;
2102 if (track->isFastTrack()) {
2103 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002104 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002105 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2106 mFastTrackAvailMask |= 1 << index;
2107 // redundant as track is about to be destroyed, for dumpsys only
2108 track->mFastIndex = -1;
2109 }
2110 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2111 if (chain != 0) {
2112 chain->decTrackCnt();
2113 }
2114}
2115
Eric Laurentede6c3b2013-09-19 14:37:46 -07002116void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002117{
2118 // Thread could be blocked waiting for async
2119 // so signal it to handle state changes immediately
2120 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
2121 // be lost so we also flag to prevent it blocking on mWaitWorkCV
2122 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002123 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002124}
2125
Eric Laurent81784c32012-11-19 14:55:58 -08002126String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2127{
Eric Laurent81784c32012-11-19 14:55:58 -08002128 Mutex::Autolock _l(mLock);
2129 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07002130 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002131 }
2132
Glenn Kastend8ea6992013-07-16 14:17:15 -07002133 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
2134 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08002135 free(s);
2136 return out_s8;
2137}
2138
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002139void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002140 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2141 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002142
Eric Laurent73e26b62015-04-27 16:55:58 -07002143 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002144
2145 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002146 case AUDIO_OUTPUT_OPENED:
2147 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002148 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002149 desc->mChannelMask = mChannelMask;
2150 desc->mSamplingRate = mSampleRate;
2151 desc->mFormat = mFormat;
2152 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002153 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002154 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002155 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002156 break;
2157
Eric Laurent73e26b62015-04-27 16:55:58 -07002158 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002159 default:
2160 break;
2161 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002162 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002163}
2164
Eric Laurentbfb1b832013-01-07 09:53:42 -08002165void AudioFlinger::PlaybackThread::writeCallback()
2166{
2167 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002168 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002169}
2170
2171void AudioFlinger::PlaybackThread::drainCallback()
2172{
2173 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002174 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002175}
2176
Eric Laurent3b4529e2013-09-05 18:09:19 -07002177void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002178{
2179 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002180 // reject out of sequence requests
2181 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2182 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002183 mWaitWorkCV.signal();
2184 }
2185}
2186
Eric Laurent3b4529e2013-09-05 18:09:19 -07002187void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002188{
2189 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002190 // reject out of sequence requests
2191 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
2192 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002193 mWaitWorkCV.signal();
2194 }
2195}
2196
2197// static
2198int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
Glenn Kasten0f11b512014-01-31 16:18:54 -08002199 void *param __unused,
Eric Laurentbfb1b832013-01-07 09:53:42 -08002200 void *cookie)
2201{
2202 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
2203 ALOGV("asyncCallback() event %d", event);
2204 switch (event) {
2205 case STREAM_CBK_EVENT_WRITE_READY:
2206 me->writeCallback();
2207 break;
2208 case STREAM_CBK_EVENT_DRAIN_READY:
2209 me->drainCallback();
2210 break;
2211 default:
2212 ALOGW("asyncCallback() unknown event %d", event);
2213 break;
2214 }
2215 return 0;
2216}
2217
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002218void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002219{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002220 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002221 mSampleRate = mOutput->getSampleRate();
2222 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002223 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002224 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002225 }
Andy Hung9a592762014-07-21 21:56:01 -07002226 if ((mType == MIXER || mType == DUPLICATING)
2227 && !isValidPcmSinkChannelMask(mChannelMask)) {
2228 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2229 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002230 }
Andy Hunge5412692014-05-16 11:25:07 -07002231 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002232
2233 // Get actual HAL format.
Andy Hung463be252014-07-10 16:56:07 -07002234 mHALFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Phil Burkca5e6142015-07-14 09:42:29 -07002235 // Get format from the shim, which will be different than the HAL format
2236 // if playing compressed audio over HDMI passthrough.
2237 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002238 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002239 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002240 }
Andy Hung6146c082014-03-18 11:56:15 -07002241 if ((mType == MIXER || mType == DUPLICATING)
2242 && !isValidPcmSinkFormat(mFormat)) {
2243 LOG_FATAL("HAL format %#x not supported for mixed output",
2244 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002245 }
Phil Burk062e67a2015-02-11 13:40:50 -08002246 mFrameSize = mOutput->getFrameSize();
Glenn Kasten70949c42013-08-06 07:40:12 -07002247 mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
2248 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002249 if (mFrameCount & 15) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002250 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002251 mFrameCount);
2252 }
2253
Eric Laurentbfb1b832013-01-07 09:53:42 -08002254 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
2255 (mOutput->stream->set_callback != NULL)) {
2256 if (mOutput->stream->set_callback(mOutput->stream,
2257 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
2258 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002259 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002260 }
2261 }
2262
Eric Laurentd1f69b02014-12-15 14:33:13 -08002263 mHwSupportsPause = false;
2264 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
2265 if (mOutput->stream->pause != NULL) {
2266 if (mOutput->stream->resume != NULL) {
2267 mHwSupportsPause = true;
2268 } else {
2269 ALOGW("direct output implements pause but not resume");
2270 }
2271 } else if (mOutput->stream->resume != NULL) {
2272 ALOGW("direct output implements resume but not pause");
2273 }
2274 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002275 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2276 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2277 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002278
Andy Hungfbfc3952015-01-15 13:33:51 -08002279 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2280 // For best precision, we use float instead of the associated output
2281 // device format (typically PCM 16 bit).
2282
2283 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2284 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2285 mBufferSize = mFrameSize * mFrameCount;
2286
2287 // TODO: We currently use the associated output device channel mask and sample rate.
2288 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2289 // (if a valid mask) to avoid premature downmix.
2290 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2291 // instead of the output device sample rate to avoid loss of high frequency information.
2292 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2293 }
2294
Andy Hung09a50072014-02-27 14:30:47 -08002295 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002296 double multiplier = 1.0;
2297 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2298 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002299 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2300 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002301
Eric Laurent81784c32012-11-19 14:55:58 -08002302 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2303 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2304 maxNormalFrameCount = maxNormalFrameCount & ~15;
2305 if (maxNormalFrameCount < minNormalFrameCount) {
2306 maxNormalFrameCount = minNormalFrameCount;
2307 }
2308 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2309 if (multiplier <= 1.0) {
2310 multiplier = 1.0;
2311 } else if (multiplier <= 2.0) {
2312 if (2 * mFrameCount <= maxNormalFrameCount) {
2313 multiplier = 2.0;
2314 } else {
2315 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2316 }
2317 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002318 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002319 }
2320 }
2321 mNormalFrameCount = multiplier * mFrameCount;
2322 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002323 if (mType == MIXER || mType == DUPLICATING) {
2324 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2325 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002326 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002327 mNormalFrameCount);
2328
Andy Hung08fb1742015-05-31 23:22:10 -07002329 // Check if we want to throttle the processing to no more than 2x normal rate
2330 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002331 mThreadThrottleTimeMs = 0;
2332 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002333 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2334
Andy Hung010a1a12014-03-13 13:57:33 -07002335 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2336 // Originally this was int16_t[] array, need to remove legacy implications.
2337 free(mSinkBuffer);
2338 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002339 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2340 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2341 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002342 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002343
Andy Hung69aed5f2014-02-25 17:24:40 -08002344 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2345 // drives the output.
2346 free(mMixerBuffer);
2347 mMixerBuffer = NULL;
2348 if (mMixerBufferEnabled) {
2349 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2350 mMixerBufferSize = mNormalFrameCount * mChannelCount
2351 * audio_bytes_per_sample(mMixerBufferFormat);
2352 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2353 }
Andy Hung98ef9782014-03-04 14:46:50 -08002354 free(mEffectBuffer);
2355 mEffectBuffer = NULL;
2356 if (mEffectBufferEnabled) {
2357 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2358 mEffectBufferSize = mNormalFrameCount * mChannelCount
2359 * audio_bytes_per_sample(mEffectBufferFormat);
2360 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2361 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002362
Eric Laurent81784c32012-11-19 14:55:58 -08002363 // force reconfiguration of effect chains and engines to take new buffer size and audio
2364 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002365 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002366 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2367 // matter.
2368 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2369 Vector< sp<EffectChain> > effectChains = mEffectChains;
2370 for (size_t i = 0; i < effectChains.size(); i ++) {
2371 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2372 }
2373}
2374
2375
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002376status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002377{
2378 if (halFrames == NULL || dspFrames == NULL) {
2379 return BAD_VALUE;
2380 }
2381 Mutex::Autolock _l(mLock);
2382 if (initCheck() != NO_ERROR) {
2383 return INVALID_OPERATION;
2384 }
Andy Hung818e7a32016-02-16 18:08:07 -08002385 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002386 *halFrames = framesWritten;
2387
2388 if (isSuspended()) {
2389 // return an estimation of rendered frames when the output is suspended
2390 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002391 *dspFrames = (uint32_t)
2392 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002393 return NO_ERROR;
2394 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002395 status_t status;
2396 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002397 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002398 *dspFrames = (size_t)frames;
2399 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002400 }
2401}
2402
Glenn Kastend848eb42016-03-08 13:42:11 -08002403uint32_t AudioFlinger::PlaybackThread::hasAudioSession(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08002404{
2405 Mutex::Autolock _l(mLock);
2406 uint32_t result = 0;
2407 if (getEffectChain_l(sessionId) != 0) {
2408 result = EFFECT_SESSION;
2409 }
2410
2411 for (size_t i = 0; i < mTracks.size(); ++i) {
2412 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002413 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002414 result |= TRACK_SESSION;
2415 break;
2416 }
2417 }
2418
2419 return result;
2420}
2421
Glenn Kastend848eb42016-03-08 13:42:11 -08002422uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08002423{
2424 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2425 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2426 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2427 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2428 }
2429 for (size_t i = 0; i < mTracks.size(); i++) {
2430 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002431 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002432 return AudioSystem::getStrategyForStream(track->streamType());
2433 }
2434 }
2435 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2436}
2437
2438
Phil Burk062e67a2015-02-11 13:40:50 -08002439AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002440{
2441 Mutex::Autolock _l(mLock);
2442 return mOutput;
2443}
2444
Phil Burk062e67a2015-02-11 13:40:50 -08002445AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002446{
2447 Mutex::Autolock _l(mLock);
2448 AudioStreamOut *output = mOutput;
2449 mOutput = NULL;
2450 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2451 // must push a NULL and wait for ack
2452 mOutputSink.clear();
2453 mPipeSink.clear();
2454 mNormalSink.clear();
2455 return output;
2456}
2457
2458// this method must always be called either with ThreadBase mLock held or inside the thread loop
2459audio_stream_t* AudioFlinger::PlaybackThread::stream() const
2460{
2461 if (mOutput == NULL) {
2462 return NULL;
2463 }
2464 return &mOutput->stream->common;
2465}
2466
2467uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2468{
2469 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2470}
2471
2472status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2473{
2474 if (!isValidSyncEvent(event)) {
2475 return BAD_VALUE;
2476 }
2477
2478 Mutex::Autolock _l(mLock);
2479
2480 for (size_t i = 0; i < mTracks.size(); ++i) {
2481 sp<Track> track = mTracks[i];
2482 if (event->triggerSession() == track->sessionId()) {
2483 (void) track->setSyncEvent(event);
2484 return NO_ERROR;
2485 }
2486 }
2487
2488 return NAME_NOT_FOUND;
2489}
2490
2491bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2492{
2493 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2494}
2495
2496void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2497 const Vector< sp<Track> >& tracksToRemove)
2498{
2499 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002500 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002501 for (size_t i = 0 ; i < count ; i++) {
2502 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002503 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002504 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002505 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002506#ifdef ADD_BATTERY_DATA
2507 // to track the speaker usage
2508 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2509#endif
2510 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002511 AudioSystem::releaseOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002512 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002513 }
Eric Laurent81784c32012-11-19 14:55:58 -08002514 }
2515 }
2516 }
Eric Laurent81784c32012-11-19 14:55:58 -08002517}
2518
2519void AudioFlinger::PlaybackThread::checkSilentMode_l()
2520{
2521 if (!mMasterMute) {
2522 char value[PROPERTY_VALUE_MAX];
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07002523 if (mOutDevice == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) {
2524 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
2525 return;
2526 }
Eric Laurent81784c32012-11-19 14:55:58 -08002527 if (property_get("ro.audio.silent", value, "0") > 0) {
2528 char *endptr;
2529 unsigned long ul = strtoul(value, &endptr, 0);
2530 if (*endptr == '\0' && ul != 0) {
2531 ALOGD("Silence is golden");
2532 // The setprop command will not allow a property to be changed after
2533 // the first time it is set, so we don't have to worry about un-muting.
2534 setMasterMute_l(true);
2535 }
2536 }
2537 }
2538}
2539
2540// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002541ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002542{
Eric Laurent81784c32012-11-19 14:55:58 -08002543 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002544 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002545 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002546
2547 // If an NBAIO sink is present, use it to write the normal mixer's submix
2548 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002549
Andy Hung010a1a12014-03-13 13:57:33 -07002550 const size_t count = mBytesRemaining / mFrameSize;
2551
Simon Wilson2d590962012-11-29 15:18:50 -08002552 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002553 // update the setpoint when AudioFlinger::mScreenState changes
2554 uint32_t screenState = AudioFlinger::mScreenState;
2555 if (screenState != mScreenState) {
2556 mScreenState = screenState;
2557 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2558 if (pipe != NULL) {
2559 pipe->setAvgFrames((mScreenState & 1) ?
2560 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2561 }
2562 }
Andy Hung010a1a12014-03-13 13:57:33 -07002563 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002564 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002565 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002566 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002567 } else {
2568 bytesWritten = framesWritten;
2569 }
2570 // otherwise use the HAL / AudioStreamOut directly
2571 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002572 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002573
Eric Laurentbfb1b832013-01-07 09:53:42 -08002574 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002575 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2576 mWriteAckSequence += 2;
2577 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002578 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002579 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002580 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002581 // FIXME We should have an implementation of timestamps for direct output threads.
2582 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002583 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurent51716182016-02-29 18:00:56 -08002584
Eric Laurentbfb1b832013-01-07 09:53:42 -08002585 if (mUseAsyncWrite &&
2586 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2587 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002588 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002589 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002590 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002591 }
Eric Laurent81784c32012-11-19 14:55:58 -08002592 }
2593
Eric Laurent81784c32012-11-19 14:55:58 -08002594 mNumWrites++;
2595 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002596 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002597 return bytesWritten;
2598}
2599
2600void AudioFlinger::PlaybackThread::threadLoop_drain()
2601{
2602 if (mOutput->stream->drain) {
2603 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2604 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002605 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2606 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002607 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002608 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002609 }
2610 mOutput->stream->drain(mOutput->stream,
2611 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2612 : AUDIO_DRAIN_ALL);
2613 }
2614}
2615
2616void AudioFlinger::PlaybackThread::threadLoop_exit()
2617{
Eric Laurent275e8e92014-11-30 15:14:47 -08002618 {
2619 Mutex::Autolock _l(mLock);
2620 for (size_t i = 0; i < mTracks.size(); i++) {
2621 sp<Track> track = mTracks[i];
2622 track->invalidate();
2623 }
2624 }
Eric Laurent81784c32012-11-19 14:55:58 -08002625}
2626
2627/*
2628The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002629 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002630 - mActiveSleepTimeUs from activeSleepTimeUs()
2631 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08002632 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
2633 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08002634 - maxPeriod from frame count and sample rate (MIXER only)
2635
2636The parameters that affect these derived values are:
2637 - frame count
2638 - frame size
2639 - sample rate
2640 - device type: A2DP or not
2641 - device latency
2642 - format: PCM or not
2643 - active sleep time
2644 - idle sleep time
2645*/
2646
2647void AudioFlinger::PlaybackThread::cacheParameters_l()
2648{
Andy Hung25c2dac2014-02-27 14:56:00 -08002649 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002650 mActiveSleepTimeUs = activeSleepTimeUs();
2651 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08002652
2653 // make sure standby delay is not too short when connected to an A2DP sink to avoid
2654 // truncating audio when going to standby.
2655 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
2656 if ((mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != 0) {
2657 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
2658 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
2659 }
2660 }
Eric Laurent81784c32012-11-19 14:55:58 -08002661}
2662
Eric Laurent13084622016-05-17 10:51:49 -07002663bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08002664{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002665 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08002666 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07002667 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002668 size_t size = mTracks.size();
2669 for (size_t i = 0; i < size; i++) {
2670 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07002671 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002672 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07002673 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002674 }
2675 }
Eric Laurent13084622016-05-17 10:51:49 -07002676 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08002677}
2678
Haynes Mathew George05317d22016-05-03 16:34:26 -07002679void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2680{
2681 Mutex::Autolock _l(mLock);
2682 invalidateTracks_l(streamType);
2683}
2684
Eric Laurent81784c32012-11-19 14:55:58 -08002685status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2686{
Glenn Kastend848eb42016-03-08 13:42:11 -08002687 audio_session_t session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002688 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2689 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002690 bool ownsBuffer = false;
2691
2692 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Glenn Kastend848eb42016-03-08 13:42:11 -08002693 if (session > AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002694 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002695 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002696 if (mType != DIRECT) {
2697 size_t numSamples = mNormalFrameCount * mChannelCount;
2698 buffer = new int16_t[numSamples];
2699 memset(buffer, 0, numSamples * sizeof(int16_t));
2700 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2701 ownsBuffer = true;
2702 }
2703
2704 // Attach all tracks with same session ID to this chain.
2705 for (size_t i = 0; i < mTracks.size(); ++i) {
2706 sp<Track> track = mTracks[i];
2707 if (session == track->sessionId()) {
2708 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2709 buffer);
2710 track->setMainBuffer(buffer);
2711 chain->incTrackCnt();
2712 }
2713 }
2714
2715 // indicate all active tracks in the chain
2716 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2717 sp<Track> track = mActiveTracks[i].promote();
2718 if (track == 0) {
2719 continue;
2720 }
2721 if (session == track->sessionId()) {
2722 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2723 chain->incActiveTrackCnt();
2724 }
2725 }
2726 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002727 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08002728 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002729 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2730 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002731 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Glenn Kastend848eb42016-03-08 13:42:11 -08002732 // chains list in order to be processed last as it contains output stage effects.
Eric Laurent81784c32012-11-19 14:55:58 -08002733 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2734 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08002735 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08002736 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08002737 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08002738 // Effect chain for other sessions are inserted at beginning of effect
2739 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08002740 // sessions is not important.
2741 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
2742 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX,
2743 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08002744 size_t size = mEffectChains.size();
2745 size_t i = 0;
2746 for (i = 0; i < size; i++) {
2747 if (mEffectChains[i]->sessionId() < session) {
2748 break;
2749 }
2750 }
2751 mEffectChains.insertAt(chain, i);
2752 checkSuspendOnAddEffectChain_l(chain);
2753
2754 return NO_ERROR;
2755}
2756
2757size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2758{
Glenn Kastend848eb42016-03-08 13:42:11 -08002759 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08002760
2761 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2762
2763 for (size_t i = 0; i < mEffectChains.size(); i++) {
2764 if (chain == mEffectChains[i]) {
2765 mEffectChains.removeAt(i);
2766 // detach all active tracks from the chain
2767 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2768 sp<Track> track = mActiveTracks[i].promote();
2769 if (track == 0) {
2770 continue;
2771 }
2772 if (session == track->sessionId()) {
2773 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2774 chain.get(), session);
2775 chain->decActiveTrackCnt();
2776 }
2777 }
2778
2779 // detach all tracks with same session ID from this chain
2780 for (size_t i = 0; i < mTracks.size(); ++i) {
2781 sp<Track> track = mTracks[i];
2782 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002783 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002784 chain->decTrackCnt();
2785 }
2786 }
2787 break;
2788 }
2789 }
2790 return mEffectChains.size();
2791}
2792
2793status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2794 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2795{
2796 Mutex::Autolock _l(mLock);
2797 return attachAuxEffect_l(track, EffectId);
2798}
2799
2800status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2801 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2802{
2803 status_t status = NO_ERROR;
2804
2805 if (EffectId == 0) {
2806 track->setAuxBuffer(0, NULL);
2807 } else {
2808 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2809 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2810 if (effect != 0) {
2811 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2812 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2813 } else {
2814 status = INVALID_OPERATION;
2815 }
2816 } else {
2817 status = BAD_VALUE;
2818 }
2819 }
2820 return status;
2821}
2822
2823void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2824{
2825 for (size_t i = 0; i < mTracks.size(); ++i) {
2826 sp<Track> track = mTracks[i];
2827 if (track->auxEffectId() == effectId) {
2828 attachAuxEffect_l(track, 0);
2829 }
2830 }
2831}
2832
2833bool AudioFlinger::PlaybackThread::threadLoop()
2834{
2835 Vector< sp<Track> > tracksToRemove;
2836
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002837 mStandbyTimeNs = systemTime();
Andy Hung69488c42016-05-16 18:43:33 -07002838 nsecs_t lastWriteFinished = -1; // time last server write completed
2839 int64_t lastFramesWritten = -1; // track changes in timestamp server frames written
Eric Laurent81784c32012-11-19 14:55:58 -08002840
2841 // MIXER
2842 nsecs_t lastWarning = 0;
2843
2844 // DUPLICATING
2845 // FIXME could this be made local to while loop?
2846 writeFrames = 0;
2847
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002848 int lastGeneration = 0;
2849
Eric Laurent81784c32012-11-19 14:55:58 -08002850 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002851 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002852
2853 if (mType == MIXER) {
2854 sleepTimeShift = 0;
2855 }
2856
2857 CpuStats cpuStats;
2858 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2859
2860 acquireWakeLock();
2861
Glenn Kasten9e58b552013-01-18 15:09:48 -08002862 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2863 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2864 // and then that string will be logged at the next convenient opportunity.
2865 const char *logString = NULL;
2866
Eric Laurent664539d2013-09-23 18:24:31 -07002867 checkSilentMode_l();
2868
Eric Laurent81784c32012-11-19 14:55:58 -08002869 while (!exitPending())
2870 {
2871 cpuStats.sample(myName);
2872
2873 Vector< sp<EffectChain> > effectChains;
2874
Eric Laurent81784c32012-11-19 14:55:58 -08002875 { // scope for mLock
2876
2877 Mutex::Autolock _l(mLock);
2878
Eric Laurent021cf962014-05-13 10:18:14 -07002879 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002880
Glenn Kasten9e58b552013-01-18 15:09:48 -08002881 if (logString != NULL) {
2882 mNBLogWriter->logTimestamp();
2883 mNBLogWriter->log(logString);
2884 logString = NULL;
2885 }
2886
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002887 // Gather the framesReleased counters for all active tracks,
Andy Hunge10393e2015-06-12 13:59:33 -07002888 // and associate with the sink frames written out. We need
2889 // this to convert the sink timestamp to the track timestamp.
Andy Hung69488c42016-05-16 18:43:33 -07002890 bool kernelLocationUpdate = false;
Andy Hunge10393e2015-06-12 13:59:33 -07002891 if (mNormalSink != 0) {
Andy Hungc54b1ff2016-02-23 14:07:07 -08002892 // Note: The DuplicatingThread may not have a mNormalSink.
Andy Hung818e7a32016-02-16 18:08:07 -08002893 // We always fetch the timestamp here because often the downstream
Andy Hung69488c42016-05-16 18:43:33 -07002894 // sink will block while writing.
Andy Hung818e7a32016-02-16 18:08:07 -08002895 ExtendedTimestamp timestamp; // use private copy to fetch
2896 (void) mNormalSink->getTimestamp(timestamp);
Andy Hung6d7b1192016-05-07 22:59:48 -07002897
2898 // We keep track of the last valid kernel position in case we are in underrun
2899 // and the normal mixer period is the same as the fast mixer period, or there
2900 // is some error from the HAL.
2901 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
2902 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
2903 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
2904 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
2905 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
2906
2907 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
2908 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
2909 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
2910 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
Andy Hung69488c42016-05-16 18:43:33 -07002911 }
2912
2913 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
2914 kernelLocationUpdate = true;
Andy Hung6d7b1192016-05-07 22:59:48 -07002915 } else {
2916 ALOGV("getTimestamp error - no valid kernel position");
2917 }
2918
Andy Hung818e7a32016-02-16 18:08:07 -08002919 // copy over kernel info
2920 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
2921 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
2922 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
2923 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hungc54b1ff2016-02-23 14:07:07 -08002924 }
2925 // mFramesWritten for non-offloaded tracks are contiguous
2926 // even after standby() is called. This is useful for the track frame
2927 // to sink frame mapping.
Andy Hung69488c42016-05-16 18:43:33 -07002928 bool serverLocationUpdate = false;
2929 if (mFramesWritten != lastFramesWritten) {
2930 serverLocationUpdate = true;
2931 lastFramesWritten = mFramesWritten;
2932 }
2933 // Only update timestamps if there is a meaningful change.
2934 // Either the kernel timestamp must be valid or we have written something.
2935 if (kernelLocationUpdate || serverLocationUpdate) {
2936 if (serverLocationUpdate) {
2937 // use the time before we called the HAL write - it is a bit more accurate
2938 // to when the server last read data than the current time here.
2939 //
2940 // If we haven't written anything, mLastWriteTime will be -1
2941 // and we use systemTime().
2942 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
2943 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastWriteTime == -1
2944 ? systemTime() : mLastWriteTime;
2945 }
2946 const size_t size = mActiveTracks.size();
2947 for (size_t i = 0; i < size; ++i) {
2948 sp<Track> t = mActiveTracks[i].promote();
2949 if (t != 0 && !t->isFastTrack()) {
2950 t->updateTrackFrameInfo(
2951 t->mAudioTrackServerProxy->framesReleased(),
2952 mFramesWritten,
2953 mTimestamp);
2954 }
Andy Hunge10393e2015-06-12 13:59:33 -07002955 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002956 }
2957
Eric Laurent81784c32012-11-19 14:55:58 -08002958 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002959 if (mSignalPending) {
2960 // A signal was raised while we were unlocked
2961 mSignalPending = false;
2962 } else if (waitingAsyncCallback_l()) {
2963 if (exitPending()) {
2964 break;
2965 }
Marco Nelissen078538c2015-05-12 09:17:57 -07002966 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07002967 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07002968 releaseWakeLock_l();
2969 released = true;
2970 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002971 mWakeLockUids.clear();
2972 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002973 ALOGV("wait async completion");
2974 mWaitWorkCV.wait(mLock);
2975 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07002976 if (released) {
2977 acquireWakeLock_l();
2978 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002979 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
2980 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002981
2982 continue;
2983 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002984 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002985 isSuspended()) {
2986 // put audio hardware into standby after short delay
2987 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002988
2989 threadLoop_standby();
2990
2991 mStandby = true;
2992 }
2993
2994 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2995 // we're about to wait, flush the binder command buffer
2996 IPCThreadState::self()->flushCommands();
2997
2998 clearOutputTracks();
2999
3000 if (exitPending()) {
3001 break;
3002 }
3003
3004 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003005 mWakeLockUids.clear();
3006 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08003007 // wait until we have something to do...
3008 ALOGV("%s going to sleep", myName.string());
3009 mWaitWorkCV.wait(mLock);
3010 ALOGV("%s waking up", myName.string());
3011 acquireWakeLock_l();
3012
3013 mMixerStatus = MIXER_IDLE;
3014 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3015 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003016 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003017 checkSilentMode_l();
3018
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003019 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3020 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003021 if (mType == MIXER) {
3022 sleepTimeShift = 0;
3023 }
3024
3025 continue;
3026 }
3027 }
Eric Laurent81784c32012-11-19 14:55:58 -08003028 // mMixerStatusIgnoringFastTracks is also updated internally
3029 mMixerStatus = prepareTracks_l(&tracksToRemove);
3030
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003031 // compare with previously applied list
3032 if (lastGeneration != mActiveTracksGeneration) {
3033 // update wakelock
3034 updateWakeLockUids_l(mWakeLockUids);
3035 lastGeneration = mActiveTracksGeneration;
3036 }
3037
Eric Laurent81784c32012-11-19 14:55:58 -08003038 // prevent any changes in effect chain list and in each effect chain
3039 // during mixing and effect process as the audio buffers could be deleted
3040 // or modified if an effect is created or deleted
3041 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003042 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003043
Eric Laurentbfb1b832013-01-07 09:53:42 -08003044 if (mBytesRemaining == 0) {
3045 mCurrentWriteLength = 0;
3046 if (mMixerStatus == MIXER_TRACKS_READY) {
3047 // threadLoop_mix() sets mCurrentWriteLength
3048 threadLoop_mix();
3049 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3050 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003051 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003052 // must be written to HAL
3053 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003054 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003055 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003056 }
3057 }
Andy Hung98ef9782014-03-04 14:46:50 -08003058 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003059 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003060 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3061 // or mSinkBuffer (if there are no effects).
3062 //
3063 // This is done pre-effects computation; if effects change to
3064 // support higher precision, this needs to move.
3065 //
3066 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003067 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003068 if (mMixerBufferValid) {
3069 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3070 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3071
Andy Hung2ddee192015-12-18 17:34:44 -08003072 // mono blend occurs for mixer threads only (not direct or offloaded)
3073 // and is handled here if we're going directly to the sink.
3074 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003075 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3076 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003077 }
3078
Andy Hung98ef9782014-03-04 14:46:50 -08003079 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
3080 mNormalFrameCount * mChannelCount);
3081 }
3082
Eric Laurentbfb1b832013-01-07 09:53:42 -08003083 mBytesRemaining = mCurrentWriteLength;
3084 if (isSuspended()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003085 mSleepTimeUs = suspendSleepTimeUs();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003086 // simulate write to HAL when suspended
Andy Hung25c2dac2014-02-27 14:56:00 -08003087 mBytesWritten += mSinkBufferSize;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003088 mFramesWritten += mSinkBufferSize / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003089 mBytesRemaining = 0;
3090 }
Eric Laurent81784c32012-11-19 14:55:58 -08003091
Eric Laurentbfb1b832013-01-07 09:53:42 -08003092 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003093 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003094 for (size_t i = 0; i < effectChains.size(); i ++) {
3095 effectChains[i]->process_l();
3096 }
Eric Laurent81784c32012-11-19 14:55:58 -08003097 }
3098 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003099 // Process effect chains for offloaded thread even if no audio
3100 // was read from audio track: process only updates effect state
3101 // and thus does have to be synchronized with audio writes but may have
3102 // to be called while waiting for async write callback
3103 if (mType == OFFLOAD) {
3104 for (size_t i = 0; i < effectChains.size(); i ++) {
3105 effectChains[i]->process_l();
3106 }
3107 }
Eric Laurent81784c32012-11-19 14:55:58 -08003108
Andy Hung98ef9782014-03-04 14:46:50 -08003109 // Only if the Effects buffer is enabled and there is data in the
3110 // Effects buffer (buffer valid), we need to
3111 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003112 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003113 if (mEffectBufferValid) {
3114 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003115
3116 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003117 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3118 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003119 }
3120
Andy Hung98ef9782014-03-04 14:46:50 -08003121 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
3122 mNormalFrameCount * mChannelCount);
3123 }
3124
Eric Laurent81784c32012-11-19 14:55:58 -08003125 // enable changes in effect chain
3126 unlockEffectChains(effectChains);
3127
Eric Laurentbfb1b832013-01-07 09:53:42 -08003128 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003129 // mSleepTimeUs == 0 means we must write to audio hardware
3130 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003131 ssize_t ret = 0;
Andy Hung69488c42016-05-16 18:43:33 -07003132 // We save lastWriteFinished here, as previousLastWriteFinished,
3133 // for throttling. On thread start, previousLastWriteFinished will be
3134 // set to -1, which properly results in no throttling after the first write.
3135 nsecs_t previousLastWriteFinished = lastWriteFinished;
3136 nsecs_t delta = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003137 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003138 // FIXME rewrite to reduce number of system calls
3139 mLastWriteTime = systemTime(); // also used for dumpsys
Andy Hung08fb1742015-05-31 23:22:10 -07003140 ret = threadLoop_write();
Andy Hung69488c42016-05-16 18:43:33 -07003141 lastWriteFinished = systemTime();
3142 delta = lastWriteFinished - mLastWriteTime;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003143 if (ret < 0) {
3144 mBytesRemaining = 0;
3145 } else {
3146 mBytesWritten += ret;
3147 mBytesRemaining -= ret;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003148 mFramesWritten += ret / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003149 }
3150 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3151 (mMixerStatus == MIXER_DRAIN_ALL)) {
3152 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003153 }
Andy Hung08fb1742015-05-31 23:22:10 -07003154 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003155 // write blocked detection
Andy Hung08fb1742015-05-31 23:22:10 -07003156 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003157 mNumDelayedWrites++;
Andy Hung69488c42016-05-16 18:43:33 -07003158 if ((lastWriteFinished - lastWarning) > kWarningThrottleNs) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003159 ATRACE_NAME("underrun");
3160 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003161 (unsigned long long) ns2ms(delta), mNumDelayedWrites, this);
Andy Hung69488c42016-05-16 18:43:33 -07003162 lastWarning = lastWriteFinished;
Glenn Kasten4944acb2013-08-19 08:39:20 -07003163 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003164 }
Andy Hung08fb1742015-05-31 23:22:10 -07003165
3166 if (mThreadThrottle
3167 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
3168 && ret > 0) { // we wrote something
3169 // Limit MixerThread data processing to no more than twice the
3170 // expected processing rate.
3171 //
3172 // This helps prevent underruns with NuPlayer and other applications
3173 // which may set up buffers that are close to the minimum size, or use
3174 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3175 //
3176 // The throttle smooths out sudden large data drains from the device,
3177 // e.g. when it comes out of standby, which often causes problems with
3178 // (1) mixer threads without a fast mixer (which has its own warm-up)
3179 // (2) minimum buffer sized tracks (even if the track is full,
3180 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07003181 //
3182 // Total time spent in last processing cycle equals time spent in
3183 // 1. threadLoop_write, as well as time spent in
3184 // 2. threadLoop_mix (significant for heavy mixing, especially
3185 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07003186
Andy Hung69488c42016-05-16 18:43:33 -07003187 // it's OK if deltaMs is an overestimate.
3188 const int32_t deltaMs =
3189 (lastWriteFinished - previousLastWriteFinished) / 1000000;
Andy Hung08fb1742015-05-31 23:22:10 -07003190 const int32_t throttleMs = mHalfBufferMs - deltaMs;
3191 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3192 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003193 // notify of throttle start on verbose log
3194 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3195 "mixer(%p) throttle begin:"
3196 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003197 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003198 mThreadThrottleTimeMs += throttleMs;
3199 } else {
3200 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3201 if (diff > 0) {
3202 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07003203 // but prevent spamming for bluetooth
3204 ALOGD_IF(!audio_is_a2dp_out_device(outDevice()),
3205 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07003206 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3207 }
Andy Hung08fb1742015-05-31 23:22:10 -07003208 }
3209 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003210 }
Eric Laurent81784c32012-11-19 14:55:58 -08003211
Eric Laurentbfb1b832013-01-07 09:53:42 -08003212 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003213 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07003214 Mutex::Autolock _l(mLock);
3215 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
3216 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08003217 }
Glenn Kastene7754022014-10-31 12:11:26 -07003218 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003219 }
Eric Laurent81784c32012-11-19 14:55:58 -08003220 }
3221
3222 // Finally let go of removed track(s), without the lock held
3223 // since we can't guarantee the destructors won't acquire that
3224 // same lock. This will also mutate and push a new fast mixer state.
3225 threadLoop_removeTracks(tracksToRemove);
3226 tracksToRemove.clear();
3227
3228 // FIXME I don't understand the need for this here;
3229 // it was in the original code but maybe the
3230 // assignment in saveOutputTracks() makes this unnecessary?
3231 clearOutputTracks();
3232
3233 // Effect chains will be actually deleted here if they were removed from
3234 // mEffectChains list during mixing or effects processing
3235 effectChains.clear();
3236
3237 // FIXME Note that the above .clear() is no longer necessary since effectChains
3238 // is now local to this block, but will keep it for now (at least until merge done).
3239 }
3240
Eric Laurentbfb1b832013-01-07 09:53:42 -08003241 threadLoop_exit();
3242
Eric Laurentcf817a22014-08-04 20:36:31 -07003243 if (!mStandby) {
3244 threadLoop_standby();
3245 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003246 }
3247
3248 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003249 mWakeLockUids.clear();
3250 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08003251
3252 ALOGV("Thread %p type %d exiting", this, mType);
3253 return false;
3254}
3255
Eric Laurentbfb1b832013-01-07 09:53:42 -08003256// removeTracks_l() must be called with ThreadBase::mLock held
3257void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3258{
3259 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003260 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003261 for (size_t i=0 ; i<count ; i++) {
3262 const sp<Track>& track = tracksToRemove.itemAt(i);
3263 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003264 mWakeLockUids.remove(track->uid());
3265 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003266 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3267 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3268 if (chain != 0) {
3269 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3270 track->sessionId());
3271 chain->decActiveTrackCnt();
3272 }
3273 if (track->isTerminated()) {
3274 removeTrack_l(track);
3275 }
3276 }
3277 }
3278
3279}
Eric Laurent81784c32012-11-19 14:55:58 -08003280
Eric Laurentaccc1472013-09-20 09:36:34 -07003281status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3282{
3283 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08003284 ExtendedTimestamp ets;
3285 status_t status = mNormalSink->getTimestamp(ets);
3286 if (status == NO_ERROR) {
3287 status = ets.getBestTimestamp(&timestamp);
3288 }
3289 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07003290 }
Andy Hung9a1c8892014-12-03 11:37:42 -08003291 if ((mType == OFFLOAD || mType == DIRECT)
3292 && mOutput != NULL && mOutput->stream->get_presentation_position) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003293 uint64_t position64;
Phil Burk062e67a2015-02-11 13:40:50 -08003294 int ret = mOutput->getPresentationPosition(&position64, &timestamp.mTime);
Eric Laurentaccc1472013-09-20 09:36:34 -07003295 if (ret == 0) {
3296 timestamp.mPosition = (uint32_t)position64;
3297 return NO_ERROR;
3298 }
3299 }
3300 return INVALID_OPERATION;
3301}
Eric Laurent1c333e22014-05-20 10:48:17 -07003302
Eric Laurent054d9d32015-04-24 08:48:48 -07003303status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3304 audio_patch_handle_t *handle)
3305{
Glenn Kastenc05b8d72016-03-24 09:48:17 -07003306 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent054d9d32015-04-24 08:48:48 -07003307
Glenn Kastenc05b8d72016-03-24 09:48:17 -07003308 status_t status = PlaybackThread::createAudioPatch_l(patch, handle);
Eric Laurent054d9d32015-04-24 08:48:48 -07003309
3310 return status;
3311}
3312
Eric Laurent1c333e22014-05-20 10:48:17 -07003313status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3314 audio_patch_handle_t *handle)
3315{
3316 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003317
3318 // store new device and send to effects
3319 audio_devices_t type = AUDIO_DEVICE_NONE;
3320 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3321 type |= patch->sinks[i].ext.device.type;
3322 }
3323
3324#ifdef ADD_BATTERY_DATA
3325 // when changing the audio output device, call addBatteryData to notify
3326 // the change
3327 if (mOutDevice != type) {
3328 uint32_t params = 0;
3329 // check whether speaker is on
3330 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3331 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003332 }
3333
Eric Laurent054d9d32015-04-24 08:48:48 -07003334 audio_devices_t deviceWithoutSpeaker
3335 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3336 // check if any other device (except speaker) is on
3337 if (type & deviceWithoutSpeaker) {
3338 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3339 }
3340
3341 if (params != 0) {
3342 addBatteryData(params);
3343 }
3344 }
3345#endif
3346
3347 for (size_t i = 0; i < mEffectChains.size(); i++) {
3348 mEffectChains[i]->setDevice_l(type);
3349 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003350
3351 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3352 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3353 bool configChanged = mPrevOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003354 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003355 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003356
3357 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003358 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3359 status = hwDevice->create_audio_patch(hwDevice,
3360 patch->num_sources,
3361 patch->sources,
3362 patch->num_sinks,
3363 patch->sinks,
3364 handle);
3365 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003366 char *address;
3367 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3368 //FIXME: we only support address on first sink with HAL version < 3.0
3369 address = audio_device_address_to_parameter(
3370 patch->sinks[0].ext.device.type,
3371 patch->sinks[0].ext.device.address);
3372 } else {
3373 address = (char *)calloc(1, 1);
3374 }
3375 AudioParameter param = AudioParameter(String8(address));
3376 free(address);
3377 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), (int)type);
3378 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3379 param.toString().string());
3380 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003381 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003382 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003383 mPrevOutDevice = type;
Eric Laurente8726fe2015-06-26 09:39:24 -07003384 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3385 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003386 return status;
3387}
3388
Eric Laurent054d9d32015-04-24 08:48:48 -07003389status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3390{
Glenn Kastenc05b8d72016-03-24 09:48:17 -07003391 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent054d9d32015-04-24 08:48:48 -07003392
3393 status_t status = PlaybackThread::releaseAudioPatch_l(handle);
3394
Eric Laurent054d9d32015-04-24 08:48:48 -07003395 return status;
3396}
3397
Eric Laurent1c333e22014-05-20 10:48:17 -07003398status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3399{
3400 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003401
3402 mOutDevice = AUDIO_DEVICE_NONE;
3403
Eric Laurent1c333e22014-05-20 10:48:17 -07003404 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
3405 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3406 status = hwDevice->release_audio_patch(hwDevice, handle);
3407 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003408 AudioParameter param;
3409 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
3410 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3411 param.toString().string());
Eric Laurent1c333e22014-05-20 10:48:17 -07003412 }
3413 return status;
3414}
3415
Eric Laurent83b88082014-06-20 18:31:16 -07003416void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3417{
3418 Mutex::Autolock _l(mLock);
3419 mTracks.add(track);
3420}
3421
3422void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3423{
3424 Mutex::Autolock _l(mLock);
3425 destroyTrack_l(track);
3426}
3427
3428void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3429{
3430 ThreadBase::getAudioPortConfig(config);
3431 config->role = AUDIO_PORT_ROLE_SOURCE;
3432 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3433 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3434}
3435
Eric Laurent81784c32012-11-19 14:55:58 -08003436// ----------------------------------------------------------------------------
3437
3438AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003439 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3440 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003441 // mAudioMixer below
3442 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08003443 mFastMixerFutex(0),
3444 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08003445 // mOutputSink below
3446 // mPipeSink below
3447 // mNormalSink below
3448{
3449 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003450 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%zu, "
3451 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003452 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3453 mNormalFrameCount);
3454 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3455
Andy Hungfbfc3952015-01-15 13:33:51 -08003456 if (type == DUPLICATING) {
3457 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3458 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3459 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3460 return;
3461 }
Eric Laurent81784c32012-11-19 14:55:58 -08003462 // create an NBAIO sink for the HAL output stream, and negotiate
3463 mOutputSink = new AudioStreamOutSink(output->stream);
3464 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003465 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003466#if !LOG_NDEBUG
3467 ssize_t index =
3468#else
3469 (void)
3470#endif
3471 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003472 ALOG_ASSERT(index == 0);
3473
3474 // initialize fast mixer depending on configuration
3475 bool initFastMixer;
3476 switch (kUseFastMixer) {
3477 case FastMixer_Never:
3478 initFastMixer = false;
3479 break;
3480 case FastMixer_Always:
3481 initFastMixer = true;
3482 break;
3483 case FastMixer_Static:
3484 case FastMixer_Dynamic:
3485 initFastMixer = mFrameCount < mNormalFrameCount;
3486 break;
3487 }
3488 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003489 audio_format_t fastMixerFormat;
3490 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3491 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3492 } else {
3493 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3494 }
3495 if (mFormat != fastMixerFormat) {
3496 // change our Sink format to accept our intermediate precision
3497 mFormat = fastMixerFormat;
3498 free(mSinkBuffer);
3499 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3500 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3501 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3502 }
Eric Laurent81784c32012-11-19 14:55:58 -08003503
3504 // create a MonoPipe to connect our submix to FastMixer
3505 NBAIO_Format format = mOutputSink->format();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003506#ifdef TEE_SINK
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003507 NBAIO_Format origformat = format;
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003508#endif
Andy Hung1258c1a2014-05-23 21:22:17 -07003509 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07003510 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003511 format.mFormat = fastMixerFormat;
3512 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3513
Eric Laurent81784c32012-11-19 14:55:58 -08003514 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3515 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3516 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3517 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3518 const NBAIO_Format offers[1] = {format};
3519 size_t numCounterOffers = 0;
Glenn Kastenfc302fd2016-04-11 14:11:26 -07003520#if !LOG_NDEBUG || defined(TEE_SINK)
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003521 ssize_t index =
3522#else
3523 (void)
3524#endif
3525 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003526 ALOG_ASSERT(index == 0);
3527 monoPipe->setAvgFrames((mScreenState & 1) ?
3528 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3529 mPipeSink = monoPipe;
3530
Glenn Kasten46909e72013-02-26 09:20:22 -08003531#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003532 if (mTeeSinkOutputEnabled) {
3533 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003534 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3535 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003536 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003537 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003538 ALOG_ASSERT(index == 0);
3539 mTeeSink = teeSink;
3540 PipeReader *teeSource = new PipeReader(*teeSink);
3541 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003542 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003543 ALOG_ASSERT(index == 0);
3544 mTeeSource = teeSource;
3545 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003546#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003547
3548 // create fast mixer and configure it initially with just one fast track for our submix
3549 mFastMixer = new FastMixer();
3550 FastMixerStateQueue *sq = mFastMixer->sq();
3551#ifdef STATE_QUEUE_DUMP
3552 sq->setObserverDump(&mStateQueueObserverDump);
3553 sq->setMutatorDump(&mStateQueueMutatorDump);
3554#endif
3555 FastMixerState *state = sq->begin();
3556 FastTrack *fastTrack = &state->mFastTracks[0];
3557 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3558 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3559 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003560 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3561 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003562 fastTrack->mGeneration++;
3563 state->mFastTracksGen++;
3564 state->mTrackMask = 1;
3565 // fast mixer will use the HAL output sink
3566 state->mOutputSink = mOutputSink.get();
3567 state->mOutputSinkGen++;
3568 state->mFrameCount = mFrameCount;
3569 state->mCommand = FastMixerState::COLD_IDLE;
3570 // already done in constructor initialization list
3571 //mFastMixerFutex = 0;
3572 state->mColdFutexAddr = &mFastMixerFutex;
3573 state->mColdGen++;
3574 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003575#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003576 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003577#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003578 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3579 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003580 sq->end();
3581 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3582
3583 // start the fast mixer
3584 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3585 pid_t tid = mFastMixer->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003586 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003587
3588#ifdef AUDIO_WATCHDOG
3589 // create and start the watchdog
3590 mAudioWatchdog = new AudioWatchdog();
3591 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3592 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3593 tid = mAudioWatchdog->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003594 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003595#endif
3596
Eric Laurent81784c32012-11-19 14:55:58 -08003597 }
3598
3599 switch (kUseFastMixer) {
3600 case FastMixer_Never:
3601 case FastMixer_Dynamic:
3602 mNormalSink = mOutputSink;
3603 break;
3604 case FastMixer_Always:
3605 mNormalSink = mPipeSink;
3606 break;
3607 case FastMixer_Static:
3608 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3609 break;
3610 }
3611}
3612
3613AudioFlinger::MixerThread::~MixerThread()
3614{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003615 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003616 FastMixerStateQueue *sq = mFastMixer->sq();
3617 FastMixerState *state = sq->begin();
3618 if (state->mCommand == FastMixerState::COLD_IDLE) {
3619 int32_t old = android_atomic_inc(&mFastMixerFutex);
3620 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003621 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003622 }
3623 }
3624 state->mCommand = FastMixerState::EXIT;
3625 sq->end();
3626 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3627 mFastMixer->join();
3628 // Though the fast mixer thread has exited, it's state queue is still valid.
3629 // We'll use that extract the final state which contains one remaining fast track
3630 // corresponding to our sub-mix.
3631 state = sq->begin();
3632 ALOG_ASSERT(state->mTrackMask == 1);
3633 FastTrack *fastTrack = &state->mFastTracks[0];
3634 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3635 delete fastTrack->mBufferProvider;
3636 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003637 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003638#ifdef AUDIO_WATCHDOG
3639 if (mAudioWatchdog != 0) {
3640 mAudioWatchdog->requestExit();
3641 mAudioWatchdog->requestExitAndWait();
3642 mAudioWatchdog.clear();
3643 }
3644#endif
3645 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003646 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003647 delete mAudioMixer;
3648}
3649
3650
3651uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3652{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003653 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003654 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3655 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3656 }
3657 return latency;
3658}
3659
3660
3661void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3662{
3663 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3664}
3665
Eric Laurentbfb1b832013-01-07 09:53:42 -08003666ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003667{
3668 // FIXME we should only do one push per cycle; confirm this is true
3669 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003670 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003671 FastMixerStateQueue *sq = mFastMixer->sq();
3672 FastMixerState *state = sq->begin();
3673 if (state->mCommand != FastMixerState::MIX_WRITE &&
3674 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3675 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07003676
3677 // FIXME workaround for first HAL write being CPU bound on some devices
3678 ATRACE_BEGIN("write");
3679 mOutput->write((char *)mSinkBuffer, 0);
3680 ATRACE_END();
3681
Eric Laurent81784c32012-11-19 14:55:58 -08003682 int32_t old = android_atomic_inc(&mFastMixerFutex);
3683 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003684 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003685 }
3686#ifdef AUDIO_WATCHDOG
3687 if (mAudioWatchdog != 0) {
3688 mAudioWatchdog->resume();
3689 }
3690#endif
3691 }
3692 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003693#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003694 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003695 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003696#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003697 sq->end();
3698 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3699 if (kUseFastMixer == FastMixer_Dynamic) {
3700 mNormalSink = mPipeSink;
3701 }
3702 } else {
3703 sq->end(false /*didModify*/);
3704 }
3705 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003706 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003707}
3708
3709void AudioFlinger::MixerThread::threadLoop_standby()
3710{
3711 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003712 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003713 FastMixerStateQueue *sq = mFastMixer->sq();
3714 FastMixerState *state = sq->begin();
3715 if (!(state->mCommand & FastMixerState::IDLE)) {
3716 state->mCommand = FastMixerState::COLD_IDLE;
3717 state->mColdFutexAddr = &mFastMixerFutex;
3718 state->mColdGen++;
3719 mFastMixerFutex = 0;
3720 sq->end();
3721 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3722 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3723 if (kUseFastMixer == FastMixer_Dynamic) {
3724 mNormalSink = mOutputSink;
3725 }
3726#ifdef AUDIO_WATCHDOG
3727 if (mAudioWatchdog != 0) {
3728 mAudioWatchdog->pause();
3729 }
3730#endif
3731 } else {
3732 sq->end(false /*didModify*/);
3733 }
3734 }
3735 PlaybackThread::threadLoop_standby();
3736}
3737
Eric Laurentbfb1b832013-01-07 09:53:42 -08003738bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3739{
3740 return false;
3741}
3742
3743bool AudioFlinger::PlaybackThread::shouldStandby_l()
3744{
3745 return !mStandby;
3746}
3747
3748bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3749{
3750 Mutex::Autolock _l(mLock);
3751 return waitingAsyncCallback_l();
3752}
3753
Eric Laurent81784c32012-11-19 14:55:58 -08003754// shared by MIXER and DIRECT, overridden by DUPLICATING
3755void AudioFlinger::PlaybackThread::threadLoop_standby()
3756{
3757 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08003758 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003759 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003760 // discard any pending drain or write ack by incrementing sequence
3761 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3762 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003763 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003764 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3765 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003766 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003767 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003768}
3769
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003770void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3771{
3772 ALOGV("signal playback thread");
3773 broadcast_l();
3774}
3775
Eric Laurent81784c32012-11-19 14:55:58 -08003776void AudioFlinger::MixerThread::threadLoop_mix()
3777{
Eric Laurent81784c32012-11-19 14:55:58 -08003778 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08003779 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08003780 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003781 // increase sleep time progressively when application underrun condition clears.
3782 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3783 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3784 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003785 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003786 sleepTimeShift--;
3787 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003788 mSleepTimeUs = 0;
3789 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08003790 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003791
Eric Laurent81784c32012-11-19 14:55:58 -08003792}
3793
3794void AudioFlinger::MixerThread::threadLoop_sleepTime()
3795{
3796 // If no tracks are ready, sleep once for the duration of an output
3797 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003798 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003799 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003800 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
3801 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
3802 mSleepTimeUs = kMinThreadSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003803 }
3804 // reduce sleep time in case of consecutive application underruns to avoid
3805 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3806 // duration we would end up writing less data than needed by the audio HAL if
3807 // the condition persists.
3808 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3809 sleepTimeShift++;
3810 }
3811 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003812 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003813 }
3814 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003815 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3816 // before effects processing or output.
3817 if (mMixerBufferValid) {
3818 memset(mMixerBuffer, 0, mMixerBufferSize);
3819 } else {
3820 memset(mSinkBuffer, 0, mSinkBufferSize);
3821 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003822 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003823 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3824 "anticipated start");
3825 }
3826 // TODO add standby time extension fct of effect tail
3827}
3828
3829// prepareTracks_l() must be called with ThreadBase::mLock held
3830AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3831 Vector< sp<Track> > *tracksToRemove)
3832{
3833
3834 mixer_state mixerStatus = MIXER_IDLE;
3835 // find out which tracks need to be processed
3836 size_t count = mActiveTracks.size();
3837 size_t mixedTracks = 0;
3838 size_t tracksWithEffect = 0;
3839 // counts only _active_ fast tracks
3840 size_t fastTracks = 0;
3841 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3842
3843 float masterVolume = mMasterVolume;
3844 bool masterMute = mMasterMute;
3845
3846 if (masterMute) {
3847 masterVolume = 0;
3848 }
3849 // Delegate master volume control to effect in output mix effect chain if needed
3850 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3851 if (chain != 0) {
3852 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3853 chain->setVolume_l(&v, &v);
3854 masterVolume = (float)((v + (1 << 23)) >> 24);
3855 chain.clear();
3856 }
3857
3858 // prepare a new state to push
3859 FastMixerStateQueue *sq = NULL;
3860 FastMixerState *state = NULL;
3861 bool didModify = false;
3862 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003863 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003864 sq = mFastMixer->sq();
3865 state = sq->begin();
3866 }
3867
Andy Hung69aed5f2014-02-25 17:24:40 -08003868 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003869 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003870
Eric Laurent81784c32012-11-19 14:55:58 -08003871 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003872 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003873 if (t == 0) {
3874 continue;
3875 }
3876
3877 // this const just means the local variable doesn't change
3878 Track* const track = t.get();
3879
3880 // process fast tracks
3881 if (track->isFastTrack()) {
3882
3883 // It's theoretically possible (though unlikely) for a fast track to be created
3884 // and then removed within the same normal mix cycle. This is not a problem, as
3885 // the track never becomes active so it's fast mixer slot is never touched.
3886 // The converse, of removing an (active) track and then creating a new track
3887 // at the identical fast mixer slot within the same normal mix cycle,
3888 // is impossible because the slot isn't marked available until the end of each cycle.
3889 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07003890 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08003891 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3892 FastTrack *fastTrack = &state->mFastTracks[j];
3893
3894 // Determine whether the track is currently in underrun condition,
3895 // and whether it had a recent underrun.
3896 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3897 FastTrackUnderruns underruns = ftDump->mUnderruns;
3898 uint32_t recentFull = (underruns.mBitFields.mFull -
3899 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3900 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3901 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3902 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3903 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3904 uint32_t recentUnderruns = recentPartial + recentEmpty;
3905 track->mObservedUnderruns = underruns;
3906 // don't count underruns that occur while stopping or pausing
3907 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07003908 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3909 recentUnderruns > 0) {
3910 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3911 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Phil Burk2812d9e2016-01-04 10:34:30 -08003912 } else {
3913 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Eric Laurent81784c32012-11-19 14:55:58 -08003914 }
3915
3916 // This is similar to the state machine for normal tracks,
3917 // with a few modifications for fast tracks.
3918 bool isActive = true;
3919 switch (track->mState) {
3920 case TrackBase::STOPPING_1:
3921 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08003922 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003923 track->mState = TrackBase::STOPPING_2;
3924 }
3925 break;
3926 case TrackBase::PAUSING:
3927 // ramp down is not yet implemented
3928 track->setPaused();
3929 break;
3930 case TrackBase::RESUMING:
3931 // ramp up is not yet implemented
3932 track->mState = TrackBase::ACTIVE;
3933 break;
3934 case TrackBase::ACTIVE:
3935 if (recentFull > 0 || recentPartial > 0) {
3936 // track has provided at least some frames recently: reset retry count
3937 track->mRetryCount = kMaxTrackRetries;
3938 }
3939 if (recentUnderruns == 0) {
3940 // no recent underruns: stay active
3941 break;
3942 }
3943 // there has recently been an underrun of some kind
3944 if (track->sharedBuffer() == 0) {
3945 // were any of the recent underruns "empty" (no frames available)?
3946 if (recentEmpty == 0) {
3947 // no, then ignore the partial underruns as they are allowed indefinitely
3948 break;
3949 }
3950 // there has recently been an "empty" underrun: decrement the retry counter
3951 if (--(track->mRetryCount) > 0) {
3952 break;
3953 }
3954 // indicate to client process that the track was disabled because of underrun;
3955 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08003956 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08003957 // remove from active list, but state remains ACTIVE [confusing but true]
3958 isActive = false;
3959 break;
3960 }
3961 // fall through
3962 case TrackBase::STOPPING_2:
3963 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003964 case TrackBase::STOPPED:
3965 case TrackBase::FLUSHED: // flush() while active
3966 // Check for presentation complete if track is inactive
3967 // We have consumed all the buffers of this track.
3968 // This would be incomplete if we auto-paused on underrun
3969 {
3970 size_t audioHALFrames =
3971 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08003972 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003973 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
3974 // track stays in active list until presentation is complete
3975 break;
3976 }
3977 }
3978 if (track->isStopping_2()) {
3979 track->mState = TrackBase::STOPPED;
3980 }
3981 if (track->isStopped()) {
3982 // Can't reset directly, as fast mixer is still polling this track
3983 // track->reset();
3984 // So instead mark this track as needing to be reset after push with ack
3985 resetMask |= 1 << i;
3986 }
3987 isActive = false;
3988 break;
3989 case TrackBase::IDLE:
3990 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08003991 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08003992 }
3993
3994 if (isActive) {
3995 // was it previously inactive?
3996 if (!(state->mTrackMask & (1 << j))) {
3997 ExtendedAudioBufferProvider *eabp = track;
3998 VolumeProvider *vp = track;
3999 fastTrack->mBufferProvider = eabp;
4000 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08004001 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07004002 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08004003 fastTrack->mGeneration++;
4004 state->mTrackMask |= 1 << j;
4005 didModify = true;
4006 // no acknowledgement required for newly active tracks
4007 }
4008 // cache the combined master volume and stream type volume for fast mixer; this
4009 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08004010 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08004011 ++fastTracks;
4012 } else {
4013 // was it previously active?
4014 if (state->mTrackMask & (1 << j)) {
4015 fastTrack->mBufferProvider = NULL;
4016 fastTrack->mGeneration++;
4017 state->mTrackMask &= ~(1 << j);
4018 didModify = true;
4019 // If any fast tracks were removed, we must wait for acknowledgement
4020 // because we're about to decrement the last sp<> on those tracks.
4021 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4022 } else {
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08004023 LOG_ALWAYS_FATAL("fast track %d should have been active; "
4024 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
4025 j, track->mState, state->mTrackMask, recentUnderruns,
4026 track->sharedBuffer() != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004027 }
4028 tracksToRemove->add(track);
4029 // Avoids a misleading display in dumpsys
4030 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
4031 }
4032 continue;
4033 }
4034
4035 { // local variable scope to avoid goto warning
4036
4037 audio_track_cblk_t* cblk = track->cblk();
4038
4039 // The first time a track is added we wait
4040 // for all its buffers to be filled before processing it
4041 int name = track->name();
4042 // make sure that we have enough frames to mix one full buffer.
4043 // enforce this condition only once to enable draining the buffer in case the client
4044 // app does not call stop() and relies on underrun to stop:
4045 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
4046 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004047 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07004048 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004049 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004050
4051 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004052 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004053 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
4054 // add frames already consumed but not yet released by the resampler
4055 // because mAudioTrackServerProxy->framesReady() will include these frames
4056 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
4057
Eric Laurent81784c32012-11-19 14:55:58 -08004058 uint32_t minFrames = 1;
4059 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
4060 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004061 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08004062 }
Eric Laurent13e4c962013-12-20 17:36:01 -08004063
4064 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07004065 if (ATRACE_ENABLED()) {
4066 // I wish we had formatted trace names
4067 char traceName[16];
4068 strcpy(traceName, "nRdy");
4069 int name = track->name();
4070 if (AudioMixer::TRACK0 <= name &&
4071 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
4072 name -= AudioMixer::TRACK0;
4073 traceName[4] = (name / 10) + '0';
4074 traceName[5] = (name % 10) + '0';
4075 } else {
4076 traceName[4] = '?';
4077 traceName[5] = '?';
4078 }
4079 traceName[6] = '\0';
4080 ATRACE_INT(traceName, framesReady);
4081 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004082 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08004083 !track->isPaused() && !track->isTerminated())
4084 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004085 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004086
4087 mixedTracks++;
4088
Andy Hung69aed5f2014-02-25 17:24:40 -08004089 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
4090 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08004091 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08004092 if (track->mainBuffer() != mSinkBuffer &&
4093 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004094 if (mEffectBufferEnabled) {
4095 mEffectBufferValid = true; // Later can set directly.
4096 }
Eric Laurent81784c32012-11-19 14:55:58 -08004097 chain = getEffectChain_l(track->sessionId());
4098 // Delegate volume control to effect in track effect chain if needed
4099 if (chain != 0) {
4100 tracksWithEffect++;
4101 } else {
4102 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
4103 "session %d",
4104 name, track->sessionId());
4105 }
4106 }
4107
4108
4109 int param = AudioMixer::VOLUME;
4110 if (track->mFillingUpStatus == Track::FS_FILLED) {
4111 // no ramp for the first volume setting
4112 track->mFillingUpStatus = Track::FS_ACTIVE;
4113 if (track->mState == TrackBase::RESUMING) {
4114 track->mState = TrackBase::ACTIVE;
4115 param = AudioMixer::RAMP_VOLUME;
4116 }
4117 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004118 // FIXME should not make a decision based on mServer
4119 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004120 // If the track is stopped before the first frame was mixed,
4121 // do not apply ramp
4122 param = AudioMixer::RAMP_VOLUME;
4123 }
4124
4125 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07004126 uint32_t vl, vr; // in U8.24 integer format
4127 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08004128 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07004129 vl = vr = 0;
4130 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08004131 if (track->isPausing()) {
4132 track->setPaused();
4133 }
4134 } else {
4135
4136 // read original volumes with volume control
4137 float typeVolume = mStreamTypes[track->streamType()].volume;
4138 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004139 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004140 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07004141 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
4142 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08004143 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07004144 if (vlf > GAIN_FLOAT_UNITY) {
4145 ALOGV("Track left volume out of range: %.3g", vlf);
4146 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004147 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07004148 if (vrf > GAIN_FLOAT_UNITY) {
4149 ALOGV("Track right volume out of range: %.3g", vrf);
4150 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004151 }
4152 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07004153 vlf *= v;
4154 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08004155 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07004156 // then derive vl and vr as U8.24 versions for the effect chain
4157 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
4158 vl = (uint32_t) (scaleto8_24 * vlf);
4159 vr = (uint32_t) (scaleto8_24 * vrf);
4160 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08004161 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08004162 // send level comes from shared memory and so may be corrupt
4163 if (sendLevel > MAX_GAIN_INT) {
4164 ALOGV("Track send level out of range: %04X", sendLevel);
4165 sendLevel = MAX_GAIN_INT;
4166 }
Andy Hung6be49402014-05-30 10:42:03 -07004167 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4168 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08004169 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004170
Eric Laurent81784c32012-11-19 14:55:58 -08004171 // Delegate volume control to effect in track effect chain if needed
4172 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4173 // Do not ramp volume if volume is controlled by effect
4174 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08004175 // Update remaining floating point volume levels
4176 vlf = (float)vl / (1 << 24);
4177 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004178 track->mHasVolumeController = true;
4179 } else {
4180 // force no volume ramp when volume controller was just disabled or removed
4181 // from effect chain to avoid volume spike
4182 if (track->mHasVolumeController) {
4183 param = AudioMixer::VOLUME;
4184 }
4185 track->mHasVolumeController = false;
4186 }
4187
Eric Laurent81784c32012-11-19 14:55:58 -08004188 // XXX: these things DON'T need to be done each time
4189 mAudioMixer->setBufferProvider(name, track);
4190 mAudioMixer->enable(name);
4191
Andy Hung6be49402014-05-30 10:42:03 -07004192 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
4193 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
4194 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004195 mAudioMixer->setParameter(
4196 name,
4197 AudioMixer::TRACK,
4198 AudioMixer::FORMAT, (void *)track->format());
4199 mAudioMixer->setParameter(
4200 name,
4201 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004202 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004203 mAudioMixer->setParameter(
4204 name,
4205 AudioMixer::TRACK,
4206 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004207 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004208 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004209 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004210 if (reqSampleRate == 0) {
4211 reqSampleRate = mSampleRate;
4212 } else if (reqSampleRate > maxSampleRate) {
4213 reqSampleRate = maxSampleRate;
4214 }
Eric Laurent81784c32012-11-19 14:55:58 -08004215 mAudioMixer->setParameter(
4216 name,
4217 AudioMixer::RESAMPLE,
4218 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004219 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004220
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004221 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004222 mAudioMixer->setParameter(
4223 name,
4224 AudioMixer::TIMESTRETCH,
4225 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004226 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004227
Andy Hung69aed5f2014-02-25 17:24:40 -08004228 /*
4229 * Select the appropriate output buffer for the track.
4230 *
Andy Hung98ef9782014-03-04 14:46:50 -08004231 * Tracks with effects go into their own effects chain buffer
4232 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004233 *
4234 * Other tracks can use mMixerBuffer for higher precision
4235 * channel accumulation. If this buffer is enabled
4236 * (mMixerBufferEnabled true), then selected tracks will accumulate
4237 * into it.
4238 *
4239 */
4240 if (mMixerBufferEnabled
4241 && (track->mainBuffer() == mSinkBuffer
4242 || track->mainBuffer() == mMixerBuffer)) {
4243 mAudioMixer->setParameter(
4244 name,
4245 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004246 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004247 mAudioMixer->setParameter(
4248 name,
4249 AudioMixer::TRACK,
4250 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4251 // TODO: override track->mainBuffer()?
4252 mMixerBufferValid = true;
4253 } else {
4254 mAudioMixer->setParameter(
4255 name,
4256 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004257 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004258 mAudioMixer->setParameter(
4259 name,
4260 AudioMixer::TRACK,
4261 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4262 }
Eric Laurent81784c32012-11-19 14:55:58 -08004263 mAudioMixer->setParameter(
4264 name,
4265 AudioMixer::TRACK,
4266 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4267
4268 // reset retry count
4269 track->mRetryCount = kMaxTrackRetries;
4270
4271 // If one track is ready, set the mixer ready if:
4272 // - the mixer was not ready during previous round OR
4273 // - no other track is not ready
4274 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4275 mixerStatus != MIXER_TRACKS_ENABLED) {
4276 mixerStatus = MIXER_TRACKS_READY;
4277 }
4278 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004279 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hung08fb1742015-05-31 23:22:10 -07004280 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)",
4281 track, framesReady, desiredFrames);
Glenn Kasten82aaf942013-07-17 16:05:07 -07004282 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08004283 } else {
4284 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004285 }
Phil Burk2812d9e2016-01-04 10:34:30 -08004286
Eric Laurent81784c32012-11-19 14:55:58 -08004287 // clear effect chain input buffer if an active track underruns to avoid sending
4288 // previous audio buffer again to effects
4289 chain = getEffectChain_l(track->sessionId());
4290 if (chain != 0) {
4291 chain->clearInputBuffer();
4292 }
4293
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004294 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004295 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4296 track->isStopped() || track->isPaused()) {
4297 // We have consumed all the buffers of this track.
4298 // Remove it from the list of active tracks.
4299 // TODO: use actual buffer filling status instead of latency when available from
4300 // audio HAL
4301 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004302 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004303 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4304 if (track->isStopped()) {
4305 track->reset();
4306 }
4307 tracksToRemove->add(track);
4308 }
4309 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004310 // No buffers for this track. Give it a few chances to
4311 // fill a buffer, then remove it from active list.
4312 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004313 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004314 tracksToRemove->add(track);
4315 // indicate to client process that the track was disabled because of underrun;
4316 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004317 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004318 // If one track is not ready, mark the mixer also not ready if:
4319 // - the mixer was ready during previous round OR
4320 // - no other track is ready
4321 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4322 mixerStatus != MIXER_TRACKS_READY) {
4323 mixerStatus = MIXER_TRACKS_ENABLED;
4324 }
4325 }
4326 mAudioMixer->disable(name);
4327 }
4328
4329 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08004330
4331 }
4332
4333 // Push the new FastMixer state if necessary
4334 bool pauseAudioWatchdog = false;
4335 if (didModify) {
4336 state->mFastTracksGen++;
4337 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4338 if (kUseFastMixer == FastMixer_Dynamic &&
4339 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4340 state->mCommand = FastMixerState::COLD_IDLE;
4341 state->mColdFutexAddr = &mFastMixerFutex;
4342 state->mColdGen++;
4343 mFastMixerFutex = 0;
4344 if (kUseFastMixer == FastMixer_Dynamic) {
4345 mNormalSink = mOutputSink;
4346 }
4347 // If we go into cold idle, need to wait for acknowledgement
4348 // so that fast mixer stops doing I/O.
4349 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4350 pauseAudioWatchdog = true;
4351 }
Eric Laurent81784c32012-11-19 14:55:58 -08004352 }
4353 if (sq != NULL) {
4354 sq->end(didModify);
4355 sq->push(block);
4356 }
4357#ifdef AUDIO_WATCHDOG
4358 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4359 mAudioWatchdog->pause();
4360 }
4361#endif
4362
4363 // Now perform the deferred reset on fast tracks that have stopped
4364 while (resetMask != 0) {
4365 size_t i = __builtin_ctz(resetMask);
4366 ALOG_ASSERT(i < count);
4367 resetMask &= ~(1 << i);
4368 sp<Track> t = mActiveTracks[i].promote();
4369 if (t == 0) {
4370 continue;
4371 }
4372 Track* track = t.get();
4373 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4374 track->reset();
4375 }
4376
4377 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004378 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004379
Eric Laurent97d547d2014-09-02 14:45:53 -07004380 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4381 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004382 }
4383
4384 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004385 // as long as there are effects we should clear the effects buffer, to avoid
4386 // passing a non-clean buffer to the effect chain
4387 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004388 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004389 // sink or mix buffer must be cleared if all tracks are connected to an
4390 // effect chain as in this case the mixer will not write to the sink or mix buffer
4391 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004392 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4393 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004394 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004395 if (mMixerBufferValid) {
4396 memset(mMixerBuffer, 0, mMixerBufferSize);
4397 // TODO: In testing, mSinkBuffer below need not be cleared because
4398 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4399 // after mixing.
4400 //
4401 // To enforce this guarantee:
4402 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4403 // (mixedTracks == 0 && fastTracks > 0))
4404 // must imply MIXER_TRACKS_READY.
4405 // Later, we may clear buffers regardless, and skip much of this logic.
4406 }
Andy Hung98ef9782014-03-04 14:46:50 -08004407 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004408 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004409 }
4410
4411 // if any fast tracks, then status is ready
4412 mMixerStatusIgnoringFastTracks = mixerStatus;
4413 if (fastTracks > 0) {
4414 mixerStatus = MIXER_TRACKS_READY;
4415 }
4416 return mixerStatus;
4417}
4418
4419// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07004420int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
Glenn Kastend848eb42016-03-08 13:42:11 -08004421 audio_format_t format, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08004422{
Andy Hunge8a1ced2014-05-09 15:02:21 -07004423 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08004424}
4425
4426// deleteTrackName_l() must be called with ThreadBase::mLock held
4427void AudioFlinger::MixerThread::deleteTrackName_l(int name)
4428{
4429 ALOGV("remove track (%d) and delete from mixer", name);
4430 mAudioMixer->deleteTrackName(name);
4431}
4432
Eric Laurent10351942014-05-08 18:49:52 -07004433// checkForNewParameter_l() must be called with ThreadBase::mLock held
4434bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4435 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004436{
Eric Laurent81784c32012-11-19 14:55:58 -08004437 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08004438 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004439
Eric Laurent10351942014-05-08 18:49:52 -07004440 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004441
Glenn Kastenc05b8d72016-03-24 09:48:17 -07004442 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004443
Eric Laurent10351942014-05-08 18:49:52 -07004444 AudioParameter param = AudioParameter(keyValuePair);
4445 int value;
4446 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4447 reconfig = true;
4448 }
4449 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004450 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004451 status = BAD_VALUE;
4452 } else {
4453 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004454 reconfig = true;
4455 }
Eric Laurent10351942014-05-08 18:49:52 -07004456 }
4457 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004458 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004459 status = BAD_VALUE;
4460 } else {
4461 // no need to save value, since it's constant
4462 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004463 }
Eric Laurent10351942014-05-08 18:49:52 -07004464 }
4465 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4466 // do not accept frame count changes if tracks are open as the track buffer
4467 // size depends on frame count and correct behavior would not be guaranteed
4468 // if frame count is changed after track creation
4469 if (!mTracks.isEmpty()) {
4470 status = INVALID_OPERATION;
4471 } else {
4472 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004473 }
Eric Laurent10351942014-05-08 18:49:52 -07004474 }
4475 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004476#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004477 // when changing the audio output device, call addBatteryData to notify
4478 // the change
4479 if (mOutDevice != value) {
4480 uint32_t params = 0;
4481 // check whether speaker is on
4482 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4483 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004484 }
Eric Laurent10351942014-05-08 18:49:52 -07004485
4486 audio_devices_t deviceWithoutSpeaker
4487 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4488 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07004489 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07004490 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4491 }
4492
4493 if (params != 0) {
4494 addBatteryData(params);
4495 }
4496 }
Eric Laurent81784c32012-11-19 14:55:58 -08004497#endif
4498
Eric Laurent10351942014-05-08 18:49:52 -07004499 // forward device change to effects that have requested to be
4500 // aware of attached audio device.
4501 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08004502 a2dpDeviceChanged =
4503 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07004504 mOutDevice = value;
4505 for (size_t i = 0; i < mEffectChains.size(); i++) {
4506 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004507 }
4508 }
Eric Laurent10351942014-05-08 18:49:52 -07004509 }
Eric Laurent81784c32012-11-19 14:55:58 -08004510
Eric Laurent10351942014-05-08 18:49:52 -07004511 if (status == NO_ERROR) {
4512 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4513 keyValuePair.string());
4514 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004515 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004516 mStandby = true;
4517 mBytesWritten = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004518 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Eric Laurent10351942014-05-08 18:49:52 -07004519 keyValuePair.string());
Eric Laurent81784c32012-11-19 14:55:58 -08004520 }
Eric Laurent10351942014-05-08 18:49:52 -07004521 if (status == NO_ERROR && reconfig) {
4522 readOutputParameters_l();
4523 delete mAudioMixer;
4524 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4525 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004526 int name = getTrackName_l(mTracks[i]->mChannelMask,
4527 mTracks[i]->mFormat, mTracks[i]->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07004528 if (name < 0) {
4529 break;
4530 }
4531 mTracks[i]->mName = name;
4532 }
Eric Laurent73e26b62015-04-27 16:55:58 -07004533 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004534 }
Eric Laurent81784c32012-11-19 14:55:58 -08004535 }
4536
Eric Laurent42537be2016-01-08 17:16:42 -08004537 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08004538}
4539
4540
4541void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4542{
Eric Laurent81784c32012-11-19 14:55:58 -08004543 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07004544 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Elliott Hughes87cebad2014-05-22 10:14:43 -07004545 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Andy Hung2ddee192015-12-18 17:34:44 -08004546 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent81784c32012-11-19 14:55:58 -08004547
4548 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten2f90c512015-12-02 11:40:09 -08004549 // while we are dumping it. It may be inconsistent, but it won't mutate!
4550 // This is a large object so we place it on the heap.
4551 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
4552 const FastMixerDumpState *copy = new FastMixerDumpState(mFastMixerDumpState);
4553 copy->dump(fd);
4554 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08004555
4556#ifdef STATE_QUEUE_DUMP
4557 // Similar for state queue
4558 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4559 observerCopy.dump(fd);
4560 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4561 mutatorCopy.dump(fd);
4562#endif
4563
Glenn Kasten46909e72013-02-26 09:20:22 -08004564#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004565 // Write the tee output to a .wav file
4566 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08004567#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004568
4569#ifdef AUDIO_WATCHDOG
4570 if (mAudioWatchdog != 0) {
4571 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4572 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4573 wdCopy.dump(fd);
4574 }
4575#endif
4576}
4577
4578uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4579{
4580 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4581}
4582
4583uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4584{
4585 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4586}
4587
4588void AudioFlinger::MixerThread::cacheParameters_l()
4589{
4590 PlaybackThread::cacheParameters_l();
4591
4592 // FIXME: Relaxed timing because of a certain device that can't meet latency
4593 // Should be reduced to 2x after the vendor fixes the driver issue
4594 // increase threshold again due to low power audio mode. The way this warning
4595 // threshold is calculated and its usefulness should be reconsidered anyway.
4596 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4597}
4598
4599// ----------------------------------------------------------------------------
4600
4601AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07004602 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady)
4603 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08004604 // mLeftVolFloat, mRightVolFloat
4605{
4606}
4607
Eric Laurentbfb1b832013-01-07 09:53:42 -08004608AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4609 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurente93cc032016-05-05 10:15:10 -07004610 ThreadBase::type_t type, bool systemReady)
4611 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004612 // mLeftVolFloat, mRightVolFloat
4613{
4614}
4615
Eric Laurent81784c32012-11-19 14:55:58 -08004616AudioFlinger::DirectOutputThread::~DirectOutputThread()
4617{
4618}
4619
Eric Laurentbfb1b832013-01-07 09:53:42 -08004620void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
4621{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004622 float left, right;
4623
4624 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4625 left = right = 0;
4626 } else {
4627 float typeVolume = mStreamTypes[track->streamType()].volume;
4628 float v = mMasterVolume * typeVolume;
4629 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004630 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4631 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4632 if (left > GAIN_FLOAT_UNITY) {
4633 left = GAIN_FLOAT_UNITY;
4634 }
4635 left *= v;
4636 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4637 if (right > GAIN_FLOAT_UNITY) {
4638 right = GAIN_FLOAT_UNITY;
4639 }
4640 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004641 }
4642
4643 if (lastTrack) {
4644 if (left != mLeftVolFloat || right != mRightVolFloat) {
4645 mLeftVolFloat = left;
4646 mRightVolFloat = right;
4647
4648 // Convert volumes from float to 8.24
4649 uint32_t vl = (uint32_t)(left * (1 << 24));
4650 uint32_t vr = (uint32_t)(right * (1 << 24));
4651
4652 // Delegate volume control to effect in track effect chain if needed
4653 // only one effect chain can be present on DirectOutputThread, so if
4654 // there is one, the track is connected to it
4655 if (!mEffectChains.isEmpty()) {
4656 mEffectChains[0]->setVolume_l(&vl, &vr);
4657 left = (float)vl / (1 << 24);
4658 right = (float)vr / (1 << 24);
4659 }
4660 if (mOutput->stream->set_volume) {
4661 mOutput->stream->set_volume(mOutput->stream, left, right);
4662 }
4663 }
4664 }
4665}
4666
Phil Burk43b4dcc2015-06-09 16:53:44 -07004667void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
4668{
4669 sp<Track> previousTrack = mPreviousTrack.promote();
4670 sp<Track> latestTrack = mLatestActiveTrack.promote();
4671
Eric Laurent0f0631e2015-07-06 18:01:25 -07004672 if (previousTrack != 0 && latestTrack != 0) {
4673 if (mType == DIRECT) {
4674 if (previousTrack.get() != latestTrack.get()) {
4675 mFlushPending = true;
4676 }
4677 } else /* mType == OFFLOAD */ {
4678 if (previousTrack->sessionId() != latestTrack->sessionId()) {
4679 mFlushPending = true;
4680 }
4681 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004682 }
4683 PlaybackThread::onAddNewTrack_l();
4684}
Eric Laurentbfb1b832013-01-07 09:53:42 -08004685
Eric Laurent81784c32012-11-19 14:55:58 -08004686AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4687 Vector< sp<Track> > *tracksToRemove
4688)
4689{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004690 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004691 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004692 bool doHwPause = false;
4693 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004694
4695 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07004696 for (size_t i = 0; i < count; i++) {
4697 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08004698 // The track died recently
4699 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004700 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08004701 }
4702
Phil Burk43b4dcc2015-06-09 16:53:44 -07004703 if (t->isInvalid()) {
4704 ALOGW("An invalidated track shouldn't be in active list");
4705 tracksToRemove->add(t);
4706 continue;
4707 }
4708
Eric Laurent81784c32012-11-19 14:55:58 -08004709 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004710#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08004711 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004712#endif
Eric Laurentfd477972013-10-25 18:10:40 -07004713 // Only consider last track started for volume and mixer state control.
4714 // In theory an older track could underrun and restart after the new one starts
4715 // but as we only care about the transition phase between two tracks on a
4716 // direct output, it is not a problem to ignore the underrun case.
4717 sp<Track> l = mLatestActiveTrack.promote();
4718 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004719
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004720 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004721 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004722 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004723 doHwPause = true;
4724 mHwPaused = true;
4725 }
4726 tracksToRemove->add(track);
4727 } else if (track->isFlushPending()) {
4728 track->flushAck();
4729 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004730 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004731 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004732 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004733 track->resumeAck();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004734 if (last && mHwPaused) {
4735 doHwResume = true;
4736 mHwPaused = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004737 }
4738 }
4739
Eric Laurent81784c32012-11-19 14:55:58 -08004740 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004741 // for all its buffers to be filled before processing it.
4742 // Allow draining the buffer in case the client
4743 // app does not call stop() and relies on underrun to stop:
4744 // hence the test on (track->mRetryCount > 1).
4745 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07004746 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08004747 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004748 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08004749 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004750 minFrames = mNormalFrameCount;
4751 } else {
4752 minFrames = 1;
4753 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004754
Eric Laurentab5cdba2014-06-09 17:22:27 -07004755 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4756 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004757 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004758 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004759
4760 if (track->mFillingUpStatus == Track::FS_FILLED) {
4761 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004762 // make sure processVolume_l() will apply new volume even if 0
4763 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004764 if (!mHwSupportsPause) {
4765 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004766 }
4767 }
4768
4769 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004770 processVolume_l(track, last);
4771 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004772 sp<Track> previousTrack = mPreviousTrack.promote();
4773 if (previousTrack != 0) {
4774 if (track != previousTrack.get()) {
4775 // Flush any data still being written from last track
4776 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07004777 // Invalidate previous track to force a seek when resuming.
4778 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004779 }
4780 }
4781 mPreviousTrack = track;
4782
Eric Laurentd595b7c2013-04-03 17:27:56 -07004783 // reset retry count
4784 track->mRetryCount = kMaxTrackRetriesDirect;
4785 mActiveTrack = t;
4786 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07004787 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004788 doHwResume = true;
4789 mHwPaused = false;
4790 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004791 }
Eric Laurent81784c32012-11-19 14:55:58 -08004792 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004793 // clear effect chain input buffer if the last active track started underruns
4794 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004795 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004796 mEffectChains[0]->clearInputBuffer();
4797 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004798 if (track->isStopping_1()) {
4799 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07004800 if (last && mHwPaused) {
4801 doHwResume = true;
4802 mHwPaused = false;
4803 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004804 }
4805 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4806 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004807 // We have consumed all the buffers of this track.
4808 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004809 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08004810 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004811 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4812 } else {
4813 audioHALFrames = 0;
4814 }
4815
Andy Hung818e7a32016-02-16 18:08:07 -08004816 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004817 if (mStandby || !last ||
4818 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004819 if (track->isStopping_2()) {
4820 track->mState = TrackBase::STOPPED;
4821 }
Eric Laurent81784c32012-11-19 14:55:58 -08004822 if (track->isStopped()) {
4823 track->reset();
4824 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004825 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004826 }
4827 } else {
4828 // No buffers for this track. Give it a few chances to
4829 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004830 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004831 if (--(track->mRetryCount) <= 0) {
4832 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004833 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004834 // indicate to client process that the track was disabled because of underrun;
4835 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004836 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004837 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07004838 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
4839 "minFrames = %u, mFormat = %#x",
4840 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08004841 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07004842 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004843 doHwPause = true;
4844 mHwPaused = true;
4845 }
Eric Laurent81784c32012-11-19 14:55:58 -08004846 }
4847 }
4848 }
4849 }
4850
Eric Laurentd1f69b02014-12-15 14:33:13 -08004851 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07004852 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004853 for (size_t i = 0; i < mTracks.size(); i++) {
4854 if (mTracks[i]->isFlushPending()) {
4855 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004856 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004857 }
4858 }
4859 }
4860
4861 // make sure the pause/flush/resume sequence is executed in the right order.
4862 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4863 // before flush and then resume HW. This can happen in case of pause/flush/resume
4864 // if resume is received before pause is executed.
4865 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07004866 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004867 mOutput->stream->pause(mOutput->stream);
4868 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004869 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004870 flushHw_l();
4871 }
4872 if (mHwSupportsPause && !mStandby && doHwResume) {
4873 mOutput->stream->resume(mOutput->stream);
4874 }
Eric Laurent81784c32012-11-19 14:55:58 -08004875 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004876 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004877
4878 return mixerStatus;
4879}
4880
4881void AudioFlinger::DirectOutputThread::threadLoop_mix()
4882{
Eric Laurent81784c32012-11-19 14:55:58 -08004883 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08004884 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004885 // output audio to hardware
4886 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07004887 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004888 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08004889 status_t status = mActiveTrack->getNextBuffer(&buffer);
4890 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08004891 // no need to pad with 0 for compressed audio
4892 if (audio_has_proportional_frames(mFormat)) {
4893 memset(curBuf, 0, frameCount * mFrameSize);
4894 }
Eric Laurent81784c32012-11-19 14:55:58 -08004895 break;
4896 }
4897 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
4898 frameCount -= buffer.frameCount;
4899 curBuf += buffer.frameCount * mFrameSize;
4900 mActiveTrack->releaseBuffer(&buffer);
4901 }
Andy Hung2098f272014-02-27 14:00:06 -08004902 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004903 mSleepTimeUs = 0;
4904 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004905 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004906}
4907
4908void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
4909{
Eric Laurentd1f69b02014-12-15 14:33:13 -08004910 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004911 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004912 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004913 return;
4914 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004915 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004916 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurente93cc032016-05-05 10:15:10 -07004917 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004918 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004919 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004920 }
Phil Burkfdb3c072016-02-09 10:47:02 -08004921 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08004922 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004923 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004924 }
4925}
4926
Eric Laurentd1f69b02014-12-15 14:33:13 -08004927void AudioFlinger::DirectOutputThread::threadLoop_exit()
4928{
4929 {
4930 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08004931 for (size_t i = 0; i < mTracks.size(); i++) {
4932 if (mTracks[i]->isFlushPending()) {
4933 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004934 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004935 }
4936 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004937 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004938 flushHw_l();
4939 }
4940 }
4941 PlaybackThread::threadLoop_exit();
4942}
4943
4944// must be called with thread mutex locked
4945bool AudioFlinger::DirectOutputThread::shouldStandby_l()
4946{
4947 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07004948 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004949
vivek mehta9cd7ad12016-03-17 00:18:29 -07004950 if ((mType == DIRECT) && audio_is_linear_pcm(mFormat) && !usesHwAvSync()) {
4951 return !mStandby;
4952 }
4953
Eric Laurentd1f69b02014-12-15 14:33:13 -08004954 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4955 // after a timeout and we will enter standby then.
4956 if (mTracks.size() > 0) {
4957 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07004958 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
4959 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004960 }
4961
Eric Laurent5cff4032015-05-26 13:49:58 -07004962 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08004963}
4964
Eric Laurent81784c32012-11-19 14:55:58 -08004965// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004966int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Glenn Kastend848eb42016-03-08 13:42:11 -08004967 audio_format_t format __unused, audio_session_t sessionId __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004968{
4969 return 0;
4970}
4971
4972// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004973void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004974{
4975}
4976
Eric Laurent10351942014-05-08 18:49:52 -07004977// checkForNewParameter_l() must be called with ThreadBase::mLock held
4978bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
4979 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004980{
4981 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08004982 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004983
Eric Laurent10351942014-05-08 18:49:52 -07004984 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004985
Eric Laurent10351942014-05-08 18:49:52 -07004986 AudioParameter param = AudioParameter(keyValuePair);
4987 int value;
4988 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4989 // forward device change to effects that have requested to be
4990 // aware of attached audio device.
4991 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08004992 a2dpDeviceChanged =
4993 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07004994 mOutDevice = value;
4995 for (size_t i = 0; i < mEffectChains.size(); i++) {
4996 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07004997 }
4998 }
Eric Laurent81784c32012-11-19 14:55:58 -08004999 }
Eric Laurent10351942014-05-08 18:49:52 -07005000 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5001 // do not accept frame count changes if tracks are open as the track buffer
5002 // size depends on frame count and correct behavior would not be garantied
5003 // if frame count is changed after track creation
5004 if (!mTracks.isEmpty()) {
5005 status = INVALID_OPERATION;
5006 } else {
5007 reconfig = true;
5008 }
5009 }
5010 if (status == NO_ERROR) {
5011 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
5012 keyValuePair.string());
5013 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005014 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005015 mStandby = true;
5016 mBytesWritten = 0;
5017 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
5018 keyValuePair.string());
5019 }
5020 if (status == NO_ERROR && reconfig) {
5021 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07005022 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005023 }
5024 }
5025
Eric Laurent42537be2016-01-08 17:16:42 -08005026 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005027}
5028
5029uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
5030{
5031 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005032 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005033 time = PlaybackThread::activeSleepTimeUs();
5034 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005035 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005036 }
5037 return time;
5038}
5039
5040uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
5041{
5042 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005043 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005044 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
5045 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005046 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005047 }
5048 return time;
5049}
5050
5051uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
5052{
5053 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005054 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005055 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
5056 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005057 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005058 }
5059 return time;
5060}
5061
5062void AudioFlinger::DirectOutputThread::cacheParameters_l()
5063{
5064 PlaybackThread::cacheParameters_l();
5065
5066 // use shorter standby delay as on normal output to release
5067 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07005068 // no delay on outputs with HW A/V sync
5069 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005070 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08005071 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005072 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07005073 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005074 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07005075 }
Eric Laurent81784c32012-11-19 14:55:58 -08005076}
5077
Eric Laurente659ef42014-09-29 13:06:46 -07005078void AudioFlinger::DirectOutputThread::flushHw_l()
5079{
Phil Burk062e67a2015-02-11 13:40:50 -08005080 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08005081 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005082 mFlushPending = false;
Eric Laurente659ef42014-09-29 13:06:46 -07005083}
5084
Eric Laurent81784c32012-11-19 14:55:58 -08005085// ----------------------------------------------------------------------------
5086
Eric Laurentbfb1b832013-01-07 09:53:42 -08005087AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07005088 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005089 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07005090 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07005091 mWriteAckSequence(0),
5092 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005093{
5094}
5095
5096AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
5097{
5098}
5099
5100void AudioFlinger::AsyncCallbackThread::onFirstRef()
5101{
5102 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
5103}
5104
5105bool AudioFlinger::AsyncCallbackThread::threadLoop()
5106{
5107 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005108 uint32_t writeAckSequence;
5109 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005110
5111 {
5112 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005113 while (!((mWriteAckSequence & 1) ||
5114 (mDrainSequence & 1) ||
5115 exitPending())) {
5116 mWaitWorkCV.wait(mLock);
5117 }
5118
Eric Laurentbfb1b832013-01-07 09:53:42 -08005119 if (exitPending()) {
5120 break;
5121 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005122 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
5123 mWriteAckSequence, mDrainSequence);
5124 writeAckSequence = mWriteAckSequence;
5125 mWriteAckSequence &= ~1;
5126 drainSequence = mDrainSequence;
5127 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005128 }
5129 {
Eric Laurent4de95592013-09-26 15:28:21 -07005130 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
5131 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005132 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005133 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005134 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005135 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005136 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005137 }
5138 }
5139 }
5140 }
5141 return false;
5142}
5143
5144void AudioFlinger::AsyncCallbackThread::exit()
5145{
5146 ALOGV("AsyncCallbackThread::exit");
5147 Mutex::Autolock _l(mLock);
5148 requestExit();
5149 mWaitWorkCV.broadcast();
5150}
5151
Eric Laurent3b4529e2013-09-05 18:09:19 -07005152void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005153{
5154 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005155 // bit 0 is cleared
5156 mWriteAckSequence = sequence << 1;
5157}
5158
5159void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5160{
5161 Mutex::Autolock _l(mLock);
5162 // ignore unexpected callbacks
5163 if (mWriteAckSequence & 2) {
5164 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005165 mWaitWorkCV.signal();
5166 }
5167}
5168
Eric Laurent3b4529e2013-09-05 18:09:19 -07005169void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005170{
5171 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005172 // bit 0 is cleared
5173 mDrainSequence = sequence << 1;
5174}
5175
5176void AudioFlinger::AsyncCallbackThread::resetDraining()
5177{
5178 Mutex::Autolock _l(mLock);
5179 // ignore unexpected callbacks
5180 if (mDrainSequence & 2) {
5181 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005182 mWaitWorkCV.signal();
5183 }
5184}
5185
5186
5187// ----------------------------------------------------------------------------
5188AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07005189 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
5190 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Eric Laurent64667972016-03-30 18:19:46 -07005191 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005192{
Eric Laurentfd477972013-10-25 18:10:40 -07005193 //FIXME: mStandby should be set to true by ThreadBase constructor
5194 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07005195 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005196}
5197
Eric Laurentbfb1b832013-01-07 09:53:42 -08005198void AudioFlinger::OffloadThread::threadLoop_exit()
5199{
5200 if (mFlushPending || mHwPaused) {
5201 // If a flush is pending or track was paused, just discard buffered data
5202 flushHw_l();
5203 } else {
5204 mMixerStatus = MIXER_DRAIN_ALL;
5205 threadLoop_drain();
5206 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005207 if (mUseAsyncWrite) {
5208 ALOG_ASSERT(mCallbackThread != 0);
5209 mCallbackThread->exit();
5210 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005211 PlaybackThread::threadLoop_exit();
5212}
5213
5214AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5215 Vector< sp<Track> > *tracksToRemove
5216)
5217{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005218 size_t count = mActiveTracks.size();
5219
5220 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005221 bool doHwPause = false;
5222 bool doHwResume = false;
5223
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005224 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07005225
Eric Laurentbfb1b832013-01-07 09:53:42 -08005226 // find out which tracks need to be processed
5227 for (size_t i = 0; i < count; i++) {
5228 sp<Track> t = mActiveTracks[i].promote();
5229 // The track died recently
5230 if (t == 0) {
5231 continue;
5232 }
5233 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005234#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08005235 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005236#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005237 // Only consider last track started for volume and mixer state control.
5238 // In theory an older track could underrun and restart after the new one starts
5239 // but as we only care about the transition phase between two tracks on a
5240 // direct output, it is not a problem to ignore the underrun case.
5241 sp<Track> l = mLatestActiveTrack.promote();
5242 bool last = l.get() == track;
5243
Haynes Mathew George7844f672014-01-15 12:32:55 -08005244 if (track->isInvalid()) {
5245 ALOGW("An invalidated track shouldn't be in active list");
5246 tracksToRemove->add(track);
5247 continue;
5248 }
5249
5250 if (track->mState == TrackBase::IDLE) {
5251 ALOGW("An idle track shouldn't be in active list");
5252 continue;
5253 }
5254
Eric Laurentbfb1b832013-01-07 09:53:42 -08005255 if (track->isPausing()) {
5256 track->setPaused();
5257 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005258 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005259 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005260 mHwPaused = true;
5261 }
5262 // If we were part way through writing the mixbuffer to
5263 // the HAL we must save this until we resume
5264 // BUG - this will be wrong if a different track is made active,
5265 // in that case we want to discard the pending data in the
5266 // mixbuffer and tell the client to present it again when the
5267 // track is resumed
5268 mPausedWriteLength = mCurrentWriteLength;
5269 mPausedBytesRemaining = mBytesRemaining;
5270 mBytesRemaining = 0; // stop writing
5271 }
5272 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005273 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005274 if (track->isStopping_1()) {
5275 track->mRetryCount = kMaxTrackStopRetriesOffload;
5276 } else {
5277 track->mRetryCount = kMaxTrackRetriesOffload;
5278 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08005279 track->flushAck();
5280 if (last) {
5281 mFlushPending = true;
5282 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005283 } else if (track->isResumePending()){
5284 track->resumeAck();
5285 if (last) {
5286 if (mPausedBytesRemaining) {
5287 // Need to continue write that was interrupted
5288 mCurrentWriteLength = mPausedWriteLength;
5289 mBytesRemaining = mPausedBytesRemaining;
5290 mPausedBytesRemaining = 0;
5291 }
5292 if (mHwPaused) {
5293 doHwResume = true;
5294 mHwPaused = false;
5295 // threadLoop_mix() will handle the case that we need to
5296 // resume an interrupted write
5297 }
5298 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005299 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005300
5301 // Do not handle new data in this iteration even if track->framesReady()
5302 mixerStatus = MIXER_TRACKS_ENABLED;
5303 }
5304 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005305 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005306 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005307 if (track->mFillingUpStatus == Track::FS_FILLED) {
5308 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07005309 // make sure processVolume_l() will apply new volume even if 0
5310 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005311 }
5312
5313 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005314 sp<Track> previousTrack = mPreviousTrack.promote();
5315 if (previousTrack != 0) {
5316 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005317 // Flush any data still being written from last track
5318 mBytesRemaining = 0;
5319 if (mPausedBytesRemaining) {
5320 // Last track was paused so we also need to flush saved
5321 // mixbuffer state and invalidate track so that it will
5322 // re-submit that unwritten data when it is next resumed
5323 mPausedBytesRemaining = 0;
5324 // Invalidate is a bit drastic - would be more efficient
5325 // to have a flag to tell client that some of the
5326 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005327 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005328 }
5329 // flush data already sent to the DSP if changing audio session as audio
5330 // comes from a different source. Also invalidate previous track to force a
5331 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005332 if (previousTrack->sessionId() != track->sessionId()) {
5333 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005334 }
5335 }
5336 }
5337 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005338 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07005339 if (track->isStopping_1()) {
5340 track->mRetryCount = kMaxTrackStopRetriesOffload;
5341 } else {
5342 track->mRetryCount = kMaxTrackRetriesOffload;
5343 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005344 mActiveTrack = t;
5345 mixerStatus = MIXER_TRACKS_READY;
5346 }
5347 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005348 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005349 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005350 if (--(track->mRetryCount) <= 0) {
5351 // Hardware buffer can hold a large amount of audio so we must
5352 // wait for all current track's data to drain before we say
5353 // that the track is stopped.
5354 if (mBytesRemaining == 0) {
5355 // Only start draining when all data in mixbuffer
5356 // has been written
5357 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5358 track->mState = TrackBase::STOPPING_2; // so presentation completes after
5359 // drain do not drain if no data was ever sent to HAL (mStandby == true)
5360 if (last && !mStandby) {
5361 // do not modify drain sequence if we are already draining. This happens
5362 // when resuming from pause after drain.
5363 if ((mDrainSequence & 1) == 0) {
5364 mSleepTimeUs = 0;
5365 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
5366 mixerStatus = MIXER_DRAIN_TRACK;
5367 mDrainSequence += 2;
5368 }
5369 if (mHwPaused) {
5370 // It is possible to move from PAUSED to STOPPING_1 without
5371 // a resume so we must ensure hardware is running
5372 doHwResume = true;
5373 mHwPaused = false;
5374 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005375 }
5376 }
Eric Laurente93cc032016-05-05 10:15:10 -07005377 } else if (last) {
5378 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
5379 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005380 }
5381 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005382 // Drain has completed or we are in standby, signal presentation complete
5383 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005384 track->mState = TrackBase::STOPPED;
5385 size_t audioHALFrames =
5386 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005387 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005388 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005389 track->presentationComplete(framesWritten, audioHALFrames);
5390 track->reset();
5391 tracksToRemove->add(track);
5392 }
5393 } else {
5394 // No buffers for this track. Give it a few chances to
5395 // fill a buffer, then remove it from active list.
5396 if (--(track->mRetryCount) <= 0) {
5397 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5398 track->name());
5399 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005400 // indicate to client process that the track was disabled because of underrun;
5401 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005402 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005403 } else if (last){
5404 mixerStatus = MIXER_TRACKS_ENABLED;
5405 }
5406 }
5407 }
5408 // compute volume for this track
5409 processVolume_l(track, last);
5410 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005411
Eric Laurentea0fade2013-10-04 16:23:48 -07005412 // make sure the pause/flush/resume sequence is executed in the right order.
5413 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5414 // before flush and then resume HW. This can happen in case of pause/flush/resume
5415 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07005416 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07005417 mOutput->stream->pause(mOutput->stream);
5418 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005419 if (mFlushPending) {
5420 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005421 }
Eric Laurentfd477972013-10-25 18:10:40 -07005422 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07005423 mOutput->stream->resume(mOutput->stream);
5424 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005425
Eric Laurentbfb1b832013-01-07 09:53:42 -08005426 // remove all the tracks that need to be...
5427 removeTracks_l(*tracksToRemove);
5428
5429 return mixerStatus;
5430}
5431
Eric Laurentbfb1b832013-01-07 09:53:42 -08005432// must be called with thread mutex locked
5433bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5434{
Eric Laurent3b4529e2013-09-05 18:09:19 -07005435 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5436 mWriteAckSequence, mDrainSequence);
5437 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005438 return true;
5439 }
5440 return false;
5441}
5442
Eric Laurentbfb1b832013-01-07 09:53:42 -08005443bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5444{
5445 Mutex::Autolock _l(mLock);
5446 return waitingAsyncCallback_l();
5447}
5448
5449void AudioFlinger::OffloadThread::flushHw_l()
5450{
Eric Laurente659ef42014-09-29 13:06:46 -07005451 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005452 // Flush anything still waiting in the mixbuffer
5453 mCurrentWriteLength = 0;
5454 mBytesRemaining = 0;
5455 mPausedWriteLength = 0;
5456 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07005457 // reset bytes written count to reflect that DSP buffers are empty after flush.
5458 mBytesWritten = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08005459
Eric Laurentbfb1b832013-01-07 09:53:42 -08005460 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005461 // discard any pending drain or write ack by incrementing sequence
5462 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5463 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005464 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005465 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5466 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005467 }
5468}
5469
Haynes Mathew George05317d22016-05-03 16:34:26 -07005470void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
5471{
5472 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07005473 if (PlaybackThread::invalidateTracks_l(streamType)) {
5474 mFlushPending = true;
5475 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07005476}
5477
Eric Laurentbfb1b832013-01-07 09:53:42 -08005478// ----------------------------------------------------------------------------
5479
Eric Laurent81784c32012-11-19 14:55:58 -08005480AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005481 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005482 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07005483 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08005484 mWaitTimeMs(UINT_MAX)
5485{
5486 addOutputTrack(mainThread);
5487}
5488
5489AudioFlinger::DuplicatingThread::~DuplicatingThread()
5490{
5491 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5492 mOutputTracks[i]->destroy();
5493 }
5494}
5495
5496void AudioFlinger::DuplicatingThread::threadLoop_mix()
5497{
5498 // mix buffers...
5499 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08005500 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08005501 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005502 if (mMixerBufferValid) {
5503 memset(mMixerBuffer, 0, mMixerBufferSize);
5504 } else {
5505 memset(mSinkBuffer, 0, mSinkBufferSize);
5506 }
Eric Laurent81784c32012-11-19 14:55:58 -08005507 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005508 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005509 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005510 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005511 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005512}
5513
5514void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5515{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005516 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005517 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005518 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005519 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005520 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005521 }
5522 } else if (mBytesWritten != 0) {
5523 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5524 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005525 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005526 } else {
5527 // flush remaining overflow buffers in output tracks
5528 writeFrames = 0;
5529 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005530 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005531 }
5532}
5533
Eric Laurentbfb1b832013-01-07 09:53:42 -08005534ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005535{
5536 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005537 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005538 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005539 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005540 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005541}
5542
5543void AudioFlinger::DuplicatingThread::threadLoop_standby()
5544{
5545 // DuplicatingThread implements standby by stopping all tracks
5546 for (size_t i = 0; i < outputTracks.size(); i++) {
5547 outputTracks[i]->stop();
5548 }
5549}
5550
5551void AudioFlinger::DuplicatingThread::saveOutputTracks()
5552{
5553 outputTracks = mOutputTracks;
5554}
5555
5556void AudioFlinger::DuplicatingThread::clearOutputTracks()
5557{
5558 outputTracks.clear();
5559}
5560
5561void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5562{
5563 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005564 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5565 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5566 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5567 const size_t frameCount =
5568 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5569 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5570 // from different OutputTracks and their associated MixerThreads (e.g. one may
5571 // nearly empty and the other may be dropping data).
5572
5573 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005574 this,
5575 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005576 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005577 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005578 frameCount,
5579 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08005580 if (outputTrack->cblk() != NULL) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005581 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
Eric Laurent81784c32012-11-19 14:55:58 -08005582 mOutputTracks.add(outputTrack);
Andy Hungc25b84a2015-01-14 19:04:10 -08005583 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005584 updateWaitTime_l();
5585 }
5586}
5587
5588void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5589{
5590 Mutex::Autolock _l(mLock);
5591 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5592 if (mOutputTracks[i]->thread() == thread) {
5593 mOutputTracks[i]->destroy();
5594 mOutputTracks.removeAt(i);
5595 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07005596 if (thread->getOutput() == mOutput) {
5597 mOutput = NULL;
5598 }
Eric Laurent81784c32012-11-19 14:55:58 -08005599 return;
5600 }
5601 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07005602 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005603}
5604
5605// caller must hold mLock
5606void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5607{
5608 mWaitTimeMs = UINT_MAX;
5609 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5610 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5611 if (strong != 0) {
5612 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5613 if (waitTimeMs < mWaitTimeMs) {
5614 mWaitTimeMs = waitTimeMs;
5615 }
5616 }
5617 }
5618}
5619
5620
5621bool AudioFlinger::DuplicatingThread::outputsReady(
5622 const SortedVector< sp<OutputTrack> > &outputTracks)
5623{
5624 for (size_t i = 0; i < outputTracks.size(); i++) {
5625 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5626 if (thread == 0) {
5627 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5628 outputTracks[i].get());
5629 return false;
5630 }
5631 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5632 // see note at standby() declaration
5633 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5634 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5635 thread.get());
5636 return false;
5637 }
5638 }
5639 return true;
5640}
5641
5642uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5643{
5644 return (mWaitTimeMs * 1000) / 2;
5645}
5646
5647void AudioFlinger::DuplicatingThread::cacheParameters_l()
5648{
5649 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5650 updateWaitTime_l();
5651
5652 MixerThread::cacheParameters_l();
5653}
5654
5655// ----------------------------------------------------------------------------
5656// Record
5657// ----------------------------------------------------------------------------
5658
5659AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5660 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005661 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005662 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07005663 audio_devices_t inDevice,
5664 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08005665#ifdef TEE_SINK
5666 , const sp<NBAIO_Sink>& teeSink
5667#endif
5668 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07005669 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005670 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005671 // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005672 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005673#ifdef TEE_SINK
5674 , mTeeSink(teeSink)
5675#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005676 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5677 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005678 // mFastCapture below
5679 , mFastCaptureFutex(0)
5680 // mInputSource
5681 // mPipeSink
5682 // mPipeSource
5683 , mPipeFramesP2(0)
5684 // mPipeMemory
5685 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005686 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005687{
Glenn Kastend7dca052015-03-05 16:05:54 -08005688 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5689 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08005690
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005691 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005692
5693 // create an NBAIO source for the HAL input stream, and negotiate
5694 mInputSource = new AudioStreamInSource(input->stream);
5695 size_t numCounterOffers = 0;
5696 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005697#if !LOG_NDEBUG
5698 ssize_t index =
5699#else
5700 (void)
5701#endif
5702 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005703 ALOG_ASSERT(index == 0);
5704
5705 // initialize fast capture depending on configuration
5706 bool initFastCapture;
5707 switch (kUseFastCapture) {
5708 case FastCapture_Never:
5709 initFastCapture = false;
5710 break;
5711 case FastCapture_Always:
5712 initFastCapture = true;
5713 break;
5714 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07005715 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005716 break;
5717 // case FastCapture_Dynamic:
5718 }
5719
5720 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07005721 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005722 NBAIO_Format format = mInputSource->format();
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005723 size_t pipeFramesP2 = roundup(mSampleRate / 25); // double-buffering of 20 ms each
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005724 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5725 void *pipeBuffer;
5726 const sp<MemoryDealer> roHeap(readOnlyHeap());
5727 sp<IMemory> pipeMemory;
5728 if ((roHeap == 0) ||
5729 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5730 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5731 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5732 goto failed;
5733 }
5734 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5735 memset(pipeBuffer, 0, pipeSize);
5736 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5737 const NBAIO_Format offers[1] = {format};
5738 size_t numCounterOffers = 0;
5739 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5740 ALOG_ASSERT(index == 0);
5741 mPipeSink = pipe;
5742 PipeReader *pipeReader = new PipeReader(*pipe);
5743 numCounterOffers = 0;
5744 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5745 ALOG_ASSERT(index == 0);
5746 mPipeSource = pipeReader;
5747 mPipeFramesP2 = pipeFramesP2;
5748 mPipeMemory = pipeMemory;
5749
5750 // create fast capture
5751 mFastCapture = new FastCapture();
5752 FastCaptureStateQueue *sq = mFastCapture->sq();
5753#ifdef STATE_QUEUE_DUMP
5754 // FIXME
5755#endif
5756 FastCaptureState *state = sq->begin();
5757 state->mCblk = NULL;
5758 state->mInputSource = mInputSource.get();
5759 state->mInputSourceGen++;
5760 state->mPipeSink = pipe;
5761 state->mPipeSinkGen++;
5762 state->mFrameCount = mFrameCount;
5763 state->mCommand = FastCaptureState::COLD_IDLE;
5764 // already done in constructor initialization list
5765 //mFastCaptureFutex = 0;
5766 state->mColdFutexAddr = &mFastCaptureFutex;
5767 state->mColdGen++;
5768 state->mDumpState = &mFastCaptureDumpState;
5769#ifdef TEE_SINK
5770 // FIXME
5771#endif
5772 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
5773 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
5774 sq->end();
5775 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5776
5777 // start the fast capture
5778 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
5779 pid_t tid = mFastCapture->getTid();
Glenn Kasten8379b722016-03-18 14:54:17 -07005780 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005781#ifdef AUDIO_WATCHDOG
5782 // FIXME
5783#endif
5784
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005785 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005786 }
5787failed: ;
5788
5789 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08005790}
5791
Eric Laurent81784c32012-11-19 14:55:58 -08005792AudioFlinger::RecordThread::~RecordThread()
5793{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005794 if (mFastCapture != 0) {
5795 FastCaptureStateQueue *sq = mFastCapture->sq();
5796 FastCaptureState *state = sq->begin();
5797 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5798 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5799 if (old == -1) {
5800 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5801 }
5802 }
5803 state->mCommand = FastCaptureState::EXIT;
5804 sq->end();
5805 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5806 mFastCapture->join();
5807 mFastCapture.clear();
5808 }
5809 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07005810 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07005811 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08005812}
5813
5814void AudioFlinger::RecordThread::onFirstRef()
5815{
Glenn Kastend7dca052015-03-05 16:05:54 -08005816 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08005817}
5818
Eric Laurent81784c32012-11-19 14:55:58 -08005819bool AudioFlinger::RecordThread::threadLoop()
5820{
Eric Laurent81784c32012-11-19 14:55:58 -08005821 nsecs_t lastWarning = 0;
5822
5823 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08005824
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005825reacquire_wakelock:
5826 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08005827 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005828 {
5829 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005830 size_t size = mActiveTracks.size();
5831 activeTracksGen = mActiveTracksGen;
5832 if (size > 0) {
5833 // FIXME an arbitrary choice
5834 activeTrack = mActiveTracks[0];
5835 acquireWakeLock_l(activeTrack->uid());
5836 if (size > 1) {
5837 SortedVector<int> tmp;
5838 for (size_t i = 0; i < size; i++) {
5839 tmp.add(mActiveTracks[i]->uid());
5840 }
5841 updateWakeLockUids_l(tmp);
5842 }
5843 } else {
5844 acquireWakeLock_l(-1);
5845 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005846 }
5847
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005848 // used to request a deferred sleep, to be executed later while mutex is unlocked
5849 uint32_t sleepUs = 0;
5850
5851 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005852 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005853 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07005854
Glenn Kasten5edadd42013-08-14 16:30:49 -07005855 // sleep with mutex unlocked
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005856 if (sleepUs > 0) {
Glenn Kastene7754022014-10-31 12:11:26 -07005857 ATRACE_BEGIN("sleep");
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005858 usleep(sleepUs);
Glenn Kastene7754022014-10-31 12:11:26 -07005859 ATRACE_END();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005860 sleepUs = 0;
Glenn Kasten5edadd42013-08-14 16:30:49 -07005861 }
5862
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005863 // activeTracks accumulates a copy of a subset of mActiveTracks
5864 Vector< sp<RecordTrack> > activeTracks;
5865
Glenn Kasten735f45f2014-08-18 15:51:59 -07005866 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005867 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07005868
Glenn Kasten735f45f2014-08-18 15:51:59 -07005869 // reference to a fast track which is about to be removed
5870 sp<RecordTrack> fastTrackToRemove;
5871
Eric Laurent81784c32012-11-19 14:55:58 -08005872 { // scope for mLock
5873 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08005874
Eric Laurent021cf962014-05-13 10:18:14 -07005875 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005876
Eric Laurent000a4192014-01-29 15:17:32 -08005877 // check exitPending here because checkForNewParameters_l() and
5878 // checkForNewParameters_l() can temporarily release mLock
5879 if (exitPending()) {
5880 break;
5881 }
5882
Glenn Kasten2b806402013-11-20 16:37:38 -08005883 // if no active track(s), then standby and release wakelock
5884 size_t size = mActiveTracks.size();
5885 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07005886 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005887 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08005888 releaseWakeLock_l();
5889 ALOGV("RecordThread: loop stopping");
5890 // go to sleep
5891 mWaitWorkCV.wait(mLock);
5892 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005893 goto reacquire_wakelock;
5894 }
5895
Glenn Kasten2b806402013-11-20 16:37:38 -08005896 if (mActiveTracksGen != activeTracksGen) {
5897 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005898 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08005899 for (size_t i = 0; i < size; i++) {
5900 tmp.add(mActiveTracks[i]->uid());
5901 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005902 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08005903 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005904
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005905 bool doBroadcast = false;
5906 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07005907
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005908 activeTrack = mActiveTracks[i];
5909 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07005910 if (activeTrack->isFastTrack()) {
5911 ALOG_ASSERT(fastTrackToRemove == 0);
5912 fastTrackToRemove = activeTrack;
5913 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005914 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08005915 mActiveTracks.remove(activeTrack);
5916 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005917 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07005918 continue;
5919 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005920
5921 TrackBase::track_state activeTrackState = activeTrack->mState;
5922 switch (activeTrackState) {
5923
5924 case TrackBase::PAUSING:
5925 mActiveTracks.remove(activeTrack);
5926 mActiveTracksGen++;
5927 doBroadcast = true;
5928 size--;
5929 continue;
5930
5931 case TrackBase::STARTING_1:
5932 sleepUs = 10000;
5933 i++;
5934 continue;
5935
5936 case TrackBase::STARTING_2:
5937 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005938 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07005939 activeTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005940 break;
5941
5942 case TrackBase::ACTIVE:
5943 break;
5944
5945 case TrackBase::IDLE:
5946 i++;
5947 continue;
5948
5949 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08005950 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07005951 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005952
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005953 activeTracks.add(activeTrack);
5954 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07005955
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005956 if (activeTrack->isFastTrack()) {
5957 ALOG_ASSERT(!mFastTrackAvail);
5958 ALOG_ASSERT(fastTrack == 0);
5959 fastTrack = activeTrack;
5960 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005961 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005962 if (doBroadcast) {
5963 mStartStopCond.broadcast();
5964 }
5965
5966 // sleep if there are no active tracks to process
5967 if (activeTracks.size() == 0) {
5968 if (sleepUs == 0) {
5969 sleepUs = kRecordThreadSleepUs;
5970 }
5971 continue;
5972 }
5973 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07005974
Eric Laurent81784c32012-11-19 14:55:58 -08005975 lockEffectChains_l(effectChains);
5976 }
5977
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005978 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07005979
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005980 size_t size = effectChains.size();
5981 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005982 // thread mutex is not locked, but effect chain is locked
5983 effectChains[i]->process_l();
5984 }
5985
Glenn Kasten735f45f2014-08-18 15:51:59 -07005986 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005987 if (mFastCapture != 0) {
5988 FastCaptureStateQueue *sq = mFastCapture->sq();
5989 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07005990 bool didModify = false;
5991 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005992 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
5993 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
5994 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5995 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5996 if (old == -1) {
5997 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5998 }
5999 }
6000 state->mCommand = FastCaptureState::READ_WRITE;
6001#if 0 // FIXME
6002 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08006003 FastThreadDumpState::kSamplingNforLowRamDevice :
6004 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006005#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07006006 didModify = true;
6007 }
6008 audio_track_cblk_t *cblkOld = state->mCblk;
6009 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
6010 if (cblkNew != cblkOld) {
6011 state->mCblk = cblkNew;
6012 // block until acked if removing a fast track
6013 if (cblkOld != NULL) {
6014 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
6015 }
6016 didModify = true;
6017 }
6018 sq->end(didModify);
6019 if (didModify) {
6020 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006021#if 0
6022 if (kUseFastCapture == FastCapture_Dynamic) {
6023 mNormalSource = mPipeSource;
6024 }
6025#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006026 }
6027 }
6028
Glenn Kasten735f45f2014-08-18 15:51:59 -07006029 // now run the fast track destructor with thread mutex unlocked
6030 fastTrackToRemove.clear();
6031
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006032 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
6033 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
6034 // slow, then this RecordThread will overrun by not calling HAL read often enough.
6035 // If destination is non-contiguous, first read past the nominal end of buffer, then
6036 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006037
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006038 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006039 ssize_t framesRead;
6040
6041 // If an NBAIO source is present, use it to read the normal capture's data
6042 if (mPipeSource != 0) {
6043 size_t framesToRead = mBufferSize / mFrameSize;
Andy Hung57446612015-04-19 23:56:46 -07006044 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
Glenn Kastend79072e2016-01-06 08:41:20 -08006045 framesToRead);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006046 if (framesRead == 0) {
6047 // since pipe is non-blocking, simulate blocking input
6048 sleepUs = (framesToRead * 1000000LL) / mSampleRate;
6049 }
6050 // otherwise use the HAL / AudioStreamIn directly
6051 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07006052 ATRACE_BEGIN("read");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006053 ssize_t bytesRead = mInput->stream->read(mInput->stream,
Andy Hung57446612015-04-19 23:56:46 -07006054 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize);
Glenn Kastenec6a7032016-03-14 07:40:23 -07006055 ATRACE_END();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006056 if (bytesRead < 0) {
6057 framesRead = bytesRead;
6058 } else {
6059 framesRead = bytesRead / mFrameSize;
6060 }
6061 }
6062
Andy Hung3f0c9022016-01-15 17:49:46 -08006063 // Update server timestamp with server stats
6064 // systemTime() is optional if the hardware supports timestamps.
6065 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
6066 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6067
6068 // Update server timestamp with kernel stats
6069 if (mInput->stream->get_capture_position != nullptr) {
6070 int64_t position, time;
6071 int ret = mInput->stream->get_capture_position(mInput->stream, &position, &time);
6072 if (ret == NO_ERROR) {
6073 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
6074 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
6075 // Note: In general record buffers should tend to be empty in
6076 // a properly running pipeline.
6077 //
6078 // Also, it is not advantageous to call get_presentation_position during the read
6079 // as the read obtains a lock, preventing the timestamp call from executing.
6080 }
6081 }
6082 // Use this to track timestamp information
6083 // ALOGD("%s", mTimestamp.toString().c_str());
6084
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006085 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006086 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006087 // Force input into standby so that it tries to recover at next read attempt
6088 inputStandBy();
6089 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006090 }
6091 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006092 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006093 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006094 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006095
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006096 if (mTeeSink != 0) {
Andy Hung57446612015-04-19 23:56:46 -07006097 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006098 }
6099 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006100 {
6101 size_t part1 = mRsmpInFramesP2 - rear;
6102 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07006103 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006104 (framesRead - part1) * mFrameSize);
6105 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006106 }
6107 rear = mRsmpInRear += framesRead;
6108
6109 size = activeTracks.size();
6110 // loop over each active track
6111 for (size_t i = 0; i < size; i++) {
6112 activeTrack = activeTracks[i];
6113
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006114 // skip fast tracks, as those are handled directly by FastCapture
6115 if (activeTrack->isFastTrack()) {
6116 continue;
6117 }
6118
Andy Hung73c02e42015-03-29 01:13:58 -07006119 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07006120 // TODO: Update the activeTrack buffer converter in case of reconfigure.
6121
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006122 enum {
6123 OVERRUN_UNKNOWN,
6124 OVERRUN_TRUE,
6125 OVERRUN_FALSE
6126 } overrun = OVERRUN_UNKNOWN;
6127
6128 // loop over getNextBuffer to handle circular sink
6129 for (;;) {
6130
6131 activeTrack->mSink.frameCount = ~0;
6132 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
6133 size_t framesOut = activeTrack->mSink.frameCount;
6134 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
6135
Andy Hung73c02e42015-03-29 01:13:58 -07006136 // check available frames and handle overrun conditions
6137 // if the record track isn't draining fast enough.
6138 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006139 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07006140 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
6141 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006142 overrun = OVERRUN_TRUE;
6143 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006144 if (framesOut == 0 || framesIn == 0) {
6145 break;
6146 }
6147
Andy Hung6770c6f2015-04-07 13:43:36 -07006148 // Don't allow framesOut to be larger than what is possible with resampling
6149 // from framesIn.
6150 // This isn't strictly necessary but helps limit buffer resizing in
6151 // RecordBufferConverter. TODO: remove when no longer needed.
6152 framesOut = min(framesOut,
6153 destinationFramesPossible(
6154 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07006155 // process frames from the RecordThread buffer provider to the RecordTrack buffer
6156 framesOut = activeTrack->mRecordBufferConverter->convert(
6157 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006158
6159 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
6160 overrun = OVERRUN_FALSE;
6161 }
6162
6163 if (activeTrack->mFramesToDrop == 0) {
6164 if (framesOut > 0) {
6165 activeTrack->mSink.frameCount = framesOut;
6166 activeTrack->releaseBuffer(&activeTrack->mSink);
6167 }
6168 } else {
6169 // FIXME could do a partial drop of framesOut
6170 if (activeTrack->mFramesToDrop > 0) {
6171 activeTrack->mFramesToDrop -= framesOut;
6172 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006173 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006174 }
6175 } else {
6176 activeTrack->mFramesToDrop += framesOut;
6177 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
6178 activeTrack->mSyncStartEvent->isCancelled()) {
6179 ALOGW("Synced record %s, session %d, trigger session %d",
6180 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
6181 activeTrack->sessionId(),
6182 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08006183 activeTrack->mSyncStartEvent->triggerSession() :
6184 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006185 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006186 }
6187 }
6188 }
6189
6190 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006191 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006192 }
6193 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006194
6195 switch (overrun) {
6196 case OVERRUN_TRUE:
6197 // client isn't retrieving buffers fast enough
6198 if (!activeTrack->setOverflow()) {
6199 nsecs_t now = systemTime();
6200 // FIXME should lastWarning per track?
6201 if ((now - lastWarning) > kWarningThrottleNs) {
6202 ALOGW("RecordThread: buffer overflow");
6203 lastWarning = now;
6204 }
6205 }
6206 break;
6207 case OVERRUN_FALSE:
6208 activeTrack->clearOverflow();
6209 break;
6210 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006211 break;
6212 }
6213
Andy Hung3f0c9022016-01-15 17:49:46 -08006214 // update frame information and push timestamp out
6215 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08006216 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08006217 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
6218 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006219 }
6220
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006221unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08006222 // enable changes in effect chain
6223 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006224 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08006225 }
6226
Glenn Kasten93e471f2013-08-19 08:40:07 -07006227 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08006228
6229 {
6230 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07006231 for (size_t i = 0; i < mTracks.size(); i++) {
6232 sp<RecordTrack> track = mTracks[i];
6233 track->invalidate();
6234 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006235 mActiveTracks.clear();
6236 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08006237 mStartStopCond.broadcast();
6238 }
6239
6240 releaseWakeLock();
6241
6242 ALOGV("RecordThread %p exiting", this);
6243 return false;
6244}
6245
Glenn Kasten93e471f2013-08-19 08:40:07 -07006246void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08006247{
6248 if (!mStandby) {
6249 inputStandBy();
6250 mStandby = true;
6251 }
6252}
6253
6254void AudioFlinger::RecordThread::inputStandBy()
6255{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006256 // Idle the fast capture if it's currently running
6257 if (mFastCapture != 0) {
6258 FastCaptureStateQueue *sq = mFastCapture->sq();
6259 FastCaptureState *state = sq->begin();
6260 if (!(state->mCommand & FastCaptureState::IDLE)) {
6261 state->mCommand = FastCaptureState::COLD_IDLE;
6262 state->mColdFutexAddr = &mFastCaptureFutex;
6263 state->mColdGen++;
6264 mFastCaptureFutex = 0;
6265 sq->end();
6266 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
6267 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
6268#if 0
6269 if (kUseFastCapture == FastCapture_Dynamic) {
6270 // FIXME
6271 }
6272#endif
6273#ifdef AUDIO_WATCHDOG
6274 // FIXME
6275#endif
6276 } else {
6277 sq->end(false /*didModify*/);
6278 }
6279 }
Eric Laurent81784c32012-11-19 14:55:58 -08006280 mInput->stream->common.standby(&mInput->stream->common);
6281}
6282
Glenn Kasten05997e22014-03-13 15:08:33 -07006283// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07006284sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08006285 const sp<AudioFlinger::Client>& client,
6286 uint32_t sampleRate,
6287 audio_format_t format,
6288 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08006289 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08006290 audio_session_t sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07006291 size_t *notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006292 int uid,
Eric Laurent05067782016-06-01 18:27:28 -07006293 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08006294 pid_t tid,
6295 status_t *status)
6296{
Glenn Kasten74935e42013-12-19 08:56:45 -08006297 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08006298 sp<RecordTrack> track;
6299 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07006300 audio_input_flags_t inputFlags = mInput->flags;
6301
6302 // special case for FAST flag considered OK if fast capture is present
6303 if (hasFastCapture()) {
6304 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
6305 }
6306
6307 // Check if requested flags are compatible with output stream flags
6308 if ((*flags & inputFlags) != *flags) {
6309 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
6310 " input flags (%08x)",
6311 *flags, inputFlags);
6312 *flags = (audio_input_flags_t)(*flags & inputFlags);
6313 }
Eric Laurent81784c32012-11-19 14:55:58 -08006314
Glenn Kasten90e58b12013-07-31 16:16:02 -07006315 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07006316 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006317 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07006318 // we formerly checked for a callback handler (non-0 tid),
6319 // but that is no longer required for TRANSFER_OBTAIN mode
6320 //
Glenn Kasten74105912014-07-03 12:28:53 -07006321 // frame count is not specified, or is exactly the pipe depth
6322 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006323 // PCM data
6324 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006325 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006326 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006327 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006328 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006329 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07006330 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006331 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006332 hasFastCapture() &&
6333 // there are sufficient fast track slots available
6334 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07006335 ) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006336 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
Glenn Kasten90e58b12013-07-31 16:16:02 -07006337 frameCount, mFrameCount);
6338 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006339 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
Glenn Kasten74105912014-07-03 12:28:53 -07006340 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006341 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07006342 frameCount, mFrameCount, mPipeFramesP2,
6343 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
6344 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07006345 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07006346 }
6347 }
6348
6349 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07006350 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07006351 // fast track: frame count is exactly the pipe depth
6352 frameCount = mPipeFramesP2;
6353 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
6354 *notificationFrames = mFrameCount;
6355 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006356 // not fast track: max notification period is resampled equivalent of one HAL buffer time
6357 // or 20 ms if there is a fast capture
6358 // TODO This could be a roundupRatio inline, and const
6359 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
6360 * sampleRate + mSampleRate - 1) / mSampleRate;
6361 // minimum number of notification periods is at least kMinNotifications,
6362 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
6363 static const size_t kMinNotifications = 3;
6364 static const uint32_t kMinMs = 30;
6365 // TODO This could be a roundupRatio inline
6366 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
6367 // TODO This could be a roundupRatio inline
6368 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
6369 maxNotificationFrames;
6370 const size_t minFrameCount = maxNotificationFrames *
6371 max(kMinNotifications, minNotificationsByMs);
6372 frameCount = max(frameCount, minFrameCount);
6373 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
6374 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07006375 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07006376 }
Glenn Kasten74935e42013-12-19 08:56:45 -08006377 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07006378
Glenn Kasten15e57982013-09-24 11:52:37 -07006379 lStatus = initCheck();
6380 if (lStatus != NO_ERROR) {
6381 ALOGE("createRecordTrack_l() audio driver not initialized");
6382 goto Exit;
6383 }
Eric Laurent81784c32012-11-19 14:55:58 -08006384
6385 { // scope for mLock
6386 Mutex::Autolock _l(mLock);
6387
6388 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07006389 format, channelMask, frameCount, NULL, sessionId, uid,
6390 *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08006391
Glenn Kasten03003332013-08-06 15:40:54 -07006392 lStatus = track->initCheck();
6393 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07006394 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08006395 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08006396 goto Exit;
6397 }
6398 mTracks.add(track);
6399
6400 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6401 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6402 mAudioFlinger->btNrecIsOff();
6403 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6404 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006405
Eric Laurent05067782016-06-01 18:27:28 -07006406 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006407 pid_t callingPid = IPCThreadState::self()->getCallingPid();
6408 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
6409 // so ask activity manager to do this on our behalf
6410 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
6411 }
Eric Laurent81784c32012-11-19 14:55:58 -08006412 }
Glenn Kasten05997e22014-03-13 15:08:33 -07006413
Eric Laurent81784c32012-11-19 14:55:58 -08006414 lStatus = NO_ERROR;
6415
6416Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07006417 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08006418 return track;
6419}
6420
6421status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6422 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08006423 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08006424{
6425 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6426 sp<ThreadBase> strongMe = this;
6427 status_t status = NO_ERROR;
6428
6429 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006430 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006431 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006432 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08006433 triggerSession,
6434 recordTrack->sessionId(),
6435 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006436 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08006437 // Sync event can be cancelled by the trigger session if the track is not in a
6438 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006439 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006440 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006441 } else {
6442 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006443 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006444 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08006445 }
6446 }
6447
6448 {
Glenn Kasten47c20702013-08-13 15:37:35 -07006449 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08006450 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006451 if (mActiveTracks.indexOf(recordTrack) >= 0) {
6452 if (recordTrack->mState == TrackBase::PAUSING) {
6453 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006454 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006455 } else {
6456 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08006457 }
6458 return status;
6459 }
6460
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006461 // TODO consider other ways of handling this, such as changing the state to :STARTING and
6462 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6463 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006464 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08006465 mActiveTracks.add(recordTrack);
6466 mActiveTracksGen++;
Eric Laurent83b88082014-06-20 18:31:16 -07006467 status_t status = NO_ERROR;
6468 if (recordTrack->isExternalTrack()) {
6469 mLock.unlock();
Glenn Kastend848eb42016-03-08 13:42:11 -08006470 status = AudioSystem::startInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006471 mLock.lock();
6472 // FIXME should verify that recordTrack is still in mActiveTracks
6473 if (status != NO_ERROR) {
6474 mActiveTracks.remove(recordTrack);
6475 mActiveTracksGen++;
6476 recordTrack->clearSyncStartEvent();
6477 ALOGV("RecordThread::start error %d", status);
6478 return status;
6479 }
Eric Laurent81784c32012-11-19 14:55:58 -08006480 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006481 // Catch up with current buffer indices if thread is already running.
6482 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
6483 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6484 // see previously buffered data before it called start(), but with greater risk of overrun.
6485
Andy Hung73c02e42015-03-29 01:13:58 -07006486 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07006487 // clear any converter state as new data will be discontinuous
6488 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006489 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08006490 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08006491 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08006492 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006493 ALOGV("Record failed to start");
6494 status = BAD_VALUE;
6495 goto startError;
6496 }
Eric Laurent81784c32012-11-19 14:55:58 -08006497 return status;
6498 }
Glenn Kasten7c027242012-12-26 14:43:16 -08006499
Eric Laurent81784c32012-11-19 14:55:58 -08006500startError:
Eric Laurent83b88082014-06-20 18:31:16 -07006501 if (recordTrack->isExternalTrack()) {
Glenn Kastend848eb42016-03-08 13:42:11 -08006502 AudioSystem::stopInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006503 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006504 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006505 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08006506 return status;
6507}
6508
Eric Laurent81784c32012-11-19 14:55:58 -08006509void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6510{
6511 sp<SyncEvent> strongEvent = event.promote();
6512
6513 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08006514 sp<RefBase> ptr = strongEvent->cookie().promote();
6515 if (ptr != 0) {
6516 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6517 recordTrack->handleSyncStartEvent(strongEvent);
6518 }
Eric Laurent81784c32012-11-19 14:55:58 -08006519 }
6520}
6521
Glenn Kastena8356f62013-07-25 14:37:52 -07006522bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08006523 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07006524 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006525 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08006526 return false;
6527 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006528 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006529 recordTrack->mState = TrackBase::PAUSING;
6530 // do not wait for mStartStopCond if exiting
6531 if (exitPending()) {
6532 return true;
6533 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006534 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08006535 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006536 // if we have been restarted, recordTrack is in mActiveTracks here
6537 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006538 ALOGV("Record stopped OK");
6539 return true;
6540 }
6541 return false;
6542}
6543
Glenn Kasten0f11b512014-01-31 16:18:54 -08006544bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08006545{
6546 return false;
6547}
6548
Glenn Kasten0f11b512014-01-31 16:18:54 -08006549status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006550{
6551#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6552 if (!isValidSyncEvent(event)) {
6553 return BAD_VALUE;
6554 }
6555
Glenn Kastend848eb42016-03-08 13:42:11 -08006556 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08006557 status_t ret = NAME_NOT_FOUND;
6558
6559 Mutex::Autolock _l(mLock);
6560
6561 for (size_t i = 0; i < mTracks.size(); i++) {
6562 sp<RecordTrack> track = mTracks[i];
6563 if (eventSession == track->sessionId()) {
6564 (void) track->setSyncEvent(event);
6565 ret = NO_ERROR;
6566 }
6567 }
6568 return ret;
6569#else
6570 return BAD_VALUE;
6571#endif
6572}
6573
6574// destroyTrack_l() must be called with ThreadBase::mLock held
6575void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6576{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006577 track->terminate();
6578 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006579 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006580 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006581 removeTrack_l(track);
6582 }
6583}
6584
6585void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6586{
6587 mTracks.remove(track);
6588 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006589 if (track->isFastTrack()) {
6590 ALOG_ASSERT(!mFastTrackAvail);
6591 mFastTrackAvail = true;
6592 }
Eric Laurent81784c32012-11-19 14:55:58 -08006593}
6594
6595void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6596{
6597 dumpInternals(fd, args);
6598 dumpTracks(fd, args);
6599 dumpEffectChains(fd, args);
6600}
6601
6602void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6603{
Elliott Hughes87cebad2014-05-22 10:14:43 -07006604 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08006605
Glenn Kasten44182c22015-03-05 17:12:23 -08006606 dumpBase(fd, args);
6607
6608 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006609 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006610 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006611 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006612 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08006613
Glenn Kasten2f90c512015-12-02 11:40:09 -08006614 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
6615 // while we are dumping it. It may be inconsistent, but it won't mutate!
6616 // This is a large object so we place it on the heap.
6617 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
6618 const FastCaptureDumpState *copy = new FastCaptureDumpState(mFastCaptureDumpState);
6619 copy->dump(fd);
6620 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08006621}
6622
Glenn Kasten0f11b512014-01-31 16:18:54 -08006623void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006624{
6625 const size_t SIZE = 256;
6626 char buffer[SIZE];
6627 String8 result;
6628
Marco Nelissenb2208842014-02-07 14:00:50 -08006629 size_t numtracks = mTracks.size();
6630 size_t numactive = mActiveTracks.size();
6631 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006632 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006633 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006634 dprintf(fd, " of which %zu are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006635 RecordTrack::appendDumpHeader(result);
6636 for (size_t i = 0; i < numtracks ; ++i) {
6637 sp<RecordTrack> track = mTracks[i];
6638 if (track != 0) {
6639 bool active = mActiveTracks.indexOf(track) >= 0;
6640 if (active) {
6641 numactiveseen++;
6642 }
6643 track->dump(buffer, SIZE, active);
6644 result.append(buffer);
6645 }
Eric Laurent81784c32012-11-19 14:55:58 -08006646 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006647 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006648 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006649 }
6650
Marco Nelissenb2208842014-02-07 14:00:50 -08006651 if (numactiveseen != numactive) {
6652 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6653 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006654 result.append(buffer);
6655 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006656 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006657 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006658 if (mTracks.indexOf(track) < 0) {
6659 track->dump(buffer, SIZE, true);
6660 result.append(buffer);
6661 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006662 }
Eric Laurent81784c32012-11-19 14:55:58 -08006663
6664 }
6665 write(fd, result.string(), result.size());
6666}
6667
Andy Hung73c02e42015-03-29 01:13:58 -07006668
6669void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
6670{
6671 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6672 RecordThread *recordThread = (RecordThread *) threadBase.get();
6673 mRsmpInFront = recordThread->mRsmpInRear;
6674 mRsmpInUnrel = 0;
6675}
6676
6677void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
6678 size_t *framesAvailable, bool *hasOverrun)
6679{
6680 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6681 RecordThread *recordThread = (RecordThread *) threadBase.get();
6682 const int32_t rear = recordThread->mRsmpInRear;
6683 const int32_t front = mRsmpInFront;
6684 const ssize_t filled = rear - front;
6685
6686 size_t framesIn;
6687 bool overrun = false;
6688 if (filled < 0) {
6689 // should not happen, but treat like a massive overrun and re-sync
6690 framesIn = 0;
6691 mRsmpInFront = rear;
6692 overrun = true;
6693 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
6694 framesIn = (size_t) filled;
6695 } else {
6696 // client is not keeping up with server, but give it latest data
6697 framesIn = recordThread->mRsmpInFrames;
6698 mRsmpInFront = /* front = */ rear - framesIn;
6699 overrun = true;
6700 }
6701 if (framesAvailable != NULL) {
6702 *framesAvailable = framesIn;
6703 }
6704 if (hasOverrun != NULL) {
6705 *hasOverrun = overrun;
6706 }
6707}
6708
Eric Laurent81784c32012-11-19 14:55:58 -08006709// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006710status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08006711 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006712{
Andy Hung73c02e42015-03-29 01:13:58 -07006713 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006714 if (threadBase == 0) {
6715 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006716 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006717 return NOT_ENOUGH_DATA;
6718 }
6719 RecordThread *recordThread = (RecordThread *) threadBase.get();
6720 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07006721 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07006722 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006723 // FIXME should not be P2 (don't want to increase latency)
6724 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006725 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07006726 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006727 front &= recordThread->mRsmpInFramesP2 - 1;
6728 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07006729 if (part1 > (size_t) filled) {
6730 part1 = filled;
6731 }
6732 size_t ask = buffer->frameCount;
6733 ALOG_ASSERT(ask > 0);
6734 if (part1 > ask) {
6735 part1 = ask;
6736 }
6737 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07006738 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07006739 buffer->raw = NULL;
6740 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07006741 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07006742 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08006743 }
6744
Andy Hung57446612015-04-19 23:56:46 -07006745 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07006746 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07006747 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08006748 return NO_ERROR;
6749}
6750
6751// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006752void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
6753 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006754{
Glenn Kasten85948432013-08-19 12:09:05 -07006755 size_t stepCount = buffer->frameCount;
6756 if (stepCount == 0) {
6757 return;
6758 }
Andy Hung73c02e42015-03-29 01:13:58 -07006759 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
6760 mRsmpInUnrel -= stepCount;
6761 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006762 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006763 buffer->frameCount = 0;
6764}
6765
Andy Hung97a893e2015-03-29 01:03:07 -07006766AudioFlinger::RecordThread::RecordBufferConverter::RecordBufferConverter(
6767 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6768 uint32_t srcSampleRate,
6769 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6770 uint32_t dstSampleRate) :
6771 mSrcChannelMask(AUDIO_CHANNEL_INVALID), // updateParameters will set following vars
6772 // mSrcFormat
6773 // mSrcSampleRate
6774 // mDstChannelMask
6775 // mDstFormat
6776 // mDstSampleRate
6777 // mSrcChannelCount
6778 // mDstChannelCount
6779 // mDstFrameSize
6780 mBuf(NULL), mBufFrames(0), mBufFrameSize(0),
Andy Hungd330ee42015-04-20 13:23:41 -07006781 mResampler(NULL),
6782 mIsLegacyDownmix(false),
6783 mIsLegacyUpmix(false),
6784 mRequiresFloat(false),
6785 mInputConverterProvider(NULL)
Andy Hung97a893e2015-03-29 01:03:07 -07006786{
6787 (void)updateParameters(srcChannelMask, srcFormat, srcSampleRate,
6788 dstChannelMask, dstFormat, dstSampleRate);
6789}
6790
6791AudioFlinger::RecordThread::RecordBufferConverter::~RecordBufferConverter() {
6792 free(mBuf);
6793 delete mResampler;
Andy Hungd330ee42015-04-20 13:23:41 -07006794 delete mInputConverterProvider;
Andy Hung97a893e2015-03-29 01:03:07 -07006795}
6796
6797size_t AudioFlinger::RecordThread::RecordBufferConverter::convert(void *dst,
6798 AudioBufferProvider *provider, size_t frames)
6799{
Andy Hungd330ee42015-04-20 13:23:41 -07006800 if (mInputConverterProvider != NULL) {
6801 mInputConverterProvider->setBufferProvider(provider);
6802 provider = mInputConverterProvider;
6803 }
6804
6805 if (mResampler == NULL) {
Andy Hung97a893e2015-03-29 01:03:07 -07006806 ALOGVV("NO RESAMPLING sampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6807 mSrcSampleRate, mSrcFormat, mDstFormat);
6808
6809 AudioBufferProvider::Buffer buffer;
6810 for (size_t i = frames; i > 0; ) {
6811 buffer.frameCount = i;
Glenn Kastend79072e2016-01-06 08:41:20 -08006812 status_t status = provider->getNextBuffer(&buffer);
Andy Hung97a893e2015-03-29 01:03:07 -07006813 if (status != OK || buffer.frameCount == 0) {
6814 frames -= i; // cannot fill request.
6815 break;
6816 }
Andy Hungd330ee42015-04-20 13:23:41 -07006817 // format convert to destination buffer
6818 convertNoResampler(dst, buffer.raw, buffer.frameCount);
Andy Hung97a893e2015-03-29 01:03:07 -07006819
6820 dst = (int8_t*)dst + buffer.frameCount * mDstFrameSize;
6821 i -= buffer.frameCount;
6822 provider->releaseBuffer(&buffer);
6823 }
6824 } else {
6825 ALOGVV("RESAMPLING mSrcSampleRate:%u mDstSampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6826 mSrcSampleRate, mDstSampleRate, mSrcFormat, mDstFormat);
6827
Andy Hungd330ee42015-04-20 13:23:41 -07006828 // reallocate buffer if needed
6829 if (mBufFrameSize != 0 && mBufFrames < frames) {
6830 free(mBuf);
6831 mBufFrames = frames;
6832 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6833 }
Andy Hung97a893e2015-03-29 01:03:07 -07006834 // resampler accumulates, but we only have one source track
Andy Hungd330ee42015-04-20 13:23:41 -07006835 memset(mBuf, 0, frames * mBufFrameSize);
6836 frames = mResampler->resample((int32_t*)mBuf, frames, provider);
6837 // format convert to destination buffer
6838 convertResampler(dst, mBuf, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006839 }
6840 return frames;
6841}
6842
6843status_t AudioFlinger::RecordThread::RecordBufferConverter::updateParameters(
6844 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6845 uint32_t srcSampleRate,
6846 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6847 uint32_t dstSampleRate)
6848{
6849 // quick evaluation if there is any change.
6850 if (mSrcFormat == srcFormat
6851 && mSrcChannelMask == srcChannelMask
6852 && mSrcSampleRate == srcSampleRate
6853 && mDstFormat == dstFormat
6854 && mDstChannelMask == dstChannelMask
6855 && mDstSampleRate == dstSampleRate) {
6856 return NO_ERROR;
6857 }
6858
Andy Hungdb4c0312015-05-06 08:46:52 -07006859 ALOGV("RecordBufferConverter updateParameters srcMask:%#x dstMask:%#x"
6860 " srcFormat:%#x dstFormat:%#x srcRate:%u dstRate:%u",
6861 srcChannelMask, dstChannelMask, srcFormat, dstFormat, srcSampleRate, dstSampleRate);
Andy Hung97a893e2015-03-29 01:03:07 -07006862 const bool valid =
6863 audio_is_input_channel(srcChannelMask)
6864 && audio_is_input_channel(dstChannelMask)
6865 && audio_is_valid_format(srcFormat) && audio_is_linear_pcm(srcFormat)
6866 && audio_is_valid_format(dstFormat) && audio_is_linear_pcm(dstFormat)
6867 && (srcSampleRate <= dstSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX)
6868 ; // no upsampling checks for now
6869 if (!valid) {
6870 return BAD_VALUE;
6871 }
6872
6873 mSrcFormat = srcFormat;
6874 mSrcChannelMask = srcChannelMask;
6875 mSrcSampleRate = srcSampleRate;
6876 mDstFormat = dstFormat;
6877 mDstChannelMask = dstChannelMask;
6878 mDstSampleRate = dstSampleRate;
6879
6880 // compute derived parameters
6881 mSrcChannelCount = audio_channel_count_from_in_mask(srcChannelMask);
6882 mDstChannelCount = audio_channel_count_from_in_mask(dstChannelMask);
6883 mDstFrameSize = mDstChannelCount * audio_bytes_per_sample(mDstFormat);
6884
Andy Hungd330ee42015-04-20 13:23:41 -07006885 // do we need to resample?
6886 delete mResampler;
6887 mResampler = NULL;
6888 if (mSrcSampleRate != mDstSampleRate) {
6889 mResampler = AudioResampler::create(AUDIO_FORMAT_PCM_FLOAT,
6890 mSrcChannelCount, mDstSampleRate);
6891 mResampler->setSampleRate(mSrcSampleRate);
6892 mResampler->setVolume(AudioMixer::UNITY_GAIN_FLOAT, AudioMixer::UNITY_GAIN_FLOAT);
6893 }
6894
6895 // are we running legacy channel conversion modes?
6896 mIsLegacyDownmix = (mSrcChannelMask == AUDIO_CHANNEL_IN_STEREO
6897 || mSrcChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK)
6898 && mDstChannelMask == AUDIO_CHANNEL_IN_MONO;
6899 mIsLegacyUpmix = mSrcChannelMask == AUDIO_CHANNEL_IN_MONO
6900 && (mDstChannelMask == AUDIO_CHANNEL_IN_STEREO
6901 || mDstChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK);
6902
6903 // do we need to process in float?
6904 mRequiresFloat = mResampler != NULL || mIsLegacyDownmix || mIsLegacyUpmix;
6905
6906 // do we need a staging buffer to convert for destination (we can still optimize this)?
6907 // we use mBufFrameSize > 0 to indicate both frame size as well as buffer necessity
6908 if (mResampler != NULL) {
6909 mBufFrameSize = max(mSrcChannelCount, FCC_2)
6910 * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
Andy Hunga97630b2015-07-22 23:27:24 -07006911 } else if (mIsLegacyUpmix || mIsLegacyDownmix) { // legacy modes always float
Andy Hungd330ee42015-04-20 13:23:41 -07006912 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
6913 } else if (mSrcChannelMask != mDstChannelMask && mDstFormat != mSrcFormat) {
Andy Hung97a893e2015-03-29 01:03:07 -07006914 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(mSrcFormat);
6915 } else {
6916 mBufFrameSize = 0;
6917 }
6918 mBufFrames = 0; // force the buffer to be resized.
6919
Andy Hungd330ee42015-04-20 13:23:41 -07006920 // do we need an input converter buffer provider to give us float?
6921 delete mInputConverterProvider;
6922 mInputConverterProvider = NULL;
6923 if (mRequiresFloat && mSrcFormat != AUDIO_FORMAT_PCM_FLOAT) {
6924 mInputConverterProvider = new ReformatBufferProvider(
6925 audio_channel_count_from_in_mask(mSrcChannelMask),
6926 mSrcFormat,
6927 AUDIO_FORMAT_PCM_FLOAT,
6928 256 /* provider buffer frame count */);
6929 }
6930
6931 // do we need a remixer to do channel mask conversion
6932 if (!mIsLegacyDownmix && !mIsLegacyUpmix && mSrcChannelMask != mDstChannelMask) {
6933 (void) memcpy_by_index_array_initialization_from_channel_mask(
6934 mIdxAry, ARRAY_SIZE(mIdxAry), mDstChannelMask, mSrcChannelMask);
Andy Hung97a893e2015-03-29 01:03:07 -07006935 }
6936 return NO_ERROR;
6937}
6938
Andy Hungd330ee42015-04-20 13:23:41 -07006939void AudioFlinger::RecordThread::RecordBufferConverter::convertNoResampler(
6940 void *dst, const void *src, size_t frames)
Andy Hung97a893e2015-03-29 01:03:07 -07006941{
Andy Hungd330ee42015-04-20 13:23:41 -07006942 // src is native type unless there is legacy upmix or downmix, whereupon it is float.
Andy Hung97a893e2015-03-29 01:03:07 -07006943 if (mBufFrameSize != 0 && mBufFrames < frames) {
6944 free(mBuf);
6945 mBufFrames = frames;
6946 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6947 }
Andy Hungd330ee42015-04-20 13:23:41 -07006948 // do we need to do legacy upmix and downmix?
6949 if (mIsLegacyUpmix || mIsLegacyDownmix) {
Andy Hung97a893e2015-03-29 01:03:07 -07006950 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07006951 if (mIsLegacyUpmix) {
6952 upmix_to_stereo_float_from_mono_float((float *)dstBuf,
6953 (const float *)src, frames);
6954 } else /*mIsLegacyDownmix */ {
6955 downmix_to_mono_float_from_stereo_float((float *)dstBuf,
6956 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006957 }
Andy Hungd330ee42015-04-20 13:23:41 -07006958 if (mBuf != NULL) {
6959 memcpy_by_audio_format(dst, mDstFormat, mBuf, AUDIO_FORMAT_PCM_FLOAT,
6960 frames * mDstChannelCount);
6961 }
6962 return;
6963 }
6964 // do we need to do channel mask conversion?
6965 if (mSrcChannelMask != mDstChannelMask) {
Andy Hung97a893e2015-03-29 01:03:07 -07006966 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07006967 memcpy_by_index_array(dstBuf, mDstChannelCount,
6968 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mSrcFormat), frames);
6969 if (dstBuf == dst) {
6970 return; // format is the same
6971 }
6972 }
6973 // convert to destination buffer
6974 const void *convertBuf = mBuf != NULL ? mBuf : src;
6975 memcpy_by_audio_format(dst, mDstFormat, convertBuf, mSrcFormat,
6976 frames * mDstChannelCount);
6977}
6978
6979void AudioFlinger::RecordThread::RecordBufferConverter::convertResampler(
6980 void *dst, /*not-a-const*/ void *src, size_t frames)
6981{
6982 // src buffer format is ALWAYS float when entering this routine
6983 if (mIsLegacyUpmix) {
6984 ; // mono to stereo already handled by resampler
6985 } else if (mIsLegacyDownmix
6986 || (mSrcChannelMask == mDstChannelMask && mSrcChannelCount == 1)) {
6987 // the resampler outputs stereo for mono input channel (a feature?)
6988 // must convert to mono
6989 downmix_to_mono_float_from_stereo_float((float *)src,
6990 (const float *)src, frames);
6991 } else if (mSrcChannelMask != mDstChannelMask) {
6992 // convert to mono channel again for channel mask conversion (could be skipped
6993 // with further optimization).
Andy Hung97a893e2015-03-29 01:03:07 -07006994 if (mSrcChannelCount == 1) {
Andy Hungd330ee42015-04-20 13:23:41 -07006995 downmix_to_mono_float_from_stereo_float((float *)src,
6996 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006997 }
Andy Hungd330ee42015-04-20 13:23:41 -07006998 // convert to destination format (in place, OK as float is larger than other types)
6999 if (mDstFormat != AUDIO_FORMAT_PCM_FLOAT) {
7000 memcpy_by_audio_format(src, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
7001 frames * mSrcChannelCount);
7002 }
7003 // channel convert and save to dst
7004 memcpy_by_index_array(dst, mDstChannelCount,
7005 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mDstFormat), frames);
7006 return;
Andy Hung97a893e2015-03-29 01:03:07 -07007007 }
Andy Hungd330ee42015-04-20 13:23:41 -07007008 // convert to destination format and save to dst
7009 memcpy_by_audio_format(dst, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
7010 frames * mDstChannelCount);
Andy Hung97a893e2015-03-29 01:03:07 -07007011}
7012
Eric Laurent10351942014-05-08 18:49:52 -07007013bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
7014 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007015{
7016 bool reconfig = false;
7017
Eric Laurent10351942014-05-08 18:49:52 -07007018 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007019
Eric Laurent10351942014-05-08 18:49:52 -07007020 audio_format_t reqFormat = mFormat;
7021 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07007022 // 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 -07007023 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
7024
7025 AudioParameter param = AudioParameter(keyValuePair);
7026 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07007027
7028 // scope for AutoPark extends to end of method
7029 AutoPark<FastCapture> park(mFastCapture);
7030
Eric Laurent10351942014-05-08 18:49:52 -07007031 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
7032 // channel count change can be requested. Do we mandate the first client defines the
7033 // HAL sampling rate and channel count or do we allow changes on the fly?
7034 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
7035 samplingRate = value;
7036 reconfig = true;
7037 }
7038 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07007039 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07007040 status = BAD_VALUE;
7041 } else {
7042 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08007043 reconfig = true;
7044 }
Eric Laurent10351942014-05-08 18:49:52 -07007045 }
7046 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
7047 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07007048 if (!audio_is_input_channel(mask) ||
7049 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007050 status = BAD_VALUE;
7051 } else {
7052 channelMask = mask;
7053 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007054 }
Eric Laurent10351942014-05-08 18:49:52 -07007055 }
7056 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7057 // do not accept frame count changes if tracks are open as the track buffer
7058 // size depends on frame count and correct behavior would not be guaranteed
7059 // if frame count is changed after track creation
7060 if (mActiveTracks.size() > 0) {
7061 status = INVALID_OPERATION;
7062 } else {
7063 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007064 }
Eric Laurent10351942014-05-08 18:49:52 -07007065 }
7066 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7067 // forward device change to effects that have requested to be
7068 // aware of attached audio device.
7069 for (size_t i = 0; i < mEffectChains.size(); i++) {
7070 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08007071 }
Eric Laurent81784c32012-11-19 14:55:58 -08007072
Eric Laurent10351942014-05-08 18:49:52 -07007073 // store input device and output device but do not forward output device to audio HAL.
7074 // Note that status is ignored by the caller for output device
7075 // (see AudioFlinger::setParameters()
7076 if (audio_is_output_devices(value)) {
7077 mOutDevice = value;
7078 status = BAD_VALUE;
7079 } else {
7080 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07007081 if (value != AUDIO_DEVICE_NONE) {
7082 mPrevInDevice = value;
7083 }
Eric Laurent10351942014-05-08 18:49:52 -07007084 // disable AEC and NS if the device is a BT SCO headset supporting those
7085 // pre processings
7086 if (mTracks.size() > 0) {
7087 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7088 mAudioFlinger->btNrecIsOff();
7089 for (size_t i = 0; i < mTracks.size(); i++) {
7090 sp<RecordTrack> track = mTracks[i];
7091 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7092 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08007093 }
7094 }
7095 }
Eric Laurent10351942014-05-08 18:49:52 -07007096 }
7097 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
7098 mAudioSource != (audio_source_t)value) {
7099 // forward device change to effects that have requested to be
7100 // aware of attached audio device.
7101 for (size_t i = 0; i < mEffectChains.size(); i++) {
7102 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08007103 }
Eric Laurent10351942014-05-08 18:49:52 -07007104 mAudioSource = (audio_source_t)value;
7105 }
Glenn Kastene198c362013-08-13 09:13:36 -07007106
Eric Laurent10351942014-05-08 18:49:52 -07007107 if (status == NO_ERROR) {
7108 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7109 keyValuePair.string());
7110 if (status == INVALID_OPERATION) {
7111 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08007112 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7113 keyValuePair.string());
Eric Laurent10351942014-05-08 18:49:52 -07007114 }
7115 if (reconfig) {
7116 if (status == BAD_VALUE &&
Andy Hung97a893e2015-03-29 01:03:07 -07007117 audio_is_linear_pcm(mInput->stream->common.get_format(&mInput->stream->common)) &&
7118 audio_is_linear_pcm(reqFormat) &&
Eric Laurent10351942014-05-08 18:49:52 -07007119 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
Andy Hung97a893e2015-03-29 01:03:07 -07007120 <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate)) &&
Andy Hunge5412692014-05-16 11:25:07 -07007121 audio_channel_count_from_in_mask(
Andy Hungd1abb8f2015-05-05 23:42:34 -07007122 mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007123 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007124 }
Eric Laurent10351942014-05-08 18:49:52 -07007125 if (status == NO_ERROR) {
7126 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007127 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08007128 }
7129 }
Eric Laurent81784c32012-11-19 14:55:58 -08007130 }
Eric Laurent10351942014-05-08 18:49:52 -07007131
Eric Laurent81784c32012-11-19 14:55:58 -08007132 return reconfig;
7133}
7134
7135String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
7136{
Eric Laurent81784c32012-11-19 14:55:58 -08007137 Mutex::Autolock _l(mLock);
7138 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07007139 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08007140 }
7141
Glenn Kastend8ea6992013-07-16 14:17:15 -07007142 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
7143 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08007144 free(s);
7145 return out_s8;
7146}
7147
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007148void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007149 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7150
7151 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08007152
7153 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007154 case AUDIO_INPUT_OPENED:
7155 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07007156 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07007157 desc->mChannelMask = mChannelMask;
7158 desc->mSamplingRate = mSampleRate;
7159 desc->mFormat = mFormat;
7160 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07007161 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07007162 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007163 break;
7164
Eric Laurent73e26b62015-04-27 16:55:58 -07007165 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08007166 default:
7167 break;
7168 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007169 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08007170}
7171
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007172void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007173{
Eric Laurent81784c32012-11-19 14:55:58 -08007174 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
7175 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Andy Hunge5412692014-05-16 11:25:07 -07007176 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Andy Hungd330ee42015-04-20 13:23:41 -07007177 if (mChannelCount > FCC_8) {
7178 ALOGE("HAL channel count %d > %d", mChannelCount, FCC_8);
7179 }
Andy Hung463be252014-07-10 16:56:07 -07007180 mHALFormat = mInput->stream->common.get_format(&mInput->stream->common);
7181 mFormat = mHALFormat;
Andy Hungd330ee42015-04-20 13:23:41 -07007182 if (!audio_is_linear_pcm(mFormat)) {
7183 ALOGE("HAL format %#x is not linear pcm", mFormat);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07007184 }
Eric Laurent665470b2014-07-03 16:37:08 -07007185 mFrameSize = audio_stream_in_frame_size(mInput->stream);
Glenn Kasten548efc92012-11-29 08:48:51 -08007186 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
7187 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007188 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08007189 // 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 -07007190 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08007191 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007192 // A larger value should allow more old data to be read after a track calls start(),
7193 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07007194 //
7195 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08007196 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07007197 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07007198 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07007199 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007200
7201 // TODO optimize audio capture buffer sizes ...
7202 // Here we calculate the size of the sliding buffer used as a source
7203 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
7204 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
7205 // be better to have it derived from the pipe depth in the long term.
7206 // The current value is higher than necessary. However it should not add to latency.
7207
Glenn Kasten85948432013-08-19 12:09:05 -07007208 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Andy Hung0a01c2f2015-09-21 12:44:54 -07007209 size_t bufferSize = (mRsmpInFramesP2 + mFrameCount - 1) * mFrameSize;
7210 (void)posix_memalign(&mRsmpInBuffer, 32, bufferSize);
7211 memset(mRsmpInBuffer, 0, bufferSize); // if posix_memalign fails, will segv here.
Eric Laurent81784c32012-11-19 14:55:58 -08007212
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007213 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
7214 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08007215}
7216
Glenn Kasten5f972c02014-01-13 09:59:31 -08007217uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08007218{
7219 Mutex::Autolock _l(mLock);
7220 if (initCheck() != NO_ERROR) {
7221 return 0;
7222 }
7223
7224 return mInput->stream->get_input_frames_lost(mInput->stream);
7225}
7226
Glenn Kastend848eb42016-03-08 13:42:11 -08007227uint32_t AudioFlinger::RecordThread::hasAudioSession(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08007228{
7229 Mutex::Autolock _l(mLock);
7230 uint32_t result = 0;
7231 if (getEffectChain_l(sessionId) != 0) {
7232 result = EFFECT_SESSION;
7233 }
7234
7235 for (size_t i = 0; i < mTracks.size(); ++i) {
7236 if (sessionId == mTracks[i]->sessionId()) {
7237 result |= TRACK_SESSION;
7238 break;
7239 }
7240 }
7241
7242 return result;
7243}
7244
Glenn Kastend848eb42016-03-08 13:42:11 -08007245KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08007246{
Glenn Kastend848eb42016-03-08 13:42:11 -08007247 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08007248 Mutex::Autolock _l(mLock);
7249 for (size_t j = 0; j < mTracks.size(); ++j) {
7250 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08007251 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08007252 if (ids.indexOfKey(sessionId) < 0) {
7253 ids.add(sessionId, true);
7254 }
7255 }
7256 return ids;
7257}
7258
7259AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7260{
7261 Mutex::Autolock _l(mLock);
7262 AudioStreamIn *input = mInput;
7263 mInput = NULL;
7264 return input;
7265}
7266
7267// this method must always be called either with ThreadBase mLock held or inside the thread loop
7268audio_stream_t* AudioFlinger::RecordThread::stream() const
7269{
7270 if (mInput == NULL) {
7271 return NULL;
7272 }
7273 return &mInput->stream->common;
7274}
7275
7276status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7277{
7278 // only one chain per input thread
7279 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07007280 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08007281 return INVALID_OPERATION;
7282 }
7283 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07007284 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08007285 chain->setInBuffer(NULL);
7286 chain->setOutBuffer(NULL);
7287
7288 checkSuspendOnAddEffectChain_l(chain);
7289
Eric Laurent1b928682014-10-02 19:41:47 -07007290 // make sure enabled pre processing effects state is communicated to the HAL as we
7291 // just moved them to a new input stream.
7292 chain->syncHalEffectsState();
7293
Eric Laurent81784c32012-11-19 14:55:58 -08007294 mEffectChains.add(chain);
7295
7296 return NO_ERROR;
7297}
7298
7299size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7300{
7301 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7302 ALOGW_IF(mEffectChains.size() != 1,
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007303 "removeEffectChain_l() %p invalid chain size %zu on thread %p",
Eric Laurent81784c32012-11-19 14:55:58 -08007304 chain.get(), mEffectChains.size(), this);
7305 if (mEffectChains.size() == 1) {
7306 mEffectChains.removeAt(0);
7307 }
7308 return 0;
7309}
7310
Eric Laurent1c333e22014-05-20 10:48:17 -07007311status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7312 audio_patch_handle_t *handle)
7313{
7314 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007315
7316 // store new device and send to effects
7317 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07007318 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07007319 for (size_t i = 0; i < mEffectChains.size(); i++) {
7320 mEffectChains[i]->setDevice_l(mInDevice);
7321 }
7322
7323 // disable AEC and NS if the device is a BT SCO headset supporting those
7324 // pre processings
7325 if (mTracks.size() > 0) {
7326 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7327 mAudioFlinger->btNrecIsOff();
7328 for (size_t i = 0; i < mTracks.size(); i++) {
7329 sp<RecordTrack> track = mTracks[i];
7330 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7331 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
7332 }
7333 }
7334
7335 // store new source and send to effects
7336 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7337 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07007338 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07007339 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07007340 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007341 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007342
Eric Laurent054d9d32015-04-24 08:48:48 -07007343 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007344 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
7345 status = hwDevice->create_audio_patch(hwDevice,
7346 patch->num_sources,
7347 patch->sources,
7348 patch->num_sinks,
7349 patch->sinks,
7350 handle);
7351 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007352 char *address;
7353 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7354 address = audio_device_address_to_parameter(
7355 patch->sources[0].ext.device.type,
7356 patch->sources[0].ext.device.address);
7357 } else {
7358 address = (char *)calloc(1, 1);
7359 }
7360 AudioParameter param = AudioParameter(String8(address));
7361 free(address);
7362 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING),
7363 (int)patch->sources[0].ext.device.type);
7364 param.addInt(String8(AUDIO_PARAMETER_STREAM_INPUT_SOURCE),
7365 (int)patch->sinks[0].ext.mix.usecase.source);
7366 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7367 param.toString().string());
7368 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07007369 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007370
Eric Laurente8726fe2015-06-26 09:39:24 -07007371 if (mInDevice != mPrevInDevice) {
7372 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7373 mPrevInDevice = mInDevice;
7374 }
Eric Laurent296fb132015-05-01 11:38:42 -07007375
Eric Laurent1c333e22014-05-20 10:48:17 -07007376 return status;
7377}
7378
7379status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7380{
7381 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007382
7383 mInDevice = AUDIO_DEVICE_NONE;
7384
Eric Laurent1c333e22014-05-20 10:48:17 -07007385 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
7386 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
7387 status = hwDevice->release_audio_patch(hwDevice, handle);
7388 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007389 AudioParameter param;
7390 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
7391 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7392 param.toString().string());
Eric Laurent1c333e22014-05-20 10:48:17 -07007393 }
7394 return status;
7395}
7396
Eric Laurent83b88082014-06-20 18:31:16 -07007397void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
7398{
7399 Mutex::Autolock _l(mLock);
7400 mTracks.add(record);
7401}
7402
7403void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
7404{
7405 Mutex::Autolock _l(mLock);
7406 destroyTrack_l(record);
7407}
7408
7409void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
7410{
7411 ThreadBase::getAudioPortConfig(config);
7412 config->role = AUDIO_PORT_ROLE_SINK;
7413 config->ext.mix.hw_module = mInput->audioHwDev->handle();
7414 config->ext.mix.usecase.source = mAudioSource;
7415}
Eric Laurent1c333e22014-05-20 10:48:17 -07007416
Glenn Kasten63238ef2015-03-02 15:50:29 -08007417} // namespace android