blob: bd7f6d57ccb515d02f50a441152a481f8fe33114 [file] [log] [blame]
Eric Laurent81784c32012-11-19 14:55:58 -08001/*
2**
3** Copyright 2012, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
Alex Ray371eb972012-11-30 11:11:54 -080021#define ATRACE_TAG ATRACE_TAG_AUDIO
Eric Laurent81784c32012-11-19 14:55:58 -080022
Glenn Kasten153b9fe2013-07-15 11:23:36 -070023#include "Configuration.h"
Eric Laurent81784c32012-11-19 14:55:58 -080024#include <math.h>
25#include <fcntl.h>
Glenn Kastenad8510a2015-02-17 16:24:07 -080026#include <linux/futex.h>
Eric Laurent81784c32012-11-19 14:55:58 -080027#include <sys/stat.h>
Glenn Kastenad8510a2015-02-17 16:24:07 -080028#include <sys/syscall.h>
Eric Laurent81784c32012-11-19 14:55:58 -080029#include <cutils/properties.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070030#include <media/AudioParameter.h>
Andy Hungcd044842014-08-07 11:04:34 -070031#include <media/AudioResamplerPublic.h>
Eric Laurent81784c32012-11-19 14:55:58 -080032#include <utils/Log.h>
Alex Ray371eb972012-11-30 11:11:54 -080033#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080034
35#include <private/media/AudioTrackShared.h>
36#include <hardware/audio.h>
37#include <audio_effects/effect_ns.h>
38#include <audio_effects/effect_aec.h>
Andy Hung2ddee192015-12-18 17:34:44 -080039#include <audio_utils/conversion.h>
Eric Laurent81784c32012-11-19 14:55:58 -080040#include <audio_utils/primitives.h>
Andy Hung98ef9782014-03-04 14:46:50 -080041#include <audio_utils/format.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070042#include <audio_utils/minifloat.h>
Eric Laurent81784c32012-11-19 14:55:58 -080043
44// NBAIO implementations
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070045#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080046#include <media/nbaio/AudioStreamOutSink.h>
47#include <media/nbaio/MonoPipe.h>
48#include <media/nbaio/MonoPipeReader.h>
49#include <media/nbaio/Pipe.h>
50#include <media/nbaio/PipeReader.h>
51#include <media/nbaio/SourceAudioBufferProvider.h>
Wei Jia3f273d12015-11-24 09:06:49 -080052#include <mediautils/BatteryNotifier.h>
Eric Laurent81784c32012-11-19 14:55:58 -080053
54#include <powermanager/PowerManager.h>
55
Eric Laurent81784c32012-11-19 14:55:58 -080056#include "AudioFlinger.h"
57#include "AudioMixer.h"
Andy Hungd330ee42015-04-20 13:23:41 -070058#include "BufferProviders.h"
Eric Laurent81784c32012-11-19 14:55:58 -080059#include "FastMixer.h"
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070060#include "FastCapture.h"
Eric Laurent81784c32012-11-19 14:55:58 -080061#include "ServiceUtilities.h"
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -070062#include "mediautils/SchedulingPolicyService.h"
Eric Laurent81784c32012-11-19 14:55:58 -080063
Eric Laurent81784c32012-11-19 14:55:58 -080064#ifdef ADD_BATTERY_DATA
65#include <media/IMediaPlayerService.h>
66#include <media/IMediaDeathNotifier.h>
67#endif
68
Eric Laurent81784c32012-11-19 14:55:58 -080069#ifdef DEBUG_CPU_USAGE
70#include <cpustats/CentralTendencyStatistics.h>
71#include <cpustats/ThreadCpuUsage.h>
72#endif
73
Glenn Kastenc05b8d72016-03-24 09:48:17 -070074#include "AutoPark.h"
75
Eric Laurent81784c32012-11-19 14:55:58 -080076// ----------------------------------------------------------------------------
77
78// Note: the following macro is used for extremely verbose logging message. In
79// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
80// 0; but one side effect of this is to turn all LOGV's as well. Some messages
81// are so verbose that we want to suppress them even when we have ALOG_ASSERT
82// turned on. Do not uncomment the #def below unless you really know what you
83// are doing and want to see all of the extremely verbose messages.
84//#define VERY_VERY_VERBOSE_LOGGING
85#ifdef VERY_VERY_VERBOSE_LOGGING
86#define ALOGVV ALOGV
87#else
88#define ALOGVV(a...) do { } while(0)
89#endif
90
Andy Hung6770c6f2015-04-07 13:43:36 -070091// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -070092#define max(a, b) ((a) > (b) ? (a) : (b))
Andy Hung6770c6f2015-04-07 13:43:36 -070093template <typename T>
94static inline T min(const T& a, const T& b)
95{
96 return a < b ? a : b;
97}
Glenn Kasten49d00ad2014-07-21 11:22:03 -070098
Andy Hungd330ee42015-04-20 13:23:41 -070099#ifndef ARRAY_SIZE
100#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
101#endif
102
Eric Laurent81784c32012-11-19 14:55:58 -0800103namespace android {
104
105// retry counts for buffer fill timeout
106// 50 * ~20msecs = 1 second
107static const int8_t kMaxTrackRetries = 50;
108static const int8_t kMaxTrackStartupRetries = 50;
109// allow less retry attempts on direct output thread.
110// direct outputs can be a scarce resource in audio hardware and should
111// be released as quickly as possible.
112static const int8_t kMaxTrackRetriesDirect = 2;
Eric Laurent51716182016-02-29 18:00:56 -0800113// retry count before removing active track in case of underrun on offloaded thread:
114// we need to make sure that AudioTrack client has enough time to send large buffers
115//FIXME may be more appropriate if expressed in time units. Need to revise how underrun is handled
116// for offloaded tracks
117static const int8_t kMaxTrackRetriesOffload = 10;
118static const int8_t kMaxTrackStartupRetriesOffload = 100;
119
Eric Laurent81784c32012-11-19 14:55:58 -0800120
121// don't warn about blocked writes or record buffer overflows more often than this
122static const nsecs_t kWarningThrottleNs = seconds(5);
123
124// RecordThread loop sleep time upon application overrun or audio HAL read error
125static const int kRecordThreadSleepUs = 5000;
126
Eric Laurent10351942014-05-08 18:49:52 -0700127// maximum time to wait in sendConfigEvent_l() for a status to be received
128static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800129
130// minimum sleep time for the mixer thread loop when tracks are active but in underrun
131static const uint32_t kMinThreadSleepTimeUs = 5000;
132// maximum divider applied to the active sleep time in the mixer thread loop
133static const uint32_t kMaxThreadSleepTimeShift = 2;
134
Andy Hung09a50072014-02-27 14:30:47 -0800135// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700136// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800137static const uint32_t kMinNormalSinkBufferSizeMs = 20;
138// maximum normal sink buffer size
139static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800140
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700141// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
142// FIXME This should be based on experimentally observed scheduling jitter
143static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
144
Eric Laurent972a1732013-09-04 09:42:59 -0700145// Offloaded output thread standby delay: allows track transition without going to standby
146static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
147
Eric Laurent51716182016-02-29 18:00:56 -0800148// Direct output thread minimum sleep time in idle or active(underrun) state
149static const nsecs_t kDirectMinSleepTimeUs = 10000;
150
151// Offloaded output bit rate in bits per second when unknown.
152// Used for sleep time calculation, so use a high default bitrate to be conservative on sleep time.
153static const uint32_t kOffloadDefaultBitRateBps = 1500000;
154
155
Eric Laurent81784c32012-11-19 14:55:58 -0800156// Whether to use fast mixer
157static const enum {
158 FastMixer_Never, // never initialize or use: for debugging only
159 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
160 // normal mixer multiplier is 1
161 FastMixer_Static, // initialize if needed, then use all the time if initialized,
162 // multiplier is calculated based on min & max normal mixer buffer size
163 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
164 // multiplier is calculated based on min & max normal mixer buffer size
165 // FIXME for FastMixer_Dynamic:
166 // Supporting this option will require fixing HALs that can't handle large writes.
167 // For example, one HAL implementation returns an error from a large write,
168 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
169 // We could either fix the HAL implementations, or provide a wrapper that breaks
170 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
171} kUseFastMixer = FastMixer_Static;
172
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700173// Whether to use fast capture
174static const enum {
175 FastCapture_Never, // never initialize or use: for debugging only
176 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
177 FastCapture_Static, // initialize if needed, then use all the time if initialized
178} kUseFastCapture = FastCapture_Static;
179
Eric Laurent81784c32012-11-19 14:55:58 -0800180// Priorities for requestPriority
181static const int kPriorityAudioApp = 2;
182static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700183static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800184
Glenn Kastenea38ee72016-04-18 11:08:01 -0700185// IAudioFlinger::createTrack() has an in/out parameter 'pFrameCount' for the total size of the
186// track buffer in shared memory. Zero on input means to use a default value. For fast tracks,
187// AudioFlinger derives the default from HAL buffer size and 'fast track multiplier'.
Glenn Kasten03490092014-05-27 12:30:54 -0700188
189// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800190static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800191
Glenn Kasten03490092014-05-27 12:30:54 -0700192// The minimum and maximum allowed values
193static const int kFastTrackMultiplierMin = 1;
194static const int kFastTrackMultiplierMax = 2;
195
196// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
197static int sFastTrackMultiplier = kFastTrackMultiplier;
198
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700199// See Thread::readOnlyHeap().
200// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
201// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
202// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Glenn Kasten9f81de32014-07-27 15:02:23 -0700203static const size_t kRecordThreadReadOnlyHeapSize = 0x2000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700204
Eric Laurent81784c32012-11-19 14:55:58 -0800205// ----------------------------------------------------------------------------
206
Glenn Kasten03490092014-05-27 12:30:54 -0700207static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
208
209static void sFastTrackMultiplierInit()
210{
211 char value[PROPERTY_VALUE_MAX];
212 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
213 char *endptr;
214 unsigned long ul = strtoul(value, &endptr, 0);
215 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
216 sFastTrackMultiplier = (int) ul;
217 }
218 }
219}
220
221// ----------------------------------------------------------------------------
222
Eric Laurent81784c32012-11-19 14:55:58 -0800223#ifdef ADD_BATTERY_DATA
224// To collect the amplifier usage
225static void addBatteryData(uint32_t params) {
226 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
227 if (service == NULL) {
228 // it already logged
229 return;
230 }
231
232 service->addBatteryData(params);
233}
234#endif
235
Andy Hung3f0c9022016-01-15 17:49:46 -0800236// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
237struct {
238 // call when you acquire a partial wakelock
239 void acquire(const sp<IBinder> &wakeLockToken) {
240 pthread_mutex_lock(&mLock);
241 if (wakeLockToken.get() == nullptr) {
242 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
243 } else {
244 if (mCount == 0) {
245 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
246 }
247 ++mCount;
248 }
249 pthread_mutex_unlock(&mLock);
250 }
251
252 // call when you release a partial wakelock.
253 void release(const sp<IBinder> &wakeLockToken) {
254 if (wakeLockToken.get() == nullptr) {
255 return;
256 }
257 pthread_mutex_lock(&mLock);
258 if (--mCount < 0) {
259 ALOGE("negative wakelock count");
260 mCount = 0;
261 }
262 pthread_mutex_unlock(&mLock);
263 }
264
265 // retrieves the boottime timebase offset from monotonic.
266 int64_t getBoottimeOffset() {
267 pthread_mutex_lock(&mLock);
268 int64_t boottimeOffset = mBoottimeOffset;
269 pthread_mutex_unlock(&mLock);
270 return boottimeOffset;
271 }
272
273 // Adjusts the timebase offset between TIMEBASE_MONOTONIC
274 // and the selected timebase.
275 // Currently only TIMEBASE_BOOTTIME is allowed.
276 //
277 // This only needs to be called upon acquiring the first partial wakelock
278 // after all other partial wakelocks are released.
279 //
280 // We do an empirical measurement of the offset rather than parsing
281 // /proc/timer_list since the latter is not a formal kernel ABI.
282 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
283 int clockbase;
284 switch (timebase) {
285 case ExtendedTimestamp::TIMEBASE_BOOTTIME:
286 clockbase = SYSTEM_TIME_BOOTTIME;
287 break;
288 default:
289 LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
290 break;
291 }
292 // try three times to get the clock offset, choose the one
293 // with the minimum gap in measurements.
294 const int tries = 3;
295 nsecs_t bestGap, measured;
296 for (int i = 0; i < tries; ++i) {
297 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
298 const nsecs_t tbase = systemTime(clockbase);
299 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
300 const nsecs_t gap = tmono2 - tmono;
301 if (i == 0 || gap < bestGap) {
302 bestGap = gap;
303 measured = tbase - ((tmono + tmono2) >> 1);
304 }
305 }
306
307 // to avoid micro-adjusting, we don't change the timebase
308 // unless it is significantly different.
309 //
310 // Assumption: It probably takes more than toleranceNs to
311 // suspend and resume the device.
312 static int64_t toleranceNs = 10000; // 10 us
313 if (llabs(*offset - measured) > toleranceNs) {
314 ALOGV("Adjusting timebase offset old: %lld new: %lld",
315 (long long)*offset, (long long)measured);
316 *offset = measured;
317 }
318 }
319
320 pthread_mutex_t mLock;
321 int32_t mCount;
322 int64_t mBoottimeOffset;
323} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
Eric Laurent81784c32012-11-19 14:55:58 -0800324
325// ----------------------------------------------------------------------------
326// CPU Stats
327// ----------------------------------------------------------------------------
328
329class CpuStats {
330public:
331 CpuStats();
332 void sample(const String8 &title);
333#ifdef DEBUG_CPU_USAGE
334private:
335 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
336 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
337
338 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
339
340 int mCpuNum; // thread's current CPU number
341 int mCpukHz; // frequency of thread's current CPU in kHz
342#endif
343};
344
345CpuStats::CpuStats()
346#ifdef DEBUG_CPU_USAGE
347 : mCpuNum(-1), mCpukHz(-1)
348#endif
349{
350}
351
Glenn Kasten0f11b512014-01-31 16:18:54 -0800352void CpuStats::sample(const String8 &title
353#ifndef DEBUG_CPU_USAGE
354 __unused
355#endif
356 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800357#ifdef DEBUG_CPU_USAGE
358 // get current thread's delta CPU time in wall clock ns
359 double wcNs;
360 bool valid = mCpuUsage.sampleAndEnable(wcNs);
361
362 // record sample for wall clock statistics
363 if (valid) {
364 mWcStats.sample(wcNs);
365 }
366
367 // get the current CPU number
368 int cpuNum = sched_getcpu();
369
370 // get the current CPU frequency in kHz
371 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
372
373 // check if either CPU number or frequency changed
374 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
375 mCpuNum = cpuNum;
376 mCpukHz = cpukHz;
377 // ignore sample for purposes of cycles
378 valid = false;
379 }
380
381 // if no change in CPU number or frequency, then record sample for cycle statistics
382 if (valid && mCpukHz > 0) {
383 double cycles = wcNs * cpukHz * 0.000001;
384 mHzStats.sample(cycles);
385 }
386
387 unsigned n = mWcStats.n();
388 // mCpuUsage.elapsed() is expensive, so don't call it every loop
389 if ((n & 127) == 1) {
390 long long elapsed = mCpuUsage.elapsed();
391 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
392 double perLoop = elapsed / (double) n;
393 double perLoop100 = perLoop * 0.01;
394 double perLoop1k = perLoop * 0.001;
395 double mean = mWcStats.mean();
396 double stddev = mWcStats.stddev();
397 double minimum = mWcStats.minimum();
398 double maximum = mWcStats.maximum();
399 double meanCycles = mHzStats.mean();
400 double stddevCycles = mHzStats.stddev();
401 double minCycles = mHzStats.minimum();
402 double maxCycles = mHzStats.maximum();
403 mCpuUsage.resetElapsed();
404 mWcStats.reset();
405 mHzStats.reset();
406 ALOGD("CPU usage for %s over past %.1f secs\n"
407 " (%u mixer loops at %.1f mean ms per loop):\n"
408 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
409 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
410 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
411 title.string(),
412 elapsed * .000000001, n, perLoop * .000001,
413 mean * .001,
414 stddev * .001,
415 minimum * .001,
416 maximum * .001,
417 mean / perLoop100,
418 stddev / perLoop100,
419 minimum / perLoop100,
420 maximum / perLoop100,
421 meanCycles / perLoop1k,
422 stddevCycles / perLoop1k,
423 minCycles / perLoop1k,
424 maxCycles / perLoop1k);
425
426 }
427 }
428#endif
429};
430
431// ----------------------------------------------------------------------------
432// ThreadBase
433// ----------------------------------------------------------------------------
434
Glenn Kasten97b7b752014-09-28 13:04:24 -0700435// static
436const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
437{
438 switch (type) {
439 case MIXER:
440 return "MIXER";
441 case DIRECT:
442 return "DIRECT";
443 case DUPLICATING:
444 return "DUPLICATING";
445 case RECORD:
446 return "RECORD";
447 case OFFLOAD:
448 return "OFFLOAD";
449 default:
450 return "unknown";
451 }
452}
453
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800454String8 devicesToString(audio_devices_t devices)
455{
456 static const struct mapping {
457 audio_devices_t mDevices;
458 const char * mString;
459 } mappingsOut[] = {
Glenn Kasten818da522015-12-02 13:53:26 -0800460 {AUDIO_DEVICE_OUT_EARPIECE, "EARPIECE"},
461 {AUDIO_DEVICE_OUT_SPEAKER, "SPEAKER"},
462 {AUDIO_DEVICE_OUT_WIRED_HEADSET, "WIRED_HEADSET"},
463 {AUDIO_DEVICE_OUT_WIRED_HEADPHONE, "WIRED_HEADPHONE"},
464 {AUDIO_DEVICE_OUT_BLUETOOTH_SCO, "BLUETOOTH_SCO"},
465 {AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET, "BLUETOOTH_SCO_HEADSET"},
466 {AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT, "BLUETOOTH_SCO_CARKIT"},
467 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, "BLUETOOTH_A2DP"},
468 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,"BLUETOOTH_A2DP_HEADPHONES"},
469 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER, "BLUETOOTH_A2DP_SPEAKER"},
470 {AUDIO_DEVICE_OUT_AUX_DIGITAL, "AUX_DIGITAL"},
471 {AUDIO_DEVICE_OUT_HDMI, "HDMI"},
472 {AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET,"ANLG_DOCK_HEADSET"},
473 {AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET,"DGTL_DOCK_HEADSET"},
474 {AUDIO_DEVICE_OUT_USB_ACCESSORY, "USB_ACCESSORY"},
475 {AUDIO_DEVICE_OUT_USB_DEVICE, "USB_DEVICE"},
476 {AUDIO_DEVICE_OUT_TELEPHONY_TX, "TELEPHONY_TX"},
477 {AUDIO_DEVICE_OUT_LINE, "LINE"},
478 {AUDIO_DEVICE_OUT_HDMI_ARC, "HDMI_ARC"},
479 {AUDIO_DEVICE_OUT_SPDIF, "SPDIF"},
480 {AUDIO_DEVICE_OUT_FM, "FM"},
481 {AUDIO_DEVICE_OUT_AUX_LINE, "AUX_LINE"},
482 {AUDIO_DEVICE_OUT_SPEAKER_SAFE, "SPEAKER_SAFE"},
483 {AUDIO_DEVICE_OUT_IP, "IP"},
Eric Laurent58545be2016-02-22 18:54:20 -0800484 {AUDIO_DEVICE_OUT_BUS, "BUS"},
Glenn Kasten818da522015-12-02 13:53:26 -0800485 {AUDIO_DEVICE_NONE, "NONE"}, // must be last
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800486 }, mappingsIn[] = {
Glenn Kasten818da522015-12-02 13:53:26 -0800487 {AUDIO_DEVICE_IN_COMMUNICATION, "COMMUNICATION"},
488 {AUDIO_DEVICE_IN_AMBIENT, "AMBIENT"},
489 {AUDIO_DEVICE_IN_BUILTIN_MIC, "BUILTIN_MIC"},
490 {AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET, "BLUETOOTH_SCO_HEADSET"},
491 {AUDIO_DEVICE_IN_WIRED_HEADSET, "WIRED_HEADSET"},
492 {AUDIO_DEVICE_IN_AUX_DIGITAL, "AUX_DIGITAL"},
493 {AUDIO_DEVICE_IN_VOICE_CALL, "VOICE_CALL"},
494 {AUDIO_DEVICE_IN_TELEPHONY_RX, "TELEPHONY_RX"},
495 {AUDIO_DEVICE_IN_BACK_MIC, "BACK_MIC"},
496 {AUDIO_DEVICE_IN_REMOTE_SUBMIX, "REMOTE_SUBMIX"},
497 {AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET, "ANLG_DOCK_HEADSET"},
498 {AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET, "DGTL_DOCK_HEADSET"},
499 {AUDIO_DEVICE_IN_USB_ACCESSORY, "USB_ACCESSORY"},
500 {AUDIO_DEVICE_IN_USB_DEVICE, "USB_DEVICE"},
501 {AUDIO_DEVICE_IN_FM_TUNER, "FM_TUNER"},
502 {AUDIO_DEVICE_IN_TV_TUNER, "TV_TUNER"},
503 {AUDIO_DEVICE_IN_LINE, "LINE"},
504 {AUDIO_DEVICE_IN_SPDIF, "SPDIF"},
505 {AUDIO_DEVICE_IN_BLUETOOTH_A2DP, "BLUETOOTH_A2DP"},
506 {AUDIO_DEVICE_IN_LOOPBACK, "LOOPBACK"},
507 {AUDIO_DEVICE_IN_IP, "IP"},
Eric Laurent58545be2016-02-22 18:54:20 -0800508 {AUDIO_DEVICE_IN_BUS, "BUS"},
Glenn Kasten818da522015-12-02 13:53:26 -0800509 {AUDIO_DEVICE_NONE, "NONE"}, // must be last
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800510 };
511 String8 result;
512 audio_devices_t allDevices = AUDIO_DEVICE_NONE;
513 const mapping *entry;
514 if (devices & AUDIO_DEVICE_BIT_IN) {
515 devices &= ~AUDIO_DEVICE_BIT_IN;
516 entry = mappingsIn;
517 } else {
518 entry = mappingsOut;
519 }
520 for ( ; entry->mDevices != AUDIO_DEVICE_NONE; entry++) {
521 allDevices = (audio_devices_t) (allDevices | entry->mDevices);
522 if (devices & entry->mDevices) {
523 if (!result.isEmpty()) {
524 result.append("|");
525 }
526 result.append(entry->mString);
527 }
528 }
529 if (devices & ~allDevices) {
530 if (!result.isEmpty()) {
531 result.append("|");
532 }
533 result.appendFormat("0x%X", devices & ~allDevices);
534 }
535 if (result.isEmpty()) {
536 result.append(entry->mString);
537 }
538 return result;
539}
540
541String8 inputFlagsToString(audio_input_flags_t flags)
542{
543 static const struct mapping {
544 audio_input_flags_t mFlag;
545 const char * mString;
546 } mappings[] = {
Glenn Kasten818da522015-12-02 13:53:26 -0800547 {AUDIO_INPUT_FLAG_FAST, "FAST"},
548 {AUDIO_INPUT_FLAG_HW_HOTWORD, "HW_HOTWORD"},
549 {AUDIO_INPUT_FLAG_RAW, "RAW"},
550 {AUDIO_INPUT_FLAG_SYNC, "SYNC"},
551 {AUDIO_INPUT_FLAG_NONE, "NONE"}, // must be last
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800552 };
553 String8 result;
554 audio_input_flags_t allFlags = AUDIO_INPUT_FLAG_NONE;
555 const mapping *entry;
556 for (entry = mappings; entry->mFlag != AUDIO_INPUT_FLAG_NONE; entry++) {
557 allFlags = (audio_input_flags_t) (allFlags | entry->mFlag);
558 if (flags & entry->mFlag) {
559 if (!result.isEmpty()) {
560 result.append("|");
561 }
562 result.append(entry->mString);
563 }
564 }
565 if (flags & ~allFlags) {
566 if (!result.isEmpty()) {
567 result.append("|");
568 }
569 result.appendFormat("0x%X", flags & ~allFlags);
570 }
571 if (result.isEmpty()) {
572 result.append(entry->mString);
573 }
574 return result;
575}
576
577String8 outputFlagsToString(audio_output_flags_t flags)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700578{
579 static const struct mapping {
580 audio_output_flags_t mFlag;
581 const char * mString;
582 } mappings[] = {
Glenn Kasten818da522015-12-02 13:53:26 -0800583 {AUDIO_OUTPUT_FLAG_DIRECT, "DIRECT"},
584 {AUDIO_OUTPUT_FLAG_PRIMARY, "PRIMARY"},
585 {AUDIO_OUTPUT_FLAG_FAST, "FAST"},
586 {AUDIO_OUTPUT_FLAG_DEEP_BUFFER, "DEEP_BUFFER"},
587 {AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,"COMPRESS_OFFLOAD"},
588 {AUDIO_OUTPUT_FLAG_NON_BLOCKING, "NON_BLOCKING"},
589 {AUDIO_OUTPUT_FLAG_HW_AV_SYNC, "HW_AV_SYNC"},
590 {AUDIO_OUTPUT_FLAG_RAW, "RAW"},
591 {AUDIO_OUTPUT_FLAG_SYNC, "SYNC"},
592 {AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO, "IEC958_NONAUDIO"},
593 {AUDIO_OUTPUT_FLAG_NONE, "NONE"}, // must be last
Glenn Kasten97b7b752014-09-28 13:04:24 -0700594 };
595 String8 result;
596 audio_output_flags_t allFlags = AUDIO_OUTPUT_FLAG_NONE;
597 const mapping *entry;
598 for (entry = mappings; entry->mFlag != AUDIO_OUTPUT_FLAG_NONE; entry++) {
599 allFlags = (audio_output_flags_t) (allFlags | entry->mFlag);
600 if (flags & entry->mFlag) {
601 if (!result.isEmpty()) {
602 result.append("|");
603 }
604 result.append(entry->mString);
605 }
606 }
607 if (flags & ~allFlags) {
608 if (!result.isEmpty()) {
609 result.append("|");
610 }
611 result.appendFormat("0x%X", flags & ~allFlags);
612 }
613 if (result.isEmpty()) {
614 result.append(entry->mString);
615 }
616 return result;
617}
618
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800619const char *sourceToString(audio_source_t source)
620{
621 switch (source) {
622 case AUDIO_SOURCE_DEFAULT: return "default";
623 case AUDIO_SOURCE_MIC: return "mic";
624 case AUDIO_SOURCE_VOICE_UPLINK: return "voice uplink";
625 case AUDIO_SOURCE_VOICE_DOWNLINK: return "voice downlink";
626 case AUDIO_SOURCE_VOICE_CALL: return "voice call";
627 case AUDIO_SOURCE_CAMCORDER: return "camcorder";
628 case AUDIO_SOURCE_VOICE_RECOGNITION: return "voice recognition";
629 case AUDIO_SOURCE_VOICE_COMMUNICATION: return "voice communication";
630 case AUDIO_SOURCE_REMOTE_SUBMIX: return "remote submix";
rago8a397d52015-12-02 11:27:57 -0800631 case AUDIO_SOURCE_UNPROCESSED: return "unprocessed";
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800632 case AUDIO_SOURCE_FM_TUNER: return "FM tuner";
633 case AUDIO_SOURCE_HOTWORD: return "hotword";
634 default: return "unknown";
635 }
636}
637
Eric Laurent81784c32012-11-19 14:55:58 -0800638AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -0700639 audio_devices_t outDevice, audio_devices_t inDevice, type_t type, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -0800640 : Thread(false /*canCallJava*/),
641 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700642 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700643 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800644 // are set by PlaybackThread::readOutputParameters_l() or
645 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700646 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800647 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700648 mPrevOutDevice(AUDIO_DEVICE_NONE), mPrevInDevice(AUDIO_DEVICE_NONE),
649 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800650 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700651 mDeathRecipient(new PMDeathRecipient(this)),
Wei Jia3f273d12015-11-24 09:06:49 -0800652 mSystemReady(systemReady),
653 mNotifiedBatteryStart(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800654{
Eric Laurent296fb132015-05-01 11:38:42 -0700655 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800656}
657
658AudioFlinger::ThreadBase::~ThreadBase()
659{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700660 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700661 mConfigEvents.clear();
662
Eric Laurent81784c32012-11-19 14:55:58 -0800663 // do not lock the mutex in destructor
664 releaseWakeLock_l();
665 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800666 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800667 binder->unlinkToDeath(mDeathRecipient);
668 }
669}
670
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700671status_t AudioFlinger::ThreadBase::readyToRun()
672{
673 status_t status = initCheck();
674 if (status == NO_ERROR) {
675 ALOGI("AudioFlinger's thread %p ready to run", this);
676 } else {
677 ALOGE("No working audio driver found.");
678 }
679 return status;
680}
681
Eric Laurent81784c32012-11-19 14:55:58 -0800682void AudioFlinger::ThreadBase::exit()
683{
684 ALOGV("ThreadBase::exit");
685 // do any cleanup required for exit to succeed
686 preExit();
687 {
688 // This lock prevents the following race in thread (uniprocessor for illustration):
689 // if (!exitPending()) {
690 // // context switch from here to exit()
691 // // exit() calls requestExit(), what exitPending() observes
692 // // exit() calls signal(), which is dropped since no waiters
693 // // context switch back from exit() to here
694 // mWaitWorkCV.wait(...);
695 // // now thread is hung
696 // }
697 AutoMutex lock(mLock);
698 requestExit();
699 mWaitWorkCV.broadcast();
700 }
701 // When Thread::requestExitAndWait is made virtual and this method is renamed to
702 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
703 requestExitAndWait();
704}
705
706status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
707{
Eric Laurent81784c32012-11-19 14:55:58 -0800708 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
709 Mutex::Autolock _l(mLock);
710
Eric Laurent10351942014-05-08 18:49:52 -0700711 return sendSetParameterConfigEvent_l(keyValuePairs);
712}
713
714// sendConfigEvent_l() must be called with ThreadBase::mLock held
715// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
716status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
717{
718 status_t status = NO_ERROR;
719
Eric Laurent72e3f392015-05-20 14:43:50 -0700720 if (event->mRequiresSystemReady && !mSystemReady) {
721 event->mWaitStatus = false;
722 mPendingConfigEvents.add(event);
723 return status;
724 }
Eric Laurent10351942014-05-08 18:49:52 -0700725 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700726 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800727 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700728 mLock.unlock();
729 {
730 Mutex::Autolock _l(event->mLock);
731 while (event->mWaitStatus) {
732 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
733 event->mStatus = TIMED_OUT;
734 event->mWaitStatus = false;
735 }
736 }
737 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800738 }
Eric Laurent10351942014-05-08 18:49:52 -0700739 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800740 return status;
741}
742
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700743void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800744{
745 Mutex::Autolock _l(mLock);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700746 sendIoConfigEvent_l(event, pid);
Eric Laurent81784c32012-11-19 14:55:58 -0800747}
748
749// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700750void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800751{
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700752 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid);
Eric Laurent10351942014-05-08 18:49:52 -0700753 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800754}
755
Eric Laurent72e3f392015-05-20 14:43:50 -0700756void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio)
757{
758 Mutex::Autolock _l(mLock);
759 sendPrioConfigEvent_l(pid, tid, prio);
760}
761
Eric Laurent81784c32012-11-19 14:55:58 -0800762// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
763void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
764{
Eric Laurent10351942014-05-08 18:49:52 -0700765 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio);
766 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800767}
768
Eric Laurent10351942014-05-08 18:49:52 -0700769// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
770status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800771{
Andy Hung2ddee192015-12-18 17:34:44 -0800772 sp<ConfigEvent> configEvent;
773 AudioParameter param(keyValuePair);
774 int value;
775 if (param.getInt(String8(AUDIO_PARAMETER_MONO_OUTPUT), value) == NO_ERROR) {
776 setMasterMono_l(value != 0);
777 if (param.size() == 1) {
778 return NO_ERROR; // should be a solo parameter - we don't pass down
779 }
780 param.remove(String8(AUDIO_PARAMETER_MONO_OUTPUT));
781 configEvent = new SetParameterConfigEvent(param.toString());
782 } else {
783 configEvent = new SetParameterConfigEvent(keyValuePair);
784 }
Eric Laurent10351942014-05-08 18:49:52 -0700785 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700786}
787
Eric Laurent1c333e22014-05-20 10:48:17 -0700788status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
789 const struct audio_patch *patch,
790 audio_patch_handle_t *handle)
791{
792 Mutex::Autolock _l(mLock);
793 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
794 status_t status = sendConfigEvent_l(configEvent);
795 if (status == NO_ERROR) {
796 CreateAudioPatchConfigEventData *data =
797 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
798 *handle = data->mHandle;
799 }
800 return status;
801}
802
803status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
804 const audio_patch_handle_t handle)
805{
806 Mutex::Autolock _l(mLock);
807 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
808 return sendConfigEvent_l(configEvent);
809}
810
811
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700812// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700813void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700814{
Eric Laurent10351942014-05-08 18:49:52 -0700815 bool configChanged = false;
816
Eric Laurent81784c32012-11-19 14:55:58 -0800817 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700818 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700819 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800820 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700821 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700822 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700823 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
824 // FIXME Need to understand why this has to be done asynchronously
825 int err = requestPriority(data->mPid, data->mTid, data->mPrio,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700826 true /*asynchronous*/);
827 if (err != 0) {
828 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700829 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700830 }
831 } break;
832 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700833 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700834 ioConfigChanged(data->mEvent, data->mPid);
Eric Laurent10351942014-05-08 18:49:52 -0700835 } break;
836 case CFG_EVENT_SET_PARAMETER: {
837 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
838 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
839 configChanged = true;
Glenn Kastend5418eb2013-08-14 13:11:06 -0700840 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700841 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700842 case CFG_EVENT_CREATE_AUDIO_PATCH: {
843 CreateAudioPatchConfigEventData *data =
844 (CreateAudioPatchConfigEventData *)event->mData.get();
845 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
846 } break;
847 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
848 ReleaseAudioPatchConfigEventData *data =
849 (ReleaseAudioPatchConfigEventData *)event->mData.get();
850 event->mStatus = releaseAudioPatch_l(data->mHandle);
851 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700852 default:
Eric Laurent10351942014-05-08 18:49:52 -0700853 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700854 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800855 }
Eric Laurent10351942014-05-08 18:49:52 -0700856 {
857 Mutex::Autolock _l(event->mLock);
858 if (event->mWaitStatus) {
859 event->mWaitStatus = false;
860 event->mCond.signal();
861 }
862 }
863 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
864 }
865
866 if (configChanged) {
867 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800868 }
Eric Laurent81784c32012-11-19 14:55:58 -0800869}
870
Marco Nelissenb2208842014-02-07 14:00:50 -0800871String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
872 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700873 const audio_channel_representation_t representation =
874 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700875
876 switch (representation) {
877 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
878 if (output) {
879 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
880 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
881 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
882 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
883 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
884 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
885 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
886 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
887 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
888 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
889 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
890 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
891 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
892 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
893 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
894 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
895 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
896 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
897 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
898 } else {
899 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
900 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
901 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
902 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
903 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
904 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
905 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
906 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
907 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
908 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
909 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
910 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
911 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
912 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
913 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
914 }
915 const int len = s.length();
916 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -0700917 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -0700918 s.unlockBuffer(len - 2); // remove trailing ", "
919 }
920 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800921 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700922 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
923 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
924 return s;
925 default:
926 s.appendFormat("unknown mask, representation:%d bits:%#x",
927 representation, audio_channel_mask_get_bits(mask));
928 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800929 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800930}
931
Glenn Kasten0f11b512014-01-31 16:18:54 -0800932void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800933{
934 const size_t SIZE = 256;
935 char buffer[SIZE];
936 String8 result;
937
938 bool locked = AudioFlinger::dumpTryLock(mLock);
939 if (!locked) {
Glenn Kasten97b7b752014-09-28 13:04:24 -0700940 dprintf(fd, "thread %p may be deadlocked\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -0800941 }
942
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800943 dprintf(fd, " Thread name: %s\n", mThreadName);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700944 dprintf(fd, " I/O handle: %d\n", mId);
945 dprintf(fd, " TID: %d\n", getTid());
946 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700947 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700948 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700949 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat));
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700950 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700951 dprintf(fd, " Channel count: %u\n", mChannelCount);
952 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800953 channelMaskToString(mChannelMask, mType != RECORD).string());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700954 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat));
955 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700956 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800957 size_t numConfig = mConfigEvents.size();
958 if (numConfig) {
959 for (size_t i = 0; i < numConfig; i++) {
960 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700961 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800962 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700963 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800964 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700965 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800966 }
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800967 dprintf(fd, " Output device: %#x (%s)\n", mOutDevice, devicesToString(mOutDevice).string());
968 dprintf(fd, " Input device: %#x (%s)\n", mInDevice, devicesToString(mInDevice).string());
969 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, sourceToString(mAudioSource));
Eric Laurent81784c32012-11-19 14:55:58 -0800970
971 if (locked) {
972 mLock.unlock();
973 }
974}
975
976void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
977{
978 const size_t SIZE = 256;
979 char buffer[SIZE];
980 String8 result;
981
Marco Nelissenb2208842014-02-07 14:00:50 -0800982 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000983 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800984 write(fd, buffer, strlen(buffer));
985
Marco Nelissenb2208842014-02-07 14:00:50 -0800986 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800987 sp<EffectChain> chain = mEffectChains[i];
988 if (chain != 0) {
989 chain->dump(fd, args);
990 }
991 }
992}
993
Marco Nelissene14a5d62013-10-03 08:51:24 -0700994void AudioFlinger::ThreadBase::acquireWakeLock(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800995{
996 Mutex::Autolock _l(mLock);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700997 acquireWakeLock_l(uid);
Eric Laurent81784c32012-11-19 14:55:58 -0800998}
999
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001000String16 AudioFlinger::ThreadBase::getWakeLockTag()
1001{
1002 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -08001003 case MIXER:
1004 return String16("AudioMix");
1005 case DIRECT:
1006 return String16("AudioDirectOut");
1007 case DUPLICATING:
1008 return String16("AudioDup");
1009 case RECORD:
1010 return String16("AudioIn");
1011 case OFFLOAD:
1012 return String16("AudioOffload");
1013 default:
1014 ALOG_ASSERT(false);
1015 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001016 }
1017}
1018
Marco Nelissene14a5d62013-10-03 08:51:24 -07001019void AudioFlinger::ThreadBase::acquireWakeLock_l(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -08001020{
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001021 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001022 if (mPowerManager != 0) {
1023 sp<IBinder> binder = new BBinder();
Marco Nelissene14a5d62013-10-03 08:51:24 -07001024 status_t status;
1025 if (uid >= 0) {
Eric Laurent547789d2013-10-04 11:46:55 -07001026 status = mPowerManager->acquireWakeLockWithUid(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -07001027 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001028 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -07001029 String16("audioserver"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -07001030 uid,
1031 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -07001032 } else {
Eric Laurent547789d2013-10-04 11:46:55 -07001033 status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -07001034 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001035 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -07001036 String16("audioserver"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -07001037 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -07001038 }
Eric Laurent81784c32012-11-19 14:55:58 -08001039 if (status == NO_ERROR) {
1040 mWakeLockToken = binder;
1041 }
Glenn Kastend7dca052015-03-05 16:05:54 -08001042 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -08001043 }
Wei Jia3f273d12015-11-24 09:06:49 -08001044
1045 if (!mNotifiedBatteryStart) {
1046 BatteryNotifier::getInstance().noteStartAudio();
1047 mNotifiedBatteryStart = true;
1048 }
Andy Hung3f0c9022016-01-15 17:49:46 -08001049 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -08001050 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
1051 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -08001052}
1053
1054void AudioFlinger::ThreadBase::releaseWakeLock()
1055{
1056 Mutex::Autolock _l(mLock);
1057 releaseWakeLock_l();
1058}
1059
1060void AudioFlinger::ThreadBase::releaseWakeLock_l()
1061{
Andy Hung3f0c9022016-01-15 17:49:46 -08001062 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -08001063 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001064 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001065 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -07001066 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
1067 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -08001068 }
1069 mWakeLockToken.clear();
1070 }
Wei Jia3f273d12015-11-24 09:06:49 -08001071
1072 if (mNotifiedBatteryStart) {
1073 BatteryNotifier::getInstance().noteStopAudio();
1074 mNotifiedBatteryStart = false;
1075 }
Eric Laurent81784c32012-11-19 14:55:58 -08001076}
1077
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001078void AudioFlinger::ThreadBase::updateWakeLockUids(const SortedVector<int> &uids) {
1079 Mutex::Autolock _l(mLock);
1080 updateWakeLockUids_l(uids);
1081}
1082
1083void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -07001084 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001085 // use checkService() to avoid blocking if power service is not up yet
1086 sp<IBinder> binder =
1087 defaultServiceManager()->checkService(String16("power"));
1088 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001089 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001090 } else {
1091 mPowerManager = interface_cast<IPowerManager>(binder);
1092 binder->linkToDeath(mDeathRecipient);
1093 }
1094 }
1095}
1096
1097void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<int> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001098 getPowerManager_l();
Andy Hung438e7572015-12-14 15:51:17 -08001099 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
1100 if (mSystemReady) {
1101 ALOGE("no wake lock to update, but system ready!");
1102 } else {
1103 ALOGW("no wake lock to update, system not ready yet");
1104 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001105 return;
1106 }
1107 if (mPowerManager != 0) {
1108 sp<IBinder> binder = new BBinder();
1109 status_t status;
Glenn Kasten3abc2de2014-09-05 16:45:52 -07001110 status = mPowerManager->updateWakeLockUids(mWakeLockToken, uids.size(), uids.array(),
1111 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent4d231dc2016-03-11 18:38:23 -08001112 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001113 }
1114}
1115
Eric Laurent81784c32012-11-19 14:55:58 -08001116void AudioFlinger::ThreadBase::clearPowerManager()
1117{
1118 Mutex::Autolock _l(mLock);
1119 releaseWakeLock_l();
1120 mPowerManager.clear();
1121}
1122
Glenn Kasten0f11b512014-01-31 16:18:54 -08001123void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001124{
1125 sp<ThreadBase> thread = mThread.promote();
1126 if (thread != 0) {
1127 thread->clearPowerManager();
1128 }
1129 ALOGW("power manager service died !!!");
1130}
1131
1132void AudioFlinger::ThreadBase::setEffectSuspended(
Glenn Kastend848eb42016-03-08 13:42:11 -08001133 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001134{
1135 Mutex::Autolock _l(mLock);
1136 setEffectSuspended_l(type, suspend, sessionId);
1137}
1138
1139void AudioFlinger::ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001140 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001141{
1142 sp<EffectChain> chain = getEffectChain_l(sessionId);
1143 if (chain != 0) {
1144 if (type != NULL) {
1145 chain->setEffectSuspended_l(type, suspend);
1146 } else {
1147 chain->setEffectSuspendedAll_l(suspend);
1148 }
1149 }
1150
1151 updateSuspendedSessions_l(type, suspend, sessionId);
1152}
1153
1154void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1155{
1156 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1157 if (index < 0) {
1158 return;
1159 }
1160
1161 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1162 mSuspendedSessions.valueAt(index);
1163
1164 for (size_t i = 0; i < sessionEffects.size(); i++) {
1165 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1166 for (int j = 0; j < desc->mRefCount; j++) {
1167 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1168 chain->setEffectSuspendedAll_l(true);
1169 } else {
1170 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1171 desc->mType.timeLow);
1172 chain->setEffectSuspended_l(&desc->mType, true);
1173 }
1174 }
1175 }
1176}
1177
1178void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1179 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001180 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001181{
1182 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1183
1184 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1185
1186 if (suspend) {
1187 if (index >= 0) {
1188 sessionEffects = mSuspendedSessions.valueAt(index);
1189 } else {
1190 mSuspendedSessions.add(sessionId, sessionEffects);
1191 }
1192 } else {
1193 if (index < 0) {
1194 return;
1195 }
1196 sessionEffects = mSuspendedSessions.valueAt(index);
1197 }
1198
1199
1200 int key = EffectChain::kKeyForSuspendAll;
1201 if (type != NULL) {
1202 key = type->timeLow;
1203 }
1204 index = sessionEffects.indexOfKey(key);
1205
1206 sp<SuspendedSessionDesc> desc;
1207 if (suspend) {
1208 if (index >= 0) {
1209 desc = sessionEffects.valueAt(index);
1210 } else {
1211 desc = new SuspendedSessionDesc();
1212 if (type != NULL) {
1213 desc->mType = *type;
1214 }
1215 sessionEffects.add(key, desc);
1216 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1217 }
1218 desc->mRefCount++;
1219 } else {
1220 if (index < 0) {
1221 return;
1222 }
1223 desc = sessionEffects.valueAt(index);
1224 if (--desc->mRefCount == 0) {
1225 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1226 sessionEffects.removeItemsAt(index);
1227 if (sessionEffects.isEmpty()) {
1228 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1229 sessionId);
1230 mSuspendedSessions.removeItem(sessionId);
1231 }
1232 }
1233 }
1234 if (!sessionEffects.isEmpty()) {
1235 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1236 }
1237}
1238
1239void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1240 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001241 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001242{
1243 Mutex::Autolock _l(mLock);
1244 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1245}
1246
1247void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1248 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001249 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001250{
1251 if (mType != RECORD) {
1252 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1253 // another session. This gives the priority to well behaved effect control panels
1254 // and applications not using global effects.
1255 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1256 // global effects
1257 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1258 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1259 }
1260 }
1261
1262 sp<EffectChain> chain = getEffectChain_l(sessionId);
1263 if (chain != 0) {
1264 chain->checkSuspendOnEffectEnabled(effect, enabled);
1265 }
1266}
1267
1268// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1269sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1270 const sp<AudioFlinger::Client>& client,
1271 const sp<IEffectClient>& effectClient,
1272 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001273 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001274 effect_descriptor_t *desc,
1275 int *enabled,
Glenn Kasten9156ef32013-08-06 15:39:08 -07001276 status_t *status)
Eric Laurent81784c32012-11-19 14:55:58 -08001277{
1278 sp<EffectModule> effect;
1279 sp<EffectHandle> handle;
1280 status_t lStatus;
1281 sp<EffectChain> chain;
1282 bool chainCreated = false;
1283 bool effectCreated = false;
1284 bool effectRegistered = false;
1285
1286 lStatus = initCheck();
1287 if (lStatus != NO_ERROR) {
1288 ALOGW("createEffect_l() Audio driver not initialized.");
1289 goto Exit;
1290 }
1291
Andy Hung98ef9782014-03-04 14:46:50 -08001292 // Reject any effect on Direct output threads for now, since the format of
1293 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1294 if (mType == DIRECT) {
1295 ALOGW("createEffect_l() Cannot add effect %s on Direct output type thread %s",
Glenn Kastend7dca052015-03-05 16:05:54 -08001296 desc->name, mThreadName);
Andy Hung98ef9782014-03-04 14:46:50 -08001297 lStatus = BAD_VALUE;
1298 goto Exit;
1299 }
1300
Andy Hung389cfdb2014-08-07 17:49:53 -07001301 // Reject any effect on mixer or duplicating multichannel sinks.
Andy Hung9a592762014-07-21 21:56:01 -07001302 // TODO: fix both format and multichannel issues with effects.
Andy Hung389cfdb2014-08-07 17:49:53 -07001303 if ((mType == MIXER || mType == DUPLICATING) && mChannelCount != FCC_2) {
1304 ALOGW("createEffect_l() Cannot add effect %s for multichannel(%d) %s threads",
1305 desc->name, mChannelCount, mType == MIXER ? "MIXER" : "DUPLICATING");
Andy Hung9a592762014-07-21 21:56:01 -07001306 lStatus = BAD_VALUE;
1307 goto Exit;
1308 }
1309
Eric Laurent5baf2af2013-09-12 17:37:00 -07001310 // Allow global effects only on offloaded and mixer threads
1311 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1312 switch (mType) {
1313 case MIXER:
1314 case OFFLOAD:
1315 break;
1316 case DIRECT:
1317 case DUPLICATING:
1318 case RECORD:
1319 default:
Glenn Kastend7dca052015-03-05 16:05:54 -08001320 ALOGW("createEffect_l() Cannot add global effect %s on thread %s",
1321 desc->name, mThreadName);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001322 lStatus = BAD_VALUE;
1323 goto Exit;
1324 }
Eric Laurent81784c32012-11-19 14:55:58 -08001325 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001326
Eric Laurent81784c32012-11-19 14:55:58 -08001327 // Only Pre processor effects are allowed on input threads and only on input threads
1328 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
1329 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
1330 desc->name, desc->flags, mType);
1331 lStatus = BAD_VALUE;
1332 goto Exit;
1333 }
1334
1335 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1336
1337 { // scope for mLock
1338 Mutex::Autolock _l(mLock);
1339
1340 // check for existing effect chain with the requested audio session
1341 chain = getEffectChain_l(sessionId);
1342 if (chain == 0) {
1343 // create a new chain for this session
1344 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1345 chain = new EffectChain(this, sessionId);
1346 addEffectChain_l(chain);
1347 chain->setStrategy(getStrategyForSession_l(sessionId));
1348 chainCreated = true;
1349 } else {
1350 effect = chain->getEffectFromDesc_l(desc);
1351 }
1352
1353 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1354
1355 if (effect == 0) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08001356 audio_unique_id_t id = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001357 // Check CPU and memory usage
1358 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
1359 if (lStatus != NO_ERROR) {
1360 goto Exit;
1361 }
1362 effectRegistered = true;
1363 // create a new effect module if none present in the chain
1364 effect = new EffectModule(this, chain, desc, id, sessionId);
1365 lStatus = effect->status();
1366 if (lStatus != NO_ERROR) {
1367 goto Exit;
1368 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001369 effect->setOffloaded(mType == OFFLOAD, mId);
1370
Eric Laurent81784c32012-11-19 14:55:58 -08001371 lStatus = chain->addEffect_l(effect);
1372 if (lStatus != NO_ERROR) {
1373 goto Exit;
1374 }
1375 effectCreated = true;
1376
1377 effect->setDevice(mOutDevice);
1378 effect->setDevice(mInDevice);
1379 effect->setMode(mAudioFlinger->getMode());
1380 effect->setAudioSource(mAudioSource);
1381 }
1382 // create effect handle and connect it to effect module
1383 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001384 lStatus = handle->initCheck();
1385 if (lStatus == OK) {
1386 lStatus = effect->addHandle(handle.get());
1387 }
Eric Laurent81784c32012-11-19 14:55:58 -08001388 if (enabled != NULL) {
1389 *enabled = (int)effect->isEnabled();
1390 }
1391 }
1392
1393Exit:
1394 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1395 Mutex::Autolock _l(mLock);
1396 if (effectCreated) {
1397 chain->removeEffect_l(effect);
1398 }
1399 if (effectRegistered) {
1400 AudioSystem::unregisterEffect(effect->id());
1401 }
1402 if (chainCreated) {
1403 removeEffectChain_l(chain);
1404 }
1405 handle.clear();
1406 }
1407
Glenn Kasten9156ef32013-08-06 15:39:08 -07001408 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001409 return handle;
1410}
1411
Glenn Kastend848eb42016-03-08 13:42:11 -08001412sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1413 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001414{
1415 Mutex::Autolock _l(mLock);
1416 return getEffect_l(sessionId, effectId);
1417}
1418
Glenn Kastend848eb42016-03-08 13:42:11 -08001419sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1420 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001421{
1422 sp<EffectChain> chain = getEffectChain_l(sessionId);
1423 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1424}
1425
1426// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1427// PlaybackThread::mLock held
1428status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1429{
1430 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001431 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001432 sp<EffectChain> chain = getEffectChain_l(sessionId);
1433 bool chainCreated = false;
1434
Eric Laurent5baf2af2013-09-12 17:37:00 -07001435 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1436 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1437 this, effect->desc().name, effect->desc().flags);
1438
Eric Laurent81784c32012-11-19 14:55:58 -08001439 if (chain == 0) {
1440 // create a new chain for this session
1441 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1442 chain = new EffectChain(this, sessionId);
1443 addEffectChain_l(chain);
1444 chain->setStrategy(getStrategyForSession_l(sessionId));
1445 chainCreated = true;
1446 }
1447 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1448
1449 if (chain->getEffectFromId_l(effect->id()) != 0) {
1450 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1451 this, effect->desc().name, chain.get());
1452 return BAD_VALUE;
1453 }
1454
Eric Laurent5baf2af2013-09-12 17:37:00 -07001455 effect->setOffloaded(mType == OFFLOAD, mId);
1456
Eric Laurent81784c32012-11-19 14:55:58 -08001457 status_t status = chain->addEffect_l(effect);
1458 if (status != NO_ERROR) {
1459 if (chainCreated) {
1460 removeEffectChain_l(chain);
1461 }
1462 return status;
1463 }
1464
1465 effect->setDevice(mOutDevice);
1466 effect->setDevice(mInDevice);
1467 effect->setMode(mAudioFlinger->getMode());
1468 effect->setAudioSource(mAudioSource);
1469 return NO_ERROR;
1470}
1471
1472void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
1473
1474 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
1475 effect_descriptor_t desc = effect->desc();
1476 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1477 detachAuxEffect_l(effect->id());
1478 }
1479
1480 sp<EffectChain> chain = effect->chain().promote();
1481 if (chain != 0) {
1482 // remove effect chain if removing last effect
1483 if (chain->removeEffect_l(effect) == 0) {
1484 removeEffectChain_l(chain);
1485 }
1486 } else {
1487 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1488 }
1489}
1490
1491void AudioFlinger::ThreadBase::lockEffectChains_l(
1492 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1493{
1494 effectChains = mEffectChains;
1495 for (size_t i = 0; i < mEffectChains.size(); i++) {
1496 mEffectChains[i]->lock();
1497 }
1498}
1499
1500void AudioFlinger::ThreadBase::unlockEffectChains(
1501 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1502{
1503 for (size_t i = 0; i < effectChains.size(); i++) {
1504 effectChains[i]->unlock();
1505 }
1506}
1507
Glenn Kastend848eb42016-03-08 13:42:11 -08001508sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001509{
1510 Mutex::Autolock _l(mLock);
1511 return getEffectChain_l(sessionId);
1512}
1513
Glenn Kastend848eb42016-03-08 13:42:11 -08001514sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1515 const
Eric Laurent81784c32012-11-19 14:55:58 -08001516{
1517 size_t size = mEffectChains.size();
1518 for (size_t i = 0; i < size; i++) {
1519 if (mEffectChains[i]->sessionId() == sessionId) {
1520 return mEffectChains[i];
1521 }
1522 }
1523 return 0;
1524}
1525
1526void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1527{
1528 Mutex::Autolock _l(mLock);
1529 size_t size = mEffectChains.size();
1530 for (size_t i = 0; i < size; i++) {
1531 mEffectChains[i]->setMode_l(mode);
1532 }
1533}
1534
Eric Laurent83b88082014-06-20 18:31:16 -07001535void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1536{
1537 config->type = AUDIO_PORT_TYPE_MIX;
1538 config->ext.mix.handle = mId;
1539 config->sample_rate = mSampleRate;
1540 config->format = mFormat;
1541 config->channel_mask = mChannelMask;
1542 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1543 AUDIO_PORT_CONFIG_FORMAT;
1544}
1545
Eric Laurent72e3f392015-05-20 14:43:50 -07001546void AudioFlinger::ThreadBase::systemReady()
1547{
1548 Mutex::Autolock _l(mLock);
1549 if (mSystemReady) {
1550 return;
1551 }
1552 mSystemReady = true;
1553
1554 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1555 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1556 }
1557 mPendingConfigEvents.clear();
1558}
1559
Eric Laurent83b88082014-06-20 18:31:16 -07001560
Eric Laurent81784c32012-11-19 14:55:58 -08001561// ----------------------------------------------------------------------------
1562// Playback
1563// ----------------------------------------------------------------------------
1564
1565AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1566 AudioStreamOut* output,
1567 audio_io_handle_t id,
1568 audio_devices_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07001569 type_t type,
Eric Laurent51716182016-02-29 18:00:56 -08001570 bool systemReady,
1571 uint32_t bitRate)
Eric Laurent72e3f392015-05-20 14:43:50 -07001572 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001573 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001574 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001575 mMixerBuffer(NULL),
1576 mMixerBufferSize(0),
1577 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1578 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001579 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001580 mEffectBuffer(NULL),
1581 mEffectBufferSize(0),
1582 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1583 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001584 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001585 mFramesWritten(0),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001586 mActiveTracksGeneration(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001587 // mStreamTypes[] initialized in constructor body
1588 mOutput(output),
1589 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
1590 mMixerStatus(MIXER_IDLE),
1591 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001592 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001593 mBytesRemaining(0),
1594 mCurrentWriteLength(0),
1595 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001596 mWriteAckSequence(0),
1597 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001598 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001599 mScreenState(AudioFlinger::mScreenState),
1600 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001601 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Andy Hunge10393e2015-06-12 13:59:33 -07001602 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001603{
Glenn Kastend7dca052015-03-05 16:05:54 -08001604 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1605 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001606
1607 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1608 // it would be safer to explicitly pass initial masterVolume/masterMute as
1609 // parameter.
1610 //
1611 // If the HAL we are using has support for master volume or master mute,
1612 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1613 // and the mute set to false).
1614 mMasterVolume = audioFlinger->masterVolume_l();
1615 mMasterMute = audioFlinger->masterMute_l();
1616 if (mOutput && mOutput->audioHwDev) {
1617 if (mOutput->audioHwDev->canSetMasterVolume()) {
1618 mMasterVolume = 1.0;
1619 }
1620
1621 if (mOutput->audioHwDev->canSetMasterMute()) {
1622 mMasterMute = false;
1623 }
1624 }
1625
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001626 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001627
Eric Laurent223fd5c2014-11-11 13:43:36 -08001628 // ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001629 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001630 stream = (audio_stream_type_t) (stream + 1)) {
1631 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1632 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1633 }
Eric Laurent51716182016-02-29 18:00:56 -08001634
1635 if (audio_has_proportional_frames(mFormat)) {
1636 mBufferDurationUs = (uint32_t)((mNormalFrameCount * 1000000LL) / mSampleRate);
1637 } else {
1638 bitRate = bitRate != 0 ? bitRate : kOffloadDefaultBitRateBps;
1639 mBufferDurationUs = (uint32_t)((mBufferSize * 8 * 1000000LL) / bitRate);
1640 }
Eric Laurent81784c32012-11-19 14:55:58 -08001641}
1642
1643AudioFlinger::PlaybackThread::~PlaybackThread()
1644{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001645 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001646 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001647 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001648 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001649}
1650
1651void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1652{
1653 dumpInternals(fd, args);
1654 dumpTracks(fd, args);
1655 dumpEffectChains(fd, args);
1656}
1657
Glenn Kasten0f11b512014-01-31 16:18:54 -08001658void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001659{
1660 const size_t SIZE = 256;
1661 char buffer[SIZE];
1662 String8 result;
1663
Marco Nelissenb2208842014-02-07 14:00:50 -08001664 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001665 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1666 const stream_type_t *st = &mStreamTypes[i];
1667 if (i > 0) {
1668 result.appendFormat(", ");
1669 }
1670 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1671 if (st->mute) {
1672 result.append("M");
1673 }
1674 }
1675 result.append("\n");
1676 write(fd, result.string(), result.length());
1677 result.clear();
1678
Eric Laurent81784c32012-11-19 14:55:58 -08001679 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1680 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001681 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001682 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001683
1684 size_t numtracks = mTracks.size();
1685 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001686 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001687 size_t numactiveseen = 0;
1688 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001689 dprintf(fd, " of which %zu are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001690 Track::appendDumpHeader(result);
1691 for (size_t i = 0; i < numtracks; ++i) {
1692 sp<Track> track = mTracks[i];
1693 if (track != 0) {
1694 bool active = mActiveTracks.indexOf(track) >= 0;
1695 if (active) {
1696 numactiveseen++;
1697 }
1698 track->dump(buffer, SIZE, active);
1699 result.append(buffer);
1700 }
1701 }
1702 } else {
1703 result.append("\n");
1704 }
1705 if (numactiveseen != numactive) {
1706 // some tracks in the active list were not in the tracks list
1707 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1708 " not in the track list\n");
1709 result.append(buffer);
1710 Track::appendDumpHeader(result);
1711 for (size_t i = 0; i < numactive; ++i) {
1712 sp<Track> track = mActiveTracks[i].promote();
1713 if (track != 0 && mTracks.indexOf(track) < 0) {
1714 track->dump(buffer, SIZE, true);
1715 result.append(buffer);
1716 }
1717 }
1718 }
1719
1720 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001721}
1722
1723void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1724{
Glenn Kasten97b7b752014-09-28 13:04:24 -07001725 dprintf(fd, "\nOutput thread %p type %d (%s):\n", this, type(), threadTypeToString(type()));
Glenn Kasten44182c22015-03-05 17:12:23 -08001726
1727 dumpBase(fd, args);
1728
Elliott Hughes87cebad2014-05-22 10:14:43 -07001729 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001730 dprintf(fd, " Last write occurred (msecs): %llu\n",
1731 (unsigned long long) ns2ms(systemTime() - mLastWriteTime));
Elliott Hughes87cebad2014-05-22 10:14:43 -07001732 dprintf(fd, " Total writes: %d\n", mNumWrites);
1733 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1734 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1735 dprintf(fd, " Suspend count: %d\n", mSuspended);
1736 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1737 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1738 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1739 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08001740 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001741 AudioStreamOut *output = mOutput;
1742 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
1743 String8 flagsAsString = outputFlagsToString(flags);
1744 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n", output, flags, flagsAsString.string());
Eric Laurent81784c32012-11-19 14:55:58 -08001745}
1746
1747// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001748
1749void AudioFlinger::PlaybackThread::onFirstRef()
1750{
Glenn Kastend7dca052015-03-05 16:05:54 -08001751 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001752}
1753
1754// ThreadBase virtuals
1755void AudioFlinger::PlaybackThread::preExit()
1756{
1757 ALOGV(" preExit()");
1758 // FIXME this is using hard-coded strings but in the future, this functionality will be
1759 // converted to use audio HAL extensions required to support tunneling
1760 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1761}
1762
1763// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1764sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1765 const sp<AudioFlinger::Client>& client,
1766 audio_stream_type_t streamType,
1767 uint32_t sampleRate,
1768 audio_format_t format,
1769 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001770 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001771 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08001772 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001773 IAudioFlinger::track_flags_t *flags,
1774 pid_t tid,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001775 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -08001776 status_t *status)
1777{
Glenn Kasten74935e42013-12-19 08:56:45 -08001778 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001779 sp<Track> track;
1780 status_t lStatus;
1781
Eric Laurent81784c32012-11-19 14:55:58 -08001782 // client expresses a preference for FAST, but we get the final say
1783 if (*flags & IAudioFlinger::TRACK_FAST) {
1784 if (
Eric Laurent81784c32012-11-19 14:55:58 -08001785 // PCM data
1786 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001787 // TODO: extract as a data library function that checks that a computationally
1788 // expensive downmixer is not required: isFastOutputChannelConversion()
Andy Hung9a592762014-07-21 21:56:01 -07001789 (channelMask == mChannelMask ||
Andy Hung1f439e12015-05-19 12:57:41 -07001790 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1791 (channelMask == AUDIO_CHANNEL_OUT_MONO
1792 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001793 // hardware sample rate
1794 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001795 // normal mixer has an associated fast mixer
1796 hasFastMixer() &&
1797 // there are sufficient fast track slots available
1798 (mFastTrackAvailMask != 0)
1799 // FIXME test that MixerThread for this fast track has a capable output HAL
1800 // FIXME add a permission test also?
1801 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07001802 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
1803 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001804 // read the fast track multiplier property the first time it is needed
1805 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1806 if (ok != 0) {
1807 ALOGE("%s pthread_once failed: %d", __func__, ok);
1808 }
Andy Hunge0a269a2016-03-23 15:13:42 -07001809 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08001810 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001811 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08001812 frameCount, mFrameCount);
1813 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001814 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
1815 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07001816 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001817 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08001818 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001819 audio_is_linear_pcm(format),
1820 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1821 *flags &= ~IAudioFlinger::TRACK_FAST;
Andy Hung0e48d252015-01-26 11:43:15 -08001822 }
1823 }
1824 // For normal PCM streaming tracks, update minimum frame count.
1825 // For compatibility with AudioTrack calculation, buffer depth is forced
1826 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1827 // This is probably too conservative, but legacy application code may depend on it.
1828 // If you change this calculation, also review the start threshold which is related.
1829 if (!(*flags & IAudioFlinger::TRACK_FAST)
Phil Burkfdb3c072016-02-09 10:47:02 -08001830 && audio_has_proportional_frames(format) && sharedBuffer == 0) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001831 // this must match AudioTrack.cpp calculateMinFrameCount().
1832 // TODO: Move to a common library
Eric Laurent81784c32012-11-19 14:55:58 -08001833 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1834 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1835 if (minBufCount < 2) {
1836 minBufCount = 2;
1837 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07001838 // For normal mixing tracks, if speed is > 1.0f (normal), AudioTrack
1839 // or the client should compute and pass in a larger buffer request.
Andy Hung0e48d252015-01-26 11:43:15 -08001840 size_t minFrameCount =
Andy Hung8edb8dc2015-03-26 19:13:55 -07001841 minBufCount * sourceFramesNeededWithTimestretch(
1842 sampleRate, mNormalFrameCount,
1843 mSampleRate, AUDIO_TIMESTRETCH_SPEED_NORMAL /*speed*/);
Andy Hung0e48d252015-01-26 11:43:15 -08001844 if (frameCount < minFrameCount) { // including frameCount == 0
Eric Laurent81784c32012-11-19 14:55:58 -08001845 frameCount = minFrameCount;
1846 }
Eric Laurent81784c32012-11-19 14:55:58 -08001847 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001848 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001849
Glenn Kastenc3df8382014-03-13 15:05:25 -07001850 switch (mType) {
1851
1852 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08001853 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08001854 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001855 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1856 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001857 sampleRate, format, channelMask, mOutput, mFormat);
1858 lStatus = BAD_VALUE;
1859 goto Exit;
1860 }
1861 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001862 break;
1863
1864 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001865 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001866 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1867 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001868 sampleRate, format, channelMask, mOutput, mFormat);
1869 lStatus = BAD_VALUE;
1870 goto Exit;
1871 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001872 break;
1873
1874 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001875 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001876 ALOGE("createTrack_l() Bad parameter: format %#x \""
1877 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001878 format, mOutput, mFormat);
1879 lStatus = BAD_VALUE;
1880 goto Exit;
1881 }
Andy Hungcd044842014-08-07 11:04:34 -07001882 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08001883 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1884 lStatus = BAD_VALUE;
1885 goto Exit;
1886 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001887 break;
1888
Eric Laurent81784c32012-11-19 14:55:58 -08001889 }
1890
1891 lStatus = initCheck();
1892 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001893 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08001894 goto Exit;
1895 }
1896
1897 { // scope for mLock
1898 Mutex::Autolock _l(mLock);
1899
1900 // all tracks in same audio session must share the same routing strategy otherwise
1901 // conflicts will happen when tracks are moved from one output to another by audio policy
1902 // manager
1903 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1904 for (size_t i = 0; i < mTracks.size(); ++i) {
1905 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07001906 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001907 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1908 if (sessionId == t->sessionId() && strategy != actual) {
1909 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1910 strategy, actual);
1911 lStatus = BAD_VALUE;
1912 goto Exit;
1913 }
1914 }
1915 }
1916
Glenn Kastend79072e2016-01-06 08:41:20 -08001917 track = new Track(this, client, streamType, sampleRate, format,
1918 channelMask, frameCount, NULL, sharedBuffer,
1919 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT);
Glenn Kasten03003332013-08-06 15:40:54 -07001920
Glenn Kasten03003332013-08-06 15:40:54 -07001921 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1922 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08001923 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001924 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08001925 goto Exit;
1926 }
1927 mTracks.add(track);
1928
1929 sp<EffectChain> chain = getEffectChain_l(sessionId);
1930 if (chain != 0) {
1931 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1932 track->setMainBuffer(chain->inBuffer());
1933 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1934 chain->incTrackCnt();
1935 }
1936
1937 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1938 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1939 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1940 // so ask activity manager to do this on our behalf
1941 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1942 }
1943 }
1944
1945 lStatus = NO_ERROR;
1946
1947Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001948 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001949 return track;
1950}
1951
1952uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1953{
1954 return latency;
1955}
1956
1957uint32_t AudioFlinger::PlaybackThread::latency() const
1958{
1959 Mutex::Autolock _l(mLock);
1960 return latency_l();
1961}
1962uint32_t AudioFlinger::PlaybackThread::latency_l() const
1963{
1964 if (initCheck() == NO_ERROR) {
1965 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1966 } else {
1967 return 0;
1968 }
1969}
1970
1971void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1972{
1973 Mutex::Autolock _l(mLock);
1974 // Don't apply master volume in SW if our HAL can do it for us.
1975 if (mOutput && mOutput->audioHwDev &&
1976 mOutput->audioHwDev->canSetMasterVolume()) {
1977 mMasterVolume = 1.0;
1978 } else {
1979 mMasterVolume = value;
1980 }
1981}
1982
1983void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1984{
1985 Mutex::Autolock _l(mLock);
1986 // Don't apply master mute in SW if our HAL can do it for us.
1987 if (mOutput && mOutput->audioHwDev &&
1988 mOutput->audioHwDev->canSetMasterMute()) {
1989 mMasterMute = false;
1990 } else {
1991 mMasterMute = muted;
1992 }
1993}
1994
1995void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1996{
1997 Mutex::Autolock _l(mLock);
1998 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001999 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002000}
2001
2002void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2003{
2004 Mutex::Autolock _l(mLock);
2005 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002006 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002007}
2008
2009float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2010{
2011 Mutex::Autolock _l(mLock);
2012 return mStreamTypes[stream].volume;
2013}
2014
2015// addTrack_l() must be called with ThreadBase::mLock held
2016status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2017{
2018 status_t status = ALREADY_EXISTS;
2019
Eric Laurent81784c32012-11-19 14:55:58 -08002020 if (mActiveTracks.indexOf(track) < 0) {
2021 // the track is newly added, make sure it fills up all its
2022 // buffers before playing. This is to ensure the client will
2023 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002024 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002025 TrackBase::track_state state = track->mState;
2026 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002027 status = AudioSystem::startOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002028 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002029 mLock.lock();
2030 // abort track was stopped/paused while we released the lock
2031 if (state != track->mState) {
2032 if (status == NO_ERROR) {
2033 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002034 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002035 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002036 mLock.lock();
2037 }
2038 return INVALID_OPERATION;
2039 }
2040 // abort if start is rejected by audio policy manager
2041 if (status != NO_ERROR) {
2042 return PERMISSION_DENIED;
2043 }
2044#ifdef ADD_BATTERY_DATA
2045 // to track the speaker usage
2046 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2047#endif
2048 }
2049
Eric Laurent51716182016-02-29 18:00:56 -08002050 // set retry count for buffer fill
2051 if (track->isOffloaded()) {
2052 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2053 } else {
2054 track->mRetryCount = kMaxTrackStartupRetries;
2055 }
2056
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002057 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08002058 track->mResetDone = false;
2059 track->mPresentationCompleteFrames = 0;
2060 mActiveTracks.add(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002061 mWakeLockUids.add(track->uid());
2062 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07002063 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07002064 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2065 if (chain != 0) {
2066 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2067 track->sessionId());
2068 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002069 }
2070
2071 status = NO_ERROR;
2072 }
2073
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002074 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002075 return status;
2076}
2077
Eric Laurentbfb1b832013-01-07 09:53:42 -08002078bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002079{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002080 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002081 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002082 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2083 track->mState = TrackBase::STOPPED;
2084 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002085 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002086 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002087 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002088 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002089
2090 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002091}
2092
2093void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2094{
2095 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
2096 mTracks.remove(track);
2097 deleteTrackName_l(track->name());
2098 // redundant as track is about to be destroyed, for dumpsys only
2099 track->mName = -1;
2100 if (track->isFastTrack()) {
2101 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002102 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002103 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2104 mFastTrackAvailMask |= 1 << index;
2105 // redundant as track is about to be destroyed, for dumpsys only
2106 track->mFastIndex = -1;
2107 }
2108 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2109 if (chain != 0) {
2110 chain->decTrackCnt();
2111 }
2112}
2113
Eric Laurentede6c3b2013-09-19 14:37:46 -07002114void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002115{
2116 // Thread could be blocked waiting for async
2117 // so signal it to handle state changes immediately
2118 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
2119 // be lost so we also flag to prevent it blocking on mWaitWorkCV
2120 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002121 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002122}
2123
Eric Laurent81784c32012-11-19 14:55:58 -08002124String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2125{
Eric Laurent81784c32012-11-19 14:55:58 -08002126 Mutex::Autolock _l(mLock);
2127 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07002128 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002129 }
2130
Glenn Kastend8ea6992013-07-16 14:17:15 -07002131 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
2132 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08002133 free(s);
2134 return out_s8;
2135}
2136
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002137void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002138 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2139 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002140
Eric Laurent73e26b62015-04-27 16:55:58 -07002141 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002142
2143 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002144 case AUDIO_OUTPUT_OPENED:
2145 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002146 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002147 desc->mChannelMask = mChannelMask;
2148 desc->mSamplingRate = mSampleRate;
2149 desc->mFormat = mFormat;
2150 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002151 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002152 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002153 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002154 break;
2155
Eric Laurent73e26b62015-04-27 16:55:58 -07002156 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002157 default:
2158 break;
2159 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002160 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002161}
2162
Eric Laurentbfb1b832013-01-07 09:53:42 -08002163void AudioFlinger::PlaybackThread::writeCallback()
2164{
2165 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002166 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002167}
2168
2169void AudioFlinger::PlaybackThread::drainCallback()
2170{
2171 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002172 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002173}
2174
Eric Laurent3b4529e2013-09-05 18:09:19 -07002175void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002176{
2177 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002178 // reject out of sequence requests
2179 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2180 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002181 mWaitWorkCV.signal();
2182 }
2183}
2184
Eric Laurent3b4529e2013-09-05 18:09:19 -07002185void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002186{
2187 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002188 // reject out of sequence requests
2189 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
2190 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002191 mWaitWorkCV.signal();
2192 }
2193}
2194
2195// static
2196int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
Glenn Kasten0f11b512014-01-31 16:18:54 -08002197 void *param __unused,
Eric Laurentbfb1b832013-01-07 09:53:42 -08002198 void *cookie)
2199{
2200 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
2201 ALOGV("asyncCallback() event %d", event);
2202 switch (event) {
2203 case STREAM_CBK_EVENT_WRITE_READY:
2204 me->writeCallback();
2205 break;
2206 case STREAM_CBK_EVENT_DRAIN_READY:
2207 me->drainCallback();
2208 break;
2209 default:
2210 ALOGW("asyncCallback() unknown event %d", event);
2211 break;
2212 }
2213 return 0;
2214}
2215
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002216void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002217{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002218 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002219 mSampleRate = mOutput->getSampleRate();
2220 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002221 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002222 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002223 }
Andy Hung9a592762014-07-21 21:56:01 -07002224 if ((mType == MIXER || mType == DUPLICATING)
2225 && !isValidPcmSinkChannelMask(mChannelMask)) {
2226 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2227 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002228 }
Andy Hunge5412692014-05-16 11:25:07 -07002229 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002230
2231 // Get actual HAL format.
Andy Hung463be252014-07-10 16:56:07 -07002232 mHALFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Phil Burkca5e6142015-07-14 09:42:29 -07002233 // Get format from the shim, which will be different than the HAL format
2234 // if playing compressed audio over HDMI passthrough.
2235 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002236 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002237 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002238 }
Andy Hung6146c082014-03-18 11:56:15 -07002239 if ((mType == MIXER || mType == DUPLICATING)
2240 && !isValidPcmSinkFormat(mFormat)) {
2241 LOG_FATAL("HAL format %#x not supported for mixed output",
2242 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002243 }
Phil Burk062e67a2015-02-11 13:40:50 -08002244 mFrameSize = mOutput->getFrameSize();
Glenn Kasten70949c42013-08-06 07:40:12 -07002245 mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
2246 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002247 if (mFrameCount & 15) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002248 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002249 mFrameCount);
2250 }
2251
Eric Laurentbfb1b832013-01-07 09:53:42 -08002252 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
2253 (mOutput->stream->set_callback != NULL)) {
2254 if (mOutput->stream->set_callback(mOutput->stream,
2255 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
2256 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002257 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002258 }
2259 }
2260
Eric Laurentd1f69b02014-12-15 14:33:13 -08002261 mHwSupportsPause = false;
2262 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
2263 if (mOutput->stream->pause != NULL) {
2264 if (mOutput->stream->resume != NULL) {
2265 mHwSupportsPause = true;
2266 } else {
2267 ALOGW("direct output implements pause but not resume");
2268 }
2269 } else if (mOutput->stream->resume != NULL) {
2270 ALOGW("direct output implements resume but not pause");
2271 }
2272 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002273 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2274 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2275 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002276
Andy Hungfbfc3952015-01-15 13:33:51 -08002277 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2278 // For best precision, we use float instead of the associated output
2279 // device format (typically PCM 16 bit).
2280
2281 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2282 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2283 mBufferSize = mFrameSize * mFrameCount;
2284
2285 // TODO: We currently use the associated output device channel mask and sample rate.
2286 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2287 // (if a valid mask) to avoid premature downmix.
2288 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2289 // instead of the output device sample rate to avoid loss of high frequency information.
2290 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2291 }
2292
Andy Hung09a50072014-02-27 14:30:47 -08002293 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002294 double multiplier = 1.0;
2295 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2296 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002297 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2298 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Eric Laurent81784c32012-11-19 14:55:58 -08002299 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2300 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2301 maxNormalFrameCount = maxNormalFrameCount & ~15;
2302 if (maxNormalFrameCount < minNormalFrameCount) {
2303 maxNormalFrameCount = minNormalFrameCount;
2304 }
2305 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2306 if (multiplier <= 1.0) {
2307 multiplier = 1.0;
2308 } else if (multiplier <= 2.0) {
2309 if (2 * mFrameCount <= maxNormalFrameCount) {
2310 multiplier = 2.0;
2311 } else {
2312 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2313 }
2314 } else {
2315 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
Andy Hung09a50072014-02-27 14:30:47 -08002316 // SRC (it would be unusual for the normal sink buffer size to not be a multiple of fast
Eric Laurent81784c32012-11-19 14:55:58 -08002317 // track, but we sometimes have to do this to satisfy the maximum frame count
2318 // constraint)
2319 // FIXME this rounding up should not be done if no HAL SRC
2320 uint32_t truncMult = (uint32_t) multiplier;
2321 if ((truncMult & 1)) {
2322 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2323 ++truncMult;
2324 }
2325 }
2326 multiplier = (double) truncMult;
2327 }
2328 }
2329 mNormalFrameCount = multiplier * mFrameCount;
2330 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002331 if (mType == MIXER || mType == DUPLICATING) {
2332 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2333 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002334 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002335 mNormalFrameCount);
2336
Andy Hung08fb1742015-05-31 23:22:10 -07002337 // Check if we want to throttle the processing to no more than 2x normal rate
2338 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002339 mThreadThrottleTimeMs = 0;
2340 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002341 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2342
Andy Hung010a1a12014-03-13 13:57:33 -07002343 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2344 // Originally this was int16_t[] array, need to remove legacy implications.
2345 free(mSinkBuffer);
2346 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002347 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2348 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2349 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002350 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002351
Andy Hung69aed5f2014-02-25 17:24:40 -08002352 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2353 // drives the output.
2354 free(mMixerBuffer);
2355 mMixerBuffer = NULL;
2356 if (mMixerBufferEnabled) {
2357 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2358 mMixerBufferSize = mNormalFrameCount * mChannelCount
2359 * audio_bytes_per_sample(mMixerBufferFormat);
2360 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2361 }
Andy Hung98ef9782014-03-04 14:46:50 -08002362 free(mEffectBuffer);
2363 mEffectBuffer = NULL;
2364 if (mEffectBufferEnabled) {
2365 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2366 mEffectBufferSize = mNormalFrameCount * mChannelCount
2367 * audio_bytes_per_sample(mEffectBufferFormat);
2368 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2369 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002370
Eric Laurent81784c32012-11-19 14:55:58 -08002371 // force reconfiguration of effect chains and engines to take new buffer size and audio
2372 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002373 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002374 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2375 // matter.
2376 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2377 Vector< sp<EffectChain> > effectChains = mEffectChains;
2378 for (size_t i = 0; i < effectChains.size(); i ++) {
2379 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2380 }
2381}
2382
2383
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002384status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002385{
2386 if (halFrames == NULL || dspFrames == NULL) {
2387 return BAD_VALUE;
2388 }
2389 Mutex::Autolock _l(mLock);
2390 if (initCheck() != NO_ERROR) {
2391 return INVALID_OPERATION;
2392 }
Andy Hung818e7a32016-02-16 18:08:07 -08002393 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002394 *halFrames = framesWritten;
2395
2396 if (isSuspended()) {
2397 // return an estimation of rendered frames when the output is suspended
2398 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002399 *dspFrames = (uint32_t)
2400 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002401 return NO_ERROR;
2402 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002403 status_t status;
2404 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002405 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002406 *dspFrames = (size_t)frames;
2407 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002408 }
2409}
2410
Glenn Kastend848eb42016-03-08 13:42:11 -08002411uint32_t AudioFlinger::PlaybackThread::hasAudioSession(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08002412{
2413 Mutex::Autolock _l(mLock);
2414 uint32_t result = 0;
2415 if (getEffectChain_l(sessionId) != 0) {
2416 result = EFFECT_SESSION;
2417 }
2418
2419 for (size_t i = 0; i < mTracks.size(); ++i) {
2420 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002421 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002422 result |= TRACK_SESSION;
2423 break;
2424 }
2425 }
2426
2427 return result;
2428}
2429
Glenn Kastend848eb42016-03-08 13:42:11 -08002430uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08002431{
2432 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2433 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2434 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2435 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2436 }
2437 for (size_t i = 0; i < mTracks.size(); i++) {
2438 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002439 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002440 return AudioSystem::getStrategyForStream(track->streamType());
2441 }
2442 }
2443 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2444}
2445
2446
Phil Burk062e67a2015-02-11 13:40:50 -08002447AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002448{
2449 Mutex::Autolock _l(mLock);
2450 return mOutput;
2451}
2452
Phil Burk062e67a2015-02-11 13:40:50 -08002453AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002454{
2455 Mutex::Autolock _l(mLock);
2456 AudioStreamOut *output = mOutput;
2457 mOutput = NULL;
2458 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2459 // must push a NULL and wait for ack
2460 mOutputSink.clear();
2461 mPipeSink.clear();
2462 mNormalSink.clear();
2463 return output;
2464}
2465
2466// this method must always be called either with ThreadBase mLock held or inside the thread loop
2467audio_stream_t* AudioFlinger::PlaybackThread::stream() const
2468{
2469 if (mOutput == NULL) {
2470 return NULL;
2471 }
2472 return &mOutput->stream->common;
2473}
2474
2475uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2476{
2477 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2478}
2479
2480status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2481{
2482 if (!isValidSyncEvent(event)) {
2483 return BAD_VALUE;
2484 }
2485
2486 Mutex::Autolock _l(mLock);
2487
2488 for (size_t i = 0; i < mTracks.size(); ++i) {
2489 sp<Track> track = mTracks[i];
2490 if (event->triggerSession() == track->sessionId()) {
2491 (void) track->setSyncEvent(event);
2492 return NO_ERROR;
2493 }
2494 }
2495
2496 return NAME_NOT_FOUND;
2497}
2498
2499bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2500{
2501 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2502}
2503
2504void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2505 const Vector< sp<Track> >& tracksToRemove)
2506{
2507 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002508 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002509 for (size_t i = 0 ; i < count ; i++) {
2510 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002511 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002512 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002513 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002514#ifdef ADD_BATTERY_DATA
2515 // to track the speaker usage
2516 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2517#endif
2518 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002519 AudioSystem::releaseOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002520 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002521 }
Eric Laurent81784c32012-11-19 14:55:58 -08002522 }
2523 }
2524 }
Eric Laurent81784c32012-11-19 14:55:58 -08002525}
2526
2527void AudioFlinger::PlaybackThread::checkSilentMode_l()
2528{
2529 if (!mMasterMute) {
2530 char value[PROPERTY_VALUE_MAX];
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07002531 if (mOutDevice == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) {
2532 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
2533 return;
2534 }
Eric Laurent81784c32012-11-19 14:55:58 -08002535 if (property_get("ro.audio.silent", value, "0") > 0) {
2536 char *endptr;
2537 unsigned long ul = strtoul(value, &endptr, 0);
2538 if (*endptr == '\0' && ul != 0) {
2539 ALOGD("Silence is golden");
2540 // The setprop command will not allow a property to be changed after
2541 // the first time it is set, so we don't have to worry about un-muting.
2542 setMasterMute_l(true);
2543 }
2544 }
2545 }
2546}
2547
2548// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002549ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002550{
2551 // FIXME rewrite to reduce number of system calls
2552 mLastWriteTime = systemTime();
2553 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002554 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002555 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002556
2557 // If an NBAIO sink is present, use it to write the normal mixer's submix
2558 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002559
Andy Hung010a1a12014-03-13 13:57:33 -07002560 const size_t count = mBytesRemaining / mFrameSize;
2561
Simon Wilson2d590962012-11-29 15:18:50 -08002562 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002563 // update the setpoint when AudioFlinger::mScreenState changes
2564 uint32_t screenState = AudioFlinger::mScreenState;
2565 if (screenState != mScreenState) {
2566 mScreenState = screenState;
2567 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2568 if (pipe != NULL) {
2569 pipe->setAvgFrames((mScreenState & 1) ?
2570 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2571 }
2572 }
Andy Hung010a1a12014-03-13 13:57:33 -07002573 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002574 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002575 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002576 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002577 } else {
2578 bytesWritten = framesWritten;
2579 }
2580 // otherwise use the HAL / AudioStreamOut directly
2581 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002582 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002583
Eric Laurentbfb1b832013-01-07 09:53:42 -08002584 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002585 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2586 mWriteAckSequence += 2;
2587 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002588 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002589 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002590 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002591 // FIXME We should have an implementation of timestamps for direct output threads.
2592 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002593 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurent51716182016-02-29 18:00:56 -08002594
Eric Laurentbfb1b832013-01-07 09:53:42 -08002595 if (mUseAsyncWrite &&
2596 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2597 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002598 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002599 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002600 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002601 }
Eric Laurent81784c32012-11-19 14:55:58 -08002602 }
2603
Eric Laurent81784c32012-11-19 14:55:58 -08002604 mNumWrites++;
2605 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002606 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002607 return bytesWritten;
2608}
2609
2610void AudioFlinger::PlaybackThread::threadLoop_drain()
2611{
2612 if (mOutput->stream->drain) {
2613 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2614 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002615 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2616 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002617 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002618 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002619 }
2620 mOutput->stream->drain(mOutput->stream,
2621 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2622 : AUDIO_DRAIN_ALL);
2623 }
2624}
2625
2626void AudioFlinger::PlaybackThread::threadLoop_exit()
2627{
Eric Laurent275e8e92014-11-30 15:14:47 -08002628 {
2629 Mutex::Autolock _l(mLock);
2630 for (size_t i = 0; i < mTracks.size(); i++) {
2631 sp<Track> track = mTracks[i];
2632 track->invalidate();
2633 }
2634 }
Eric Laurent81784c32012-11-19 14:55:58 -08002635}
2636
2637/*
2638The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002639 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002640 - mActiveSleepTimeUs from activeSleepTimeUs()
2641 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08002642 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
2643 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08002644 - maxPeriod from frame count and sample rate (MIXER only)
2645
2646The parameters that affect these derived values are:
2647 - frame count
2648 - frame size
2649 - sample rate
2650 - device type: A2DP or not
2651 - device latency
2652 - format: PCM or not
2653 - active sleep time
2654 - idle sleep time
2655*/
2656
2657void AudioFlinger::PlaybackThread::cacheParameters_l()
2658{
Andy Hung25c2dac2014-02-27 14:56:00 -08002659 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002660 mActiveSleepTimeUs = activeSleepTimeUs();
2661 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08002662
2663 // make sure standby delay is not too short when connected to an A2DP sink to avoid
2664 // truncating audio when going to standby.
2665 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
2666 if ((mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != 0) {
2667 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
2668 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
2669 }
2670 }
Eric Laurent81784c32012-11-19 14:55:58 -08002671}
2672
Haynes Mathew George05317d22016-05-03 16:34:26 -07002673void AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08002674{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002675 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08002676 this, streamType, mTracks.size());
Eric Laurent81784c32012-11-19 14:55:58 -08002677
2678 size_t size = mTracks.size();
2679 for (size_t i = 0; i < size; i++) {
2680 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07002681 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002682 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08002683 }
2684 }
2685}
2686
Haynes Mathew George05317d22016-05-03 16:34:26 -07002687void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2688{
2689 Mutex::Autolock _l(mLock);
2690 invalidateTracks_l(streamType);
2691}
2692
Eric Laurent81784c32012-11-19 14:55:58 -08002693status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2694{
Glenn Kastend848eb42016-03-08 13:42:11 -08002695 audio_session_t session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002696 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2697 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002698 bool ownsBuffer = false;
2699
2700 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Glenn Kastend848eb42016-03-08 13:42:11 -08002701 if (session > AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002702 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002703 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002704 if (mType != DIRECT) {
2705 size_t numSamples = mNormalFrameCount * mChannelCount;
2706 buffer = new int16_t[numSamples];
2707 memset(buffer, 0, numSamples * sizeof(int16_t));
2708 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2709 ownsBuffer = true;
2710 }
2711
2712 // Attach all tracks with same session ID to this chain.
2713 for (size_t i = 0; i < mTracks.size(); ++i) {
2714 sp<Track> track = mTracks[i];
2715 if (session == track->sessionId()) {
2716 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2717 buffer);
2718 track->setMainBuffer(buffer);
2719 chain->incTrackCnt();
2720 }
2721 }
2722
2723 // indicate all active tracks in the chain
2724 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2725 sp<Track> track = mActiveTracks[i].promote();
2726 if (track == 0) {
2727 continue;
2728 }
2729 if (session == track->sessionId()) {
2730 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2731 chain->incActiveTrackCnt();
2732 }
2733 }
2734 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002735 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08002736 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002737 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2738 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002739 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Glenn Kastend848eb42016-03-08 13:42:11 -08002740 // chains list in order to be processed last as it contains output stage effects.
Eric Laurent81784c32012-11-19 14:55:58 -08002741 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2742 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08002743 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08002744 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08002745 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08002746 // Effect chain for other sessions are inserted at beginning of effect
2747 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08002748 // sessions is not important.
2749 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
2750 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX,
2751 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08002752 size_t size = mEffectChains.size();
2753 size_t i = 0;
2754 for (i = 0; i < size; i++) {
2755 if (mEffectChains[i]->sessionId() < session) {
2756 break;
2757 }
2758 }
2759 mEffectChains.insertAt(chain, i);
2760 checkSuspendOnAddEffectChain_l(chain);
2761
2762 return NO_ERROR;
2763}
2764
2765size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2766{
Glenn Kastend848eb42016-03-08 13:42:11 -08002767 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08002768
2769 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2770
2771 for (size_t i = 0; i < mEffectChains.size(); i++) {
2772 if (chain == mEffectChains[i]) {
2773 mEffectChains.removeAt(i);
2774 // detach all active tracks from the chain
2775 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2776 sp<Track> track = mActiveTracks[i].promote();
2777 if (track == 0) {
2778 continue;
2779 }
2780 if (session == track->sessionId()) {
2781 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2782 chain.get(), session);
2783 chain->decActiveTrackCnt();
2784 }
2785 }
2786
2787 // detach all tracks with same session ID from this chain
2788 for (size_t i = 0; i < mTracks.size(); ++i) {
2789 sp<Track> track = mTracks[i];
2790 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002791 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002792 chain->decTrackCnt();
2793 }
2794 }
2795 break;
2796 }
2797 }
2798 return mEffectChains.size();
2799}
2800
2801status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2802 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2803{
2804 Mutex::Autolock _l(mLock);
2805 return attachAuxEffect_l(track, EffectId);
2806}
2807
2808status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2809 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2810{
2811 status_t status = NO_ERROR;
2812
2813 if (EffectId == 0) {
2814 track->setAuxBuffer(0, NULL);
2815 } else {
2816 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2817 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2818 if (effect != 0) {
2819 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2820 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2821 } else {
2822 status = INVALID_OPERATION;
2823 }
2824 } else {
2825 status = BAD_VALUE;
2826 }
2827 }
2828 return status;
2829}
2830
2831void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2832{
2833 for (size_t i = 0; i < mTracks.size(); ++i) {
2834 sp<Track> track = mTracks[i];
2835 if (track->auxEffectId() == effectId) {
2836 attachAuxEffect_l(track, 0);
2837 }
2838 }
2839}
2840
2841bool AudioFlinger::PlaybackThread::threadLoop()
2842{
2843 Vector< sp<Track> > tracksToRemove;
2844
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002845 mStandbyTimeNs = systemTime();
Eric Laurent81784c32012-11-19 14:55:58 -08002846
2847 // MIXER
2848 nsecs_t lastWarning = 0;
2849
2850 // DUPLICATING
2851 // FIXME could this be made local to while loop?
2852 writeFrames = 0;
2853
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002854 int lastGeneration = 0;
2855
Eric Laurent81784c32012-11-19 14:55:58 -08002856 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002857 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002858
2859 if (mType == MIXER) {
2860 sleepTimeShift = 0;
2861 }
2862
2863 CpuStats cpuStats;
2864 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2865
2866 acquireWakeLock();
2867
Glenn Kasten9e58b552013-01-18 15:09:48 -08002868 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2869 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2870 // and then that string will be logged at the next convenient opportunity.
2871 const char *logString = NULL;
2872
Eric Laurent664539d2013-09-23 18:24:31 -07002873 checkSilentMode_l();
2874
Eric Laurent81784c32012-11-19 14:55:58 -08002875 while (!exitPending())
2876 {
2877 cpuStats.sample(myName);
2878
2879 Vector< sp<EffectChain> > effectChains;
2880
Eric Laurent81784c32012-11-19 14:55:58 -08002881 { // scope for mLock
2882
2883 Mutex::Autolock _l(mLock);
2884
Eric Laurent021cf962014-05-13 10:18:14 -07002885 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002886
Glenn Kasten9e58b552013-01-18 15:09:48 -08002887 if (logString != NULL) {
2888 mNBLogWriter->logTimestamp();
2889 mNBLogWriter->log(logString);
2890 logString = NULL;
2891 }
2892
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002893 // Gather the framesReleased counters for all active tracks,
Andy Hunge10393e2015-06-12 13:59:33 -07002894 // and associate with the sink frames written out. We need
2895 // this to convert the sink timestamp to the track timestamp.
2896 if (mNormalSink != 0) {
Andy Hungc54b1ff2016-02-23 14:07:07 -08002897 // Note: The DuplicatingThread may not have a mNormalSink.
Andy Hung818e7a32016-02-16 18:08:07 -08002898 // We always fetch the timestamp here because often the downstream
2899 // sink will block whie writing.
2900 ExtendedTimestamp timestamp; // use private copy to fetch
2901 (void) mNormalSink->getTimestamp(timestamp);
2902 // copy over kernel info
2903 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
2904 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
2905 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
2906 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hungc54b1ff2016-02-23 14:07:07 -08002907 }
2908 // mFramesWritten for non-offloaded tracks are contiguous
2909 // even after standby() is called. This is useful for the track frame
2910 // to sink frame mapping.
2911 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
2912 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
2913 const size_t size = mActiveTracks.size();
2914 for (size_t i = 0; i < size; ++i) {
2915 sp<Track> t = mActiveTracks[i].promote();
2916 if (t != 0 && !t->isFastTrack()) {
2917 t->updateTrackFrameInfo(
2918 t->mAudioTrackServerProxy->framesReleased(),
2919 mFramesWritten,
2920 mTimestamp);
Andy Hunge10393e2015-06-12 13:59:33 -07002921 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002922 }
2923
Eric Laurent81784c32012-11-19 14:55:58 -08002924 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002925 if (mSignalPending) {
2926 // A signal was raised while we were unlocked
2927 mSignalPending = false;
2928 } else if (waitingAsyncCallback_l()) {
2929 if (exitPending()) {
2930 break;
2931 }
Marco Nelissen078538c2015-05-12 09:17:57 -07002932 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07002933 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07002934 releaseWakeLock_l();
2935 released = true;
2936 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002937 mWakeLockUids.clear();
2938 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002939 ALOGV("wait async completion");
2940 mWaitWorkCV.wait(mLock);
2941 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07002942 if (released) {
2943 acquireWakeLock_l();
2944 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002945 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
2946 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002947
2948 continue;
2949 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002950 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002951 isSuspended()) {
2952 // put audio hardware into standby after short delay
2953 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002954
2955 threadLoop_standby();
2956
2957 mStandby = true;
2958 }
2959
2960 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2961 // we're about to wait, flush the binder command buffer
2962 IPCThreadState::self()->flushCommands();
2963
2964 clearOutputTracks();
2965
2966 if (exitPending()) {
2967 break;
2968 }
2969
2970 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002971 mWakeLockUids.clear();
2972 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002973 // wait until we have something to do...
2974 ALOGV("%s going to sleep", myName.string());
2975 mWaitWorkCV.wait(mLock);
2976 ALOGV("%s waking up", myName.string());
2977 acquireWakeLock_l();
2978
2979 mMixerStatus = MIXER_IDLE;
2980 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2981 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002982 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002983 checkSilentMode_l();
2984
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002985 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
2986 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002987 if (mType == MIXER) {
2988 sleepTimeShift = 0;
2989 }
2990
2991 continue;
2992 }
2993 }
Eric Laurent81784c32012-11-19 14:55:58 -08002994 // mMixerStatusIgnoringFastTracks is also updated internally
2995 mMixerStatus = prepareTracks_l(&tracksToRemove);
2996
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002997 // compare with previously applied list
2998 if (lastGeneration != mActiveTracksGeneration) {
2999 // update wakelock
3000 updateWakeLockUids_l(mWakeLockUids);
3001 lastGeneration = mActiveTracksGeneration;
3002 }
3003
Eric Laurent81784c32012-11-19 14:55:58 -08003004 // prevent any changes in effect chain list and in each effect chain
3005 // during mixing and effect process as the audio buffers could be deleted
3006 // or modified if an effect is created or deleted
3007 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003008 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003009
Eric Laurentbfb1b832013-01-07 09:53:42 -08003010 if (mBytesRemaining == 0) {
3011 mCurrentWriteLength = 0;
3012 if (mMixerStatus == MIXER_TRACKS_READY) {
3013 // threadLoop_mix() sets mCurrentWriteLength
3014 threadLoop_mix();
3015 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3016 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003017 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003018 // must be written to HAL
3019 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003020 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003021 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003022 }
3023 }
Andy Hung98ef9782014-03-04 14:46:50 -08003024 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003025 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003026 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3027 // or mSinkBuffer (if there are no effects).
3028 //
3029 // This is done pre-effects computation; if effects change to
3030 // support higher precision, this needs to move.
3031 //
3032 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003033 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003034 if (mMixerBufferValid) {
3035 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3036 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3037
Andy Hung2ddee192015-12-18 17:34:44 -08003038 // mono blend occurs for mixer threads only (not direct or offloaded)
3039 // and is handled here if we're going directly to the sink.
3040 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003041 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3042 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003043 }
3044
Andy Hung98ef9782014-03-04 14:46:50 -08003045 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
3046 mNormalFrameCount * mChannelCount);
3047 }
3048
Eric Laurentbfb1b832013-01-07 09:53:42 -08003049 mBytesRemaining = mCurrentWriteLength;
3050 if (isSuspended()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003051 mSleepTimeUs = suspendSleepTimeUs();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003052 // simulate write to HAL when suspended
Andy Hung25c2dac2014-02-27 14:56:00 -08003053 mBytesWritten += mSinkBufferSize;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003054 mFramesWritten += mSinkBufferSize / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003055 mBytesRemaining = 0;
3056 }
Eric Laurent81784c32012-11-19 14:55:58 -08003057
Eric Laurentbfb1b832013-01-07 09:53:42 -08003058 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003059 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003060 for (size_t i = 0; i < effectChains.size(); i ++) {
3061 effectChains[i]->process_l();
3062 }
Eric Laurent81784c32012-11-19 14:55:58 -08003063 }
3064 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003065 // Process effect chains for offloaded thread even if no audio
3066 // was read from audio track: process only updates effect state
3067 // and thus does have to be synchronized with audio writes but may have
3068 // to be called while waiting for async write callback
3069 if (mType == OFFLOAD) {
3070 for (size_t i = 0; i < effectChains.size(); i ++) {
3071 effectChains[i]->process_l();
3072 }
3073 }
Eric Laurent81784c32012-11-19 14:55:58 -08003074
Andy Hung98ef9782014-03-04 14:46:50 -08003075 // Only if the Effects buffer is enabled and there is data in the
3076 // Effects buffer (buffer valid), we need to
3077 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003078 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003079 if (mEffectBufferValid) {
3080 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003081
3082 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003083 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3084 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003085 }
3086
Andy Hung98ef9782014-03-04 14:46:50 -08003087 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
3088 mNormalFrameCount * mChannelCount);
3089 }
3090
Eric Laurent81784c32012-11-19 14:55:58 -08003091 // enable changes in effect chain
3092 unlockEffectChains(effectChains);
3093
Eric Laurentbfb1b832013-01-07 09:53:42 -08003094 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003095 // mSleepTimeUs == 0 means we must write to audio hardware
3096 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003097 ssize_t ret = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003098 if (mBytesRemaining) {
Andy Hung08fb1742015-05-31 23:22:10 -07003099 ret = threadLoop_write();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003100 if (ret < 0) {
3101 mBytesRemaining = 0;
3102 } else {
3103 mBytesWritten += ret;
3104 mBytesRemaining -= ret;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003105 mFramesWritten += ret / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003106 }
3107 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3108 (mMixerStatus == MIXER_DRAIN_ALL)) {
3109 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003110 }
Andy Hung08fb1742015-05-31 23:22:10 -07003111 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003112 // write blocked detection
3113 nsecs_t now = systemTime();
3114 nsecs_t delta = now - mLastWriteTime;
Andy Hung08fb1742015-05-31 23:22:10 -07003115 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003116 mNumDelayedWrites++;
3117 if ((now - lastWarning) > kWarningThrottleNs) {
3118 ATRACE_NAME("underrun");
3119 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003120 (unsigned long long) ns2ms(delta), mNumDelayedWrites, this);
Glenn Kasten4944acb2013-08-19 08:39:20 -07003121 lastWarning = now;
3122 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003123 }
Andy Hung08fb1742015-05-31 23:22:10 -07003124
3125 if (mThreadThrottle
3126 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
3127 && ret > 0) { // we wrote something
3128 // Limit MixerThread data processing to no more than twice the
3129 // expected processing rate.
3130 //
3131 // This helps prevent underruns with NuPlayer and other applications
3132 // which may set up buffers that are close to the minimum size, or use
3133 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3134 //
3135 // The throttle smooths out sudden large data drains from the device,
3136 // e.g. when it comes out of standby, which often causes problems with
3137 // (1) mixer threads without a fast mixer (which has its own warm-up)
3138 // (2) minimum buffer sized tracks (even if the track is full,
3139 // the app won't fill fast enough to handle the sudden draw).
3140
3141 const int32_t deltaMs = delta / 1000000;
3142 const int32_t throttleMs = mHalfBufferMs - deltaMs;
3143 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3144 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003145 // notify of throttle start on verbose log
3146 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3147 "mixer(%p) throttle begin:"
3148 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003149 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003150 mThreadThrottleTimeMs += throttleMs;
3151 } else {
3152 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3153 if (diff > 0) {
3154 // notify of throttle end on debug log
3155 ALOGD("mixer(%p) throttle end: throttle time(%u)", this, diff);
3156 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3157 }
Andy Hung08fb1742015-05-31 23:22:10 -07003158 }
3159 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003160 }
Eric Laurent81784c32012-11-19 14:55:58 -08003161
Eric Laurentbfb1b832013-01-07 09:53:42 -08003162 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003163 ATRACE_BEGIN("sleep");
Eric Laurent51716182016-02-29 18:00:56 -08003164 if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
3165 Mutex::Autolock _l(mLock);
3166 if (!mSignalPending && !exitPending()) {
Eric Laurent3eaf66b2016-04-01 14:44:17 -07003167 // If more than one buffer has been written to the audio HAL since exiting
3168 // standby or last flush, do not sleep more than one buffer duration
3169 // since last write and not less than kDirectMinSleepTimeUs.
Eric Laurent51716182016-02-29 18:00:56 -08003170 // Wake up if a command is received
Eric Laurent51716182016-02-29 18:00:56 -08003171 uint32_t timeoutUs = mSleepTimeUs;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07003172 if (mBytesWritten >= (int64_t) mBufferSize) {
3173 nsecs_t now = systemTime();
3174 uint32_t deltaUs = (uint32_t)((now - mLastWriteTime) / 1000);
3175 if (timeoutUs + deltaUs > mBufferDurationUs) {
3176 if (mBufferDurationUs > deltaUs) {
3177 timeoutUs = mBufferDurationUs - deltaUs;
3178 if (timeoutUs < kDirectMinSleepTimeUs) {
3179 timeoutUs = kDirectMinSleepTimeUs;
3180 }
3181 } else {
Eric Laurent51716182016-02-29 18:00:56 -08003182 timeoutUs = kDirectMinSleepTimeUs;
3183 }
Eric Laurent51716182016-02-29 18:00:56 -08003184 }
3185 }
3186 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)timeoutUs));
3187 }
3188 } else {
3189 usleep(mSleepTimeUs);
3190 }
Glenn Kastene7754022014-10-31 12:11:26 -07003191 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003192 }
Eric Laurent81784c32012-11-19 14:55:58 -08003193 }
3194
3195 // Finally let go of removed track(s), without the lock held
3196 // since we can't guarantee the destructors won't acquire that
3197 // same lock. This will also mutate and push a new fast mixer state.
3198 threadLoop_removeTracks(tracksToRemove);
3199 tracksToRemove.clear();
3200
3201 // FIXME I don't understand the need for this here;
3202 // it was in the original code but maybe the
3203 // assignment in saveOutputTracks() makes this unnecessary?
3204 clearOutputTracks();
3205
3206 // Effect chains will be actually deleted here if they were removed from
3207 // mEffectChains list during mixing or effects processing
3208 effectChains.clear();
3209
3210 // FIXME Note that the above .clear() is no longer necessary since effectChains
3211 // is now local to this block, but will keep it for now (at least until merge done).
3212 }
3213
Eric Laurentbfb1b832013-01-07 09:53:42 -08003214 threadLoop_exit();
3215
Eric Laurentcf817a22014-08-04 20:36:31 -07003216 if (!mStandby) {
3217 threadLoop_standby();
3218 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003219 }
3220
3221 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003222 mWakeLockUids.clear();
3223 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08003224
3225 ALOGV("Thread %p type %d exiting", this, mType);
3226 return false;
3227}
3228
Eric Laurentbfb1b832013-01-07 09:53:42 -08003229// removeTracks_l() must be called with ThreadBase::mLock held
3230void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3231{
3232 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003233 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003234 for (size_t i=0 ; i<count ; i++) {
3235 const sp<Track>& track = tracksToRemove.itemAt(i);
3236 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003237 mWakeLockUids.remove(track->uid());
3238 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003239 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3240 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3241 if (chain != 0) {
3242 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3243 track->sessionId());
3244 chain->decActiveTrackCnt();
3245 }
3246 if (track->isTerminated()) {
3247 removeTrack_l(track);
3248 }
3249 }
3250 }
3251
3252}
Eric Laurent81784c32012-11-19 14:55:58 -08003253
Eric Laurentaccc1472013-09-20 09:36:34 -07003254status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3255{
3256 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08003257 ExtendedTimestamp ets;
3258 status_t status = mNormalSink->getTimestamp(ets);
3259 if (status == NO_ERROR) {
3260 status = ets.getBestTimestamp(&timestamp);
3261 }
3262 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07003263 }
Andy Hung9a1c8892014-12-03 11:37:42 -08003264 if ((mType == OFFLOAD || mType == DIRECT)
3265 && mOutput != NULL && mOutput->stream->get_presentation_position) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003266 uint64_t position64;
Phil Burk062e67a2015-02-11 13:40:50 -08003267 int ret = mOutput->getPresentationPosition(&position64, &timestamp.mTime);
Eric Laurentaccc1472013-09-20 09:36:34 -07003268 if (ret == 0) {
3269 timestamp.mPosition = (uint32_t)position64;
3270 return NO_ERROR;
3271 }
3272 }
3273 return INVALID_OPERATION;
3274}
Eric Laurent1c333e22014-05-20 10:48:17 -07003275
Eric Laurent054d9d32015-04-24 08:48:48 -07003276status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3277 audio_patch_handle_t *handle)
3278{
Glenn Kastenc05b8d72016-03-24 09:48:17 -07003279 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent054d9d32015-04-24 08:48:48 -07003280
Glenn Kastenc05b8d72016-03-24 09:48:17 -07003281 status_t status = PlaybackThread::createAudioPatch_l(patch, handle);
Eric Laurent054d9d32015-04-24 08:48:48 -07003282
3283 return status;
3284}
3285
Eric Laurent1c333e22014-05-20 10:48:17 -07003286status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3287 audio_patch_handle_t *handle)
3288{
3289 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003290
3291 // store new device and send to effects
3292 audio_devices_t type = AUDIO_DEVICE_NONE;
3293 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3294 type |= patch->sinks[i].ext.device.type;
3295 }
3296
3297#ifdef ADD_BATTERY_DATA
3298 // when changing the audio output device, call addBatteryData to notify
3299 // the change
3300 if (mOutDevice != type) {
3301 uint32_t params = 0;
3302 // check whether speaker is on
3303 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3304 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003305 }
3306
Eric Laurent054d9d32015-04-24 08:48:48 -07003307 audio_devices_t deviceWithoutSpeaker
3308 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3309 // check if any other device (except speaker) is on
3310 if (type & deviceWithoutSpeaker) {
3311 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3312 }
3313
3314 if (params != 0) {
3315 addBatteryData(params);
3316 }
3317 }
3318#endif
3319
3320 for (size_t i = 0; i < mEffectChains.size(); i++) {
3321 mEffectChains[i]->setDevice_l(type);
3322 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003323
3324 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3325 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3326 bool configChanged = mPrevOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003327 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003328 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003329
3330 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003331 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3332 status = hwDevice->create_audio_patch(hwDevice,
3333 patch->num_sources,
3334 patch->sources,
3335 patch->num_sinks,
3336 patch->sinks,
3337 handle);
3338 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003339 char *address;
3340 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3341 //FIXME: we only support address on first sink with HAL version < 3.0
3342 address = audio_device_address_to_parameter(
3343 patch->sinks[0].ext.device.type,
3344 patch->sinks[0].ext.device.address);
3345 } else {
3346 address = (char *)calloc(1, 1);
3347 }
3348 AudioParameter param = AudioParameter(String8(address));
3349 free(address);
3350 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), (int)type);
3351 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3352 param.toString().string());
3353 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003354 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003355 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003356 mPrevOutDevice = type;
Eric Laurente8726fe2015-06-26 09:39:24 -07003357 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3358 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003359 return status;
3360}
3361
Eric Laurent054d9d32015-04-24 08:48:48 -07003362status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3363{
Glenn Kastenc05b8d72016-03-24 09:48:17 -07003364 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent054d9d32015-04-24 08:48:48 -07003365
3366 status_t status = PlaybackThread::releaseAudioPatch_l(handle);
3367
Eric Laurent054d9d32015-04-24 08:48:48 -07003368 return status;
3369}
3370
Eric Laurent1c333e22014-05-20 10:48:17 -07003371status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3372{
3373 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003374
3375 mOutDevice = AUDIO_DEVICE_NONE;
3376
Eric Laurent1c333e22014-05-20 10:48:17 -07003377 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
3378 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3379 status = hwDevice->release_audio_patch(hwDevice, handle);
3380 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003381 AudioParameter param;
3382 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
3383 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3384 param.toString().string());
Eric Laurent1c333e22014-05-20 10:48:17 -07003385 }
3386 return status;
3387}
3388
Eric Laurent83b88082014-06-20 18:31:16 -07003389void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3390{
3391 Mutex::Autolock _l(mLock);
3392 mTracks.add(track);
3393}
3394
3395void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3396{
3397 Mutex::Autolock _l(mLock);
3398 destroyTrack_l(track);
3399}
3400
3401void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3402{
3403 ThreadBase::getAudioPortConfig(config);
3404 config->role = AUDIO_PORT_ROLE_SOURCE;
3405 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3406 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3407}
3408
Eric Laurent81784c32012-11-19 14:55:58 -08003409// ----------------------------------------------------------------------------
3410
3411AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003412 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3413 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003414 // mAudioMixer below
3415 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08003416 mFastMixerFutex(0),
3417 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08003418 // mOutputSink below
3419 // mPipeSink below
3420 // mNormalSink below
3421{
3422 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003423 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%zu, "
3424 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003425 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3426 mNormalFrameCount);
3427 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3428
Andy Hungfbfc3952015-01-15 13:33:51 -08003429 if (type == DUPLICATING) {
3430 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3431 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3432 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3433 return;
3434 }
Eric Laurent81784c32012-11-19 14:55:58 -08003435 // create an NBAIO sink for the HAL output stream, and negotiate
3436 mOutputSink = new AudioStreamOutSink(output->stream);
3437 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003438 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003439#if !LOG_NDEBUG
3440 ssize_t index =
3441#else
3442 (void)
3443#endif
3444 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003445 ALOG_ASSERT(index == 0);
3446
3447 // initialize fast mixer depending on configuration
3448 bool initFastMixer;
3449 switch (kUseFastMixer) {
3450 case FastMixer_Never:
3451 initFastMixer = false;
3452 break;
3453 case FastMixer_Always:
3454 initFastMixer = true;
3455 break;
3456 case FastMixer_Static:
3457 case FastMixer_Dynamic:
3458 initFastMixer = mFrameCount < mNormalFrameCount;
3459 break;
3460 }
3461 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003462 audio_format_t fastMixerFormat;
3463 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3464 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3465 } else {
3466 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3467 }
3468 if (mFormat != fastMixerFormat) {
3469 // change our Sink format to accept our intermediate precision
3470 mFormat = fastMixerFormat;
3471 free(mSinkBuffer);
3472 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3473 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3474 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3475 }
Eric Laurent81784c32012-11-19 14:55:58 -08003476
3477 // create a MonoPipe to connect our submix to FastMixer
3478 NBAIO_Format format = mOutputSink->format();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003479#ifdef TEE_SINK
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003480 NBAIO_Format origformat = format;
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003481#endif
Andy Hung1258c1a2014-05-23 21:22:17 -07003482 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07003483 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003484 format.mFormat = fastMixerFormat;
3485 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3486
Eric Laurent81784c32012-11-19 14:55:58 -08003487 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3488 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3489 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3490 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3491 const NBAIO_Format offers[1] = {format};
3492 size_t numCounterOffers = 0;
Glenn Kastenfc302fd2016-04-11 14:11:26 -07003493#if !LOG_NDEBUG || defined(TEE_SINK)
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003494 ssize_t index =
3495#else
3496 (void)
3497#endif
3498 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003499 ALOG_ASSERT(index == 0);
3500 monoPipe->setAvgFrames((mScreenState & 1) ?
3501 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3502 mPipeSink = monoPipe;
3503
Glenn Kasten46909e72013-02-26 09:20:22 -08003504#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003505 if (mTeeSinkOutputEnabled) {
3506 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003507 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3508 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003509 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003510 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003511 ALOG_ASSERT(index == 0);
3512 mTeeSink = teeSink;
3513 PipeReader *teeSource = new PipeReader(*teeSink);
3514 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003515 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003516 ALOG_ASSERT(index == 0);
3517 mTeeSource = teeSource;
3518 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003519#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003520
3521 // create fast mixer and configure it initially with just one fast track for our submix
3522 mFastMixer = new FastMixer();
3523 FastMixerStateQueue *sq = mFastMixer->sq();
3524#ifdef STATE_QUEUE_DUMP
3525 sq->setObserverDump(&mStateQueueObserverDump);
3526 sq->setMutatorDump(&mStateQueueMutatorDump);
3527#endif
3528 FastMixerState *state = sq->begin();
3529 FastTrack *fastTrack = &state->mFastTracks[0];
3530 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3531 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3532 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003533 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3534 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003535 fastTrack->mGeneration++;
3536 state->mFastTracksGen++;
3537 state->mTrackMask = 1;
3538 // fast mixer will use the HAL output sink
3539 state->mOutputSink = mOutputSink.get();
3540 state->mOutputSinkGen++;
3541 state->mFrameCount = mFrameCount;
3542 state->mCommand = FastMixerState::COLD_IDLE;
3543 // already done in constructor initialization list
3544 //mFastMixerFutex = 0;
3545 state->mColdFutexAddr = &mFastMixerFutex;
3546 state->mColdGen++;
3547 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003548#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003549 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003550#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003551 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3552 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003553 sq->end();
3554 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3555
3556 // start the fast mixer
3557 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3558 pid_t tid = mFastMixer->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003559 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003560
3561#ifdef AUDIO_WATCHDOG
3562 // create and start the watchdog
3563 mAudioWatchdog = new AudioWatchdog();
3564 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3565 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3566 tid = mAudioWatchdog->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003567 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003568#endif
3569
Eric Laurent81784c32012-11-19 14:55:58 -08003570 }
3571
3572 switch (kUseFastMixer) {
3573 case FastMixer_Never:
3574 case FastMixer_Dynamic:
3575 mNormalSink = mOutputSink;
3576 break;
3577 case FastMixer_Always:
3578 mNormalSink = mPipeSink;
3579 break;
3580 case FastMixer_Static:
3581 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3582 break;
3583 }
3584}
3585
3586AudioFlinger::MixerThread::~MixerThread()
3587{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003588 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003589 FastMixerStateQueue *sq = mFastMixer->sq();
3590 FastMixerState *state = sq->begin();
3591 if (state->mCommand == FastMixerState::COLD_IDLE) {
3592 int32_t old = android_atomic_inc(&mFastMixerFutex);
3593 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003594 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003595 }
3596 }
3597 state->mCommand = FastMixerState::EXIT;
3598 sq->end();
3599 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3600 mFastMixer->join();
3601 // Though the fast mixer thread has exited, it's state queue is still valid.
3602 // We'll use that extract the final state which contains one remaining fast track
3603 // corresponding to our sub-mix.
3604 state = sq->begin();
3605 ALOG_ASSERT(state->mTrackMask == 1);
3606 FastTrack *fastTrack = &state->mFastTracks[0];
3607 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3608 delete fastTrack->mBufferProvider;
3609 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003610 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003611#ifdef AUDIO_WATCHDOG
3612 if (mAudioWatchdog != 0) {
3613 mAudioWatchdog->requestExit();
3614 mAudioWatchdog->requestExitAndWait();
3615 mAudioWatchdog.clear();
3616 }
3617#endif
3618 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003619 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003620 delete mAudioMixer;
3621}
3622
3623
3624uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3625{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003626 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003627 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3628 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3629 }
3630 return latency;
3631}
3632
3633
3634void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3635{
3636 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3637}
3638
Eric Laurentbfb1b832013-01-07 09:53:42 -08003639ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003640{
3641 // FIXME we should only do one push per cycle; confirm this is true
3642 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003643 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003644 FastMixerStateQueue *sq = mFastMixer->sq();
3645 FastMixerState *state = sq->begin();
3646 if (state->mCommand != FastMixerState::MIX_WRITE &&
3647 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3648 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07003649
3650 // FIXME workaround for first HAL write being CPU bound on some devices
3651 ATRACE_BEGIN("write");
3652 mOutput->write((char *)mSinkBuffer, 0);
3653 ATRACE_END();
3654
Eric Laurent81784c32012-11-19 14:55:58 -08003655 int32_t old = android_atomic_inc(&mFastMixerFutex);
3656 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003657 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003658 }
3659#ifdef AUDIO_WATCHDOG
3660 if (mAudioWatchdog != 0) {
3661 mAudioWatchdog->resume();
3662 }
3663#endif
3664 }
3665 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003666#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003667 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003668 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003669#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003670 sq->end();
3671 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3672 if (kUseFastMixer == FastMixer_Dynamic) {
3673 mNormalSink = mPipeSink;
3674 }
3675 } else {
3676 sq->end(false /*didModify*/);
3677 }
3678 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003679 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003680}
3681
3682void AudioFlinger::MixerThread::threadLoop_standby()
3683{
3684 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003685 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003686 FastMixerStateQueue *sq = mFastMixer->sq();
3687 FastMixerState *state = sq->begin();
3688 if (!(state->mCommand & FastMixerState::IDLE)) {
3689 state->mCommand = FastMixerState::COLD_IDLE;
3690 state->mColdFutexAddr = &mFastMixerFutex;
3691 state->mColdGen++;
3692 mFastMixerFutex = 0;
3693 sq->end();
3694 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3695 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3696 if (kUseFastMixer == FastMixer_Dynamic) {
3697 mNormalSink = mOutputSink;
3698 }
3699#ifdef AUDIO_WATCHDOG
3700 if (mAudioWatchdog != 0) {
3701 mAudioWatchdog->pause();
3702 }
3703#endif
3704 } else {
3705 sq->end(false /*didModify*/);
3706 }
3707 }
3708 PlaybackThread::threadLoop_standby();
3709}
3710
Eric Laurentbfb1b832013-01-07 09:53:42 -08003711bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3712{
3713 return false;
3714}
3715
3716bool AudioFlinger::PlaybackThread::shouldStandby_l()
3717{
3718 return !mStandby;
3719}
3720
3721bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3722{
3723 Mutex::Autolock _l(mLock);
3724 return waitingAsyncCallback_l();
3725}
3726
Eric Laurent81784c32012-11-19 14:55:58 -08003727// shared by MIXER and DIRECT, overridden by DUPLICATING
3728void AudioFlinger::PlaybackThread::threadLoop_standby()
3729{
3730 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08003731 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003732 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003733 // discard any pending drain or write ack by incrementing sequence
3734 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3735 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003736 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003737 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3738 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003739 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003740 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003741}
3742
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003743void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3744{
3745 ALOGV("signal playback thread");
3746 broadcast_l();
3747}
3748
Eric Laurent81784c32012-11-19 14:55:58 -08003749void AudioFlinger::MixerThread::threadLoop_mix()
3750{
Eric Laurent81784c32012-11-19 14:55:58 -08003751 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08003752 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08003753 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003754 // increase sleep time progressively when application underrun condition clears.
3755 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3756 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3757 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003758 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003759 sleepTimeShift--;
3760 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003761 mSleepTimeUs = 0;
3762 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08003763 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003764
Eric Laurent81784c32012-11-19 14:55:58 -08003765}
3766
3767void AudioFlinger::MixerThread::threadLoop_sleepTime()
3768{
3769 // If no tracks are ready, sleep once for the duration of an output
3770 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003771 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003772 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003773 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
3774 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
3775 mSleepTimeUs = kMinThreadSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003776 }
3777 // reduce sleep time in case of consecutive application underruns to avoid
3778 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3779 // duration we would end up writing less data than needed by the audio HAL if
3780 // the condition persists.
3781 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3782 sleepTimeShift++;
3783 }
3784 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003785 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003786 }
3787 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003788 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3789 // before effects processing or output.
3790 if (mMixerBufferValid) {
3791 memset(mMixerBuffer, 0, mMixerBufferSize);
3792 } else {
3793 memset(mSinkBuffer, 0, mSinkBufferSize);
3794 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003795 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003796 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3797 "anticipated start");
3798 }
3799 // TODO add standby time extension fct of effect tail
3800}
3801
3802// prepareTracks_l() must be called with ThreadBase::mLock held
3803AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3804 Vector< sp<Track> > *tracksToRemove)
3805{
3806
3807 mixer_state mixerStatus = MIXER_IDLE;
3808 // find out which tracks need to be processed
3809 size_t count = mActiveTracks.size();
3810 size_t mixedTracks = 0;
3811 size_t tracksWithEffect = 0;
3812 // counts only _active_ fast tracks
3813 size_t fastTracks = 0;
3814 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3815
3816 float masterVolume = mMasterVolume;
3817 bool masterMute = mMasterMute;
3818
3819 if (masterMute) {
3820 masterVolume = 0;
3821 }
3822 // Delegate master volume control to effect in output mix effect chain if needed
3823 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3824 if (chain != 0) {
3825 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3826 chain->setVolume_l(&v, &v);
3827 masterVolume = (float)((v + (1 << 23)) >> 24);
3828 chain.clear();
3829 }
3830
3831 // prepare a new state to push
3832 FastMixerStateQueue *sq = NULL;
3833 FastMixerState *state = NULL;
3834 bool didModify = false;
3835 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003836 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003837 sq = mFastMixer->sq();
3838 state = sq->begin();
3839 }
3840
Andy Hung69aed5f2014-02-25 17:24:40 -08003841 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003842 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003843
Eric Laurent81784c32012-11-19 14:55:58 -08003844 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003845 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003846 if (t == 0) {
3847 continue;
3848 }
3849
3850 // this const just means the local variable doesn't change
3851 Track* const track = t.get();
3852
3853 // process fast tracks
3854 if (track->isFastTrack()) {
3855
3856 // It's theoretically possible (though unlikely) for a fast track to be created
3857 // and then removed within the same normal mix cycle. This is not a problem, as
3858 // the track never becomes active so it's fast mixer slot is never touched.
3859 // The converse, of removing an (active) track and then creating a new track
3860 // at the identical fast mixer slot within the same normal mix cycle,
3861 // is impossible because the slot isn't marked available until the end of each cycle.
3862 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07003863 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08003864 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3865 FastTrack *fastTrack = &state->mFastTracks[j];
3866
3867 // Determine whether the track is currently in underrun condition,
3868 // and whether it had a recent underrun.
3869 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3870 FastTrackUnderruns underruns = ftDump->mUnderruns;
3871 uint32_t recentFull = (underruns.mBitFields.mFull -
3872 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3873 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3874 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3875 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3876 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3877 uint32_t recentUnderruns = recentPartial + recentEmpty;
3878 track->mObservedUnderruns = underruns;
3879 // don't count underruns that occur while stopping or pausing
3880 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07003881 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3882 recentUnderruns > 0) {
3883 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3884 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Phil Burk2812d9e2016-01-04 10:34:30 -08003885 } else {
3886 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Eric Laurent81784c32012-11-19 14:55:58 -08003887 }
3888
3889 // This is similar to the state machine for normal tracks,
3890 // with a few modifications for fast tracks.
3891 bool isActive = true;
3892 switch (track->mState) {
3893 case TrackBase::STOPPING_1:
3894 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08003895 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003896 track->mState = TrackBase::STOPPING_2;
3897 }
3898 break;
3899 case TrackBase::PAUSING:
3900 // ramp down is not yet implemented
3901 track->setPaused();
3902 break;
3903 case TrackBase::RESUMING:
3904 // ramp up is not yet implemented
3905 track->mState = TrackBase::ACTIVE;
3906 break;
3907 case TrackBase::ACTIVE:
3908 if (recentFull > 0 || recentPartial > 0) {
3909 // track has provided at least some frames recently: reset retry count
3910 track->mRetryCount = kMaxTrackRetries;
3911 }
3912 if (recentUnderruns == 0) {
3913 // no recent underruns: stay active
3914 break;
3915 }
3916 // there has recently been an underrun of some kind
3917 if (track->sharedBuffer() == 0) {
3918 // were any of the recent underruns "empty" (no frames available)?
3919 if (recentEmpty == 0) {
3920 // no, then ignore the partial underruns as they are allowed indefinitely
3921 break;
3922 }
3923 // there has recently been an "empty" underrun: decrement the retry counter
3924 if (--(track->mRetryCount) > 0) {
3925 break;
3926 }
3927 // indicate to client process that the track was disabled because of underrun;
3928 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08003929 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08003930 // remove from active list, but state remains ACTIVE [confusing but true]
3931 isActive = false;
3932 break;
3933 }
3934 // fall through
3935 case TrackBase::STOPPING_2:
3936 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003937 case TrackBase::STOPPED:
3938 case TrackBase::FLUSHED: // flush() while active
3939 // Check for presentation complete if track is inactive
3940 // We have consumed all the buffers of this track.
3941 // This would be incomplete if we auto-paused on underrun
3942 {
3943 size_t audioHALFrames =
3944 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08003945 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003946 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
3947 // track stays in active list until presentation is complete
3948 break;
3949 }
3950 }
3951 if (track->isStopping_2()) {
3952 track->mState = TrackBase::STOPPED;
3953 }
3954 if (track->isStopped()) {
3955 // Can't reset directly, as fast mixer is still polling this track
3956 // track->reset();
3957 // So instead mark this track as needing to be reset after push with ack
3958 resetMask |= 1 << i;
3959 }
3960 isActive = false;
3961 break;
3962 case TrackBase::IDLE:
3963 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08003964 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08003965 }
3966
3967 if (isActive) {
3968 // was it previously inactive?
3969 if (!(state->mTrackMask & (1 << j))) {
3970 ExtendedAudioBufferProvider *eabp = track;
3971 VolumeProvider *vp = track;
3972 fastTrack->mBufferProvider = eabp;
3973 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08003974 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003975 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08003976 fastTrack->mGeneration++;
3977 state->mTrackMask |= 1 << j;
3978 didModify = true;
3979 // no acknowledgement required for newly active tracks
3980 }
3981 // cache the combined master volume and stream type volume for fast mixer; this
3982 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08003983 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08003984 ++fastTracks;
3985 } else {
3986 // was it previously active?
3987 if (state->mTrackMask & (1 << j)) {
3988 fastTrack->mBufferProvider = NULL;
3989 fastTrack->mGeneration++;
3990 state->mTrackMask &= ~(1 << j);
3991 didModify = true;
3992 // If any fast tracks were removed, we must wait for acknowledgement
3993 // because we're about to decrement the last sp<> on those tracks.
3994 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3995 } else {
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08003996 LOG_ALWAYS_FATAL("fast track %d should have been active; "
3997 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
3998 j, track->mState, state->mTrackMask, recentUnderruns,
3999 track->sharedBuffer() != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004000 }
4001 tracksToRemove->add(track);
4002 // Avoids a misleading display in dumpsys
4003 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
4004 }
4005 continue;
4006 }
4007
4008 { // local variable scope to avoid goto warning
4009
4010 audio_track_cblk_t* cblk = track->cblk();
4011
4012 // The first time a track is added we wait
4013 // for all its buffers to be filled before processing it
4014 int name = track->name();
4015 // make sure that we have enough frames to mix one full buffer.
4016 // enforce this condition only once to enable draining the buffer in case the client
4017 // app does not call stop() and relies on underrun to stop:
4018 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
4019 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004020 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07004021 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004022 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004023
4024 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004025 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004026 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
4027 // add frames already consumed but not yet released by the resampler
4028 // because mAudioTrackServerProxy->framesReady() will include these frames
4029 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
4030
Eric Laurent81784c32012-11-19 14:55:58 -08004031 uint32_t minFrames = 1;
4032 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
4033 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004034 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08004035 }
Eric Laurent13e4c962013-12-20 17:36:01 -08004036
4037 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07004038 if (ATRACE_ENABLED()) {
4039 // I wish we had formatted trace names
4040 char traceName[16];
4041 strcpy(traceName, "nRdy");
4042 int name = track->name();
4043 if (AudioMixer::TRACK0 <= name &&
4044 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
4045 name -= AudioMixer::TRACK0;
4046 traceName[4] = (name / 10) + '0';
4047 traceName[5] = (name % 10) + '0';
4048 } else {
4049 traceName[4] = '?';
4050 traceName[5] = '?';
4051 }
4052 traceName[6] = '\0';
4053 ATRACE_INT(traceName, framesReady);
4054 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004055 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08004056 !track->isPaused() && !track->isTerminated())
4057 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004058 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004059
4060 mixedTracks++;
4061
Andy Hung69aed5f2014-02-25 17:24:40 -08004062 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
4063 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08004064 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08004065 if (track->mainBuffer() != mSinkBuffer &&
4066 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004067 if (mEffectBufferEnabled) {
4068 mEffectBufferValid = true; // Later can set directly.
4069 }
Eric Laurent81784c32012-11-19 14:55:58 -08004070 chain = getEffectChain_l(track->sessionId());
4071 // Delegate volume control to effect in track effect chain if needed
4072 if (chain != 0) {
4073 tracksWithEffect++;
4074 } else {
4075 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
4076 "session %d",
4077 name, track->sessionId());
4078 }
4079 }
4080
4081
4082 int param = AudioMixer::VOLUME;
4083 if (track->mFillingUpStatus == Track::FS_FILLED) {
4084 // no ramp for the first volume setting
4085 track->mFillingUpStatus = Track::FS_ACTIVE;
4086 if (track->mState == TrackBase::RESUMING) {
4087 track->mState = TrackBase::ACTIVE;
4088 param = AudioMixer::RAMP_VOLUME;
4089 }
4090 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004091 // FIXME should not make a decision based on mServer
4092 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004093 // If the track is stopped before the first frame was mixed,
4094 // do not apply ramp
4095 param = AudioMixer::RAMP_VOLUME;
4096 }
4097
4098 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07004099 uint32_t vl, vr; // in U8.24 integer format
4100 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08004101 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07004102 vl = vr = 0;
4103 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08004104 if (track->isPausing()) {
4105 track->setPaused();
4106 }
4107 } else {
4108
4109 // read original volumes with volume control
4110 float typeVolume = mStreamTypes[track->streamType()].volume;
4111 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004112 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004113 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07004114 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
4115 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08004116 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07004117 if (vlf > GAIN_FLOAT_UNITY) {
4118 ALOGV("Track left volume out of range: %.3g", vlf);
4119 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004120 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07004121 if (vrf > GAIN_FLOAT_UNITY) {
4122 ALOGV("Track right volume out of range: %.3g", vrf);
4123 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004124 }
4125 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07004126 vlf *= v;
4127 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08004128 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07004129 // then derive vl and vr as U8.24 versions for the effect chain
4130 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
4131 vl = (uint32_t) (scaleto8_24 * vlf);
4132 vr = (uint32_t) (scaleto8_24 * vrf);
4133 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08004134 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08004135 // send level comes from shared memory and so may be corrupt
4136 if (sendLevel > MAX_GAIN_INT) {
4137 ALOGV("Track send level out of range: %04X", sendLevel);
4138 sendLevel = MAX_GAIN_INT;
4139 }
Andy Hung6be49402014-05-30 10:42:03 -07004140 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4141 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08004142 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004143
Eric Laurent81784c32012-11-19 14:55:58 -08004144 // Delegate volume control to effect in track effect chain if needed
4145 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4146 // Do not ramp volume if volume is controlled by effect
4147 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08004148 // Update remaining floating point volume levels
4149 vlf = (float)vl / (1 << 24);
4150 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004151 track->mHasVolumeController = true;
4152 } else {
4153 // force no volume ramp when volume controller was just disabled or removed
4154 // from effect chain to avoid volume spike
4155 if (track->mHasVolumeController) {
4156 param = AudioMixer::VOLUME;
4157 }
4158 track->mHasVolumeController = false;
4159 }
4160
Eric Laurent81784c32012-11-19 14:55:58 -08004161 // XXX: these things DON'T need to be done each time
4162 mAudioMixer->setBufferProvider(name, track);
4163 mAudioMixer->enable(name);
4164
Andy Hung6be49402014-05-30 10:42:03 -07004165 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
4166 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
4167 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004168 mAudioMixer->setParameter(
4169 name,
4170 AudioMixer::TRACK,
4171 AudioMixer::FORMAT, (void *)track->format());
4172 mAudioMixer->setParameter(
4173 name,
4174 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004175 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004176 mAudioMixer->setParameter(
4177 name,
4178 AudioMixer::TRACK,
4179 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004180 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004181 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004182 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004183 if (reqSampleRate == 0) {
4184 reqSampleRate = mSampleRate;
4185 } else if (reqSampleRate > maxSampleRate) {
4186 reqSampleRate = maxSampleRate;
4187 }
Eric Laurent81784c32012-11-19 14:55:58 -08004188 mAudioMixer->setParameter(
4189 name,
4190 AudioMixer::RESAMPLE,
4191 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004192 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004193
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004194 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004195 mAudioMixer->setParameter(
4196 name,
4197 AudioMixer::TIMESTRETCH,
4198 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004199 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004200
Andy Hung69aed5f2014-02-25 17:24:40 -08004201 /*
4202 * Select the appropriate output buffer for the track.
4203 *
Andy Hung98ef9782014-03-04 14:46:50 -08004204 * Tracks with effects go into their own effects chain buffer
4205 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004206 *
4207 * Other tracks can use mMixerBuffer for higher precision
4208 * channel accumulation. If this buffer is enabled
4209 * (mMixerBufferEnabled true), then selected tracks will accumulate
4210 * into it.
4211 *
4212 */
4213 if (mMixerBufferEnabled
4214 && (track->mainBuffer() == mSinkBuffer
4215 || track->mainBuffer() == mMixerBuffer)) {
4216 mAudioMixer->setParameter(
4217 name,
4218 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004219 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004220 mAudioMixer->setParameter(
4221 name,
4222 AudioMixer::TRACK,
4223 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4224 // TODO: override track->mainBuffer()?
4225 mMixerBufferValid = true;
4226 } else {
4227 mAudioMixer->setParameter(
4228 name,
4229 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004230 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004231 mAudioMixer->setParameter(
4232 name,
4233 AudioMixer::TRACK,
4234 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4235 }
Eric Laurent81784c32012-11-19 14:55:58 -08004236 mAudioMixer->setParameter(
4237 name,
4238 AudioMixer::TRACK,
4239 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4240
4241 // reset retry count
4242 track->mRetryCount = kMaxTrackRetries;
4243
4244 // If one track is ready, set the mixer ready if:
4245 // - the mixer was not ready during previous round OR
4246 // - no other track is not ready
4247 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4248 mixerStatus != MIXER_TRACKS_ENABLED) {
4249 mixerStatus = MIXER_TRACKS_READY;
4250 }
4251 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004252 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hung08fb1742015-05-31 23:22:10 -07004253 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)",
4254 track, framesReady, desiredFrames);
Glenn Kasten82aaf942013-07-17 16:05:07 -07004255 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08004256 } else {
4257 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004258 }
Phil Burk2812d9e2016-01-04 10:34:30 -08004259
Eric Laurent81784c32012-11-19 14:55:58 -08004260 // clear effect chain input buffer if an active track underruns to avoid sending
4261 // previous audio buffer again to effects
4262 chain = getEffectChain_l(track->sessionId());
4263 if (chain != 0) {
4264 chain->clearInputBuffer();
4265 }
4266
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004267 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004268 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4269 track->isStopped() || track->isPaused()) {
4270 // We have consumed all the buffers of this track.
4271 // Remove it from the list of active tracks.
4272 // TODO: use actual buffer filling status instead of latency when available from
4273 // audio HAL
4274 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004275 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004276 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4277 if (track->isStopped()) {
4278 track->reset();
4279 }
4280 tracksToRemove->add(track);
4281 }
4282 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004283 // No buffers for this track. Give it a few chances to
4284 // fill a buffer, then remove it from active list.
4285 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004286 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004287 tracksToRemove->add(track);
4288 // indicate to client process that the track was disabled because of underrun;
4289 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004290 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004291 // If one track is not ready, mark the mixer also not ready if:
4292 // - the mixer was ready during previous round OR
4293 // - no other track is ready
4294 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4295 mixerStatus != MIXER_TRACKS_READY) {
4296 mixerStatus = MIXER_TRACKS_ENABLED;
4297 }
4298 }
4299 mAudioMixer->disable(name);
4300 }
4301
4302 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08004303
4304 }
4305
4306 // Push the new FastMixer state if necessary
4307 bool pauseAudioWatchdog = false;
4308 if (didModify) {
4309 state->mFastTracksGen++;
4310 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4311 if (kUseFastMixer == FastMixer_Dynamic &&
4312 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4313 state->mCommand = FastMixerState::COLD_IDLE;
4314 state->mColdFutexAddr = &mFastMixerFutex;
4315 state->mColdGen++;
4316 mFastMixerFutex = 0;
4317 if (kUseFastMixer == FastMixer_Dynamic) {
4318 mNormalSink = mOutputSink;
4319 }
4320 // If we go into cold idle, need to wait for acknowledgement
4321 // so that fast mixer stops doing I/O.
4322 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4323 pauseAudioWatchdog = true;
4324 }
Eric Laurent81784c32012-11-19 14:55:58 -08004325 }
4326 if (sq != NULL) {
4327 sq->end(didModify);
4328 sq->push(block);
4329 }
4330#ifdef AUDIO_WATCHDOG
4331 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4332 mAudioWatchdog->pause();
4333 }
4334#endif
4335
4336 // Now perform the deferred reset on fast tracks that have stopped
4337 while (resetMask != 0) {
4338 size_t i = __builtin_ctz(resetMask);
4339 ALOG_ASSERT(i < count);
4340 resetMask &= ~(1 << i);
4341 sp<Track> t = mActiveTracks[i].promote();
4342 if (t == 0) {
4343 continue;
4344 }
4345 Track* track = t.get();
4346 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4347 track->reset();
4348 }
4349
4350 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004351 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004352
Eric Laurent97d547d2014-09-02 14:45:53 -07004353 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4354 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004355 }
4356
4357 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004358 // as long as there are effects we should clear the effects buffer, to avoid
4359 // passing a non-clean buffer to the effect chain
4360 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004361 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004362 // sink or mix buffer must be cleared if all tracks are connected to an
4363 // effect chain as in this case the mixer will not write to the sink or mix buffer
4364 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004365 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4366 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004367 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004368 if (mMixerBufferValid) {
4369 memset(mMixerBuffer, 0, mMixerBufferSize);
4370 // TODO: In testing, mSinkBuffer below need not be cleared because
4371 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4372 // after mixing.
4373 //
4374 // To enforce this guarantee:
4375 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4376 // (mixedTracks == 0 && fastTracks > 0))
4377 // must imply MIXER_TRACKS_READY.
4378 // Later, we may clear buffers regardless, and skip much of this logic.
4379 }
Andy Hung98ef9782014-03-04 14:46:50 -08004380 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004381 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004382 }
4383
4384 // if any fast tracks, then status is ready
4385 mMixerStatusIgnoringFastTracks = mixerStatus;
4386 if (fastTracks > 0) {
4387 mixerStatus = MIXER_TRACKS_READY;
4388 }
4389 return mixerStatus;
4390}
4391
4392// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07004393int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
Glenn Kastend848eb42016-03-08 13:42:11 -08004394 audio_format_t format, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08004395{
Andy Hunge8a1ced2014-05-09 15:02:21 -07004396 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08004397}
4398
4399// deleteTrackName_l() must be called with ThreadBase::mLock held
4400void AudioFlinger::MixerThread::deleteTrackName_l(int name)
4401{
4402 ALOGV("remove track (%d) and delete from mixer", name);
4403 mAudioMixer->deleteTrackName(name);
4404}
4405
Eric Laurent10351942014-05-08 18:49:52 -07004406// checkForNewParameter_l() must be called with ThreadBase::mLock held
4407bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4408 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004409{
Eric Laurent81784c32012-11-19 14:55:58 -08004410 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08004411 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004412
Eric Laurent10351942014-05-08 18:49:52 -07004413 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004414
Glenn Kastenc05b8d72016-03-24 09:48:17 -07004415 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004416
Eric Laurent10351942014-05-08 18:49:52 -07004417 AudioParameter param = AudioParameter(keyValuePair);
4418 int value;
4419 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4420 reconfig = true;
4421 }
4422 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004423 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004424 status = BAD_VALUE;
4425 } else {
4426 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004427 reconfig = true;
4428 }
Eric Laurent10351942014-05-08 18:49:52 -07004429 }
4430 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004431 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004432 status = BAD_VALUE;
4433 } else {
4434 // no need to save value, since it's constant
4435 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004436 }
Eric Laurent10351942014-05-08 18:49:52 -07004437 }
4438 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4439 // do not accept frame count changes if tracks are open as the track buffer
4440 // size depends on frame count and correct behavior would not be guaranteed
4441 // if frame count is changed after track creation
4442 if (!mTracks.isEmpty()) {
4443 status = INVALID_OPERATION;
4444 } else {
4445 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004446 }
Eric Laurent10351942014-05-08 18:49:52 -07004447 }
4448 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004449#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004450 // when changing the audio output device, call addBatteryData to notify
4451 // the change
4452 if (mOutDevice != value) {
4453 uint32_t params = 0;
4454 // check whether speaker is on
4455 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4456 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004457 }
Eric Laurent10351942014-05-08 18:49:52 -07004458
4459 audio_devices_t deviceWithoutSpeaker
4460 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4461 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07004462 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07004463 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4464 }
4465
4466 if (params != 0) {
4467 addBatteryData(params);
4468 }
4469 }
Eric Laurent81784c32012-11-19 14:55:58 -08004470#endif
4471
Eric Laurent10351942014-05-08 18:49:52 -07004472 // forward device change to effects that have requested to be
4473 // aware of attached audio device.
4474 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08004475 a2dpDeviceChanged =
4476 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07004477 mOutDevice = value;
4478 for (size_t i = 0; i < mEffectChains.size(); i++) {
4479 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004480 }
4481 }
Eric Laurent10351942014-05-08 18:49:52 -07004482 }
Eric Laurent81784c32012-11-19 14:55:58 -08004483
Eric Laurent10351942014-05-08 18:49:52 -07004484 if (status == NO_ERROR) {
4485 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4486 keyValuePair.string());
4487 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004488 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004489 mStandby = true;
4490 mBytesWritten = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004491 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Eric Laurent10351942014-05-08 18:49:52 -07004492 keyValuePair.string());
Eric Laurent81784c32012-11-19 14:55:58 -08004493 }
Eric Laurent10351942014-05-08 18:49:52 -07004494 if (status == NO_ERROR && reconfig) {
4495 readOutputParameters_l();
4496 delete mAudioMixer;
4497 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4498 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004499 int name = getTrackName_l(mTracks[i]->mChannelMask,
4500 mTracks[i]->mFormat, mTracks[i]->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07004501 if (name < 0) {
4502 break;
4503 }
4504 mTracks[i]->mName = name;
4505 }
Eric Laurent73e26b62015-04-27 16:55:58 -07004506 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004507 }
Eric Laurent81784c32012-11-19 14:55:58 -08004508 }
4509
Eric Laurent42537be2016-01-08 17:16:42 -08004510 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08004511}
4512
4513
4514void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4515{
Eric Laurent81784c32012-11-19 14:55:58 -08004516 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07004517 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Elliott Hughes87cebad2014-05-22 10:14:43 -07004518 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Andy Hung2ddee192015-12-18 17:34:44 -08004519 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent81784c32012-11-19 14:55:58 -08004520
4521 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten2f90c512015-12-02 11:40:09 -08004522 // while we are dumping it. It may be inconsistent, but it won't mutate!
4523 // This is a large object so we place it on the heap.
4524 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
4525 const FastMixerDumpState *copy = new FastMixerDumpState(mFastMixerDumpState);
4526 copy->dump(fd);
4527 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08004528
4529#ifdef STATE_QUEUE_DUMP
4530 // Similar for state queue
4531 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4532 observerCopy.dump(fd);
4533 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4534 mutatorCopy.dump(fd);
4535#endif
4536
Glenn Kasten46909e72013-02-26 09:20:22 -08004537#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004538 // Write the tee output to a .wav file
4539 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08004540#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004541
4542#ifdef AUDIO_WATCHDOG
4543 if (mAudioWatchdog != 0) {
4544 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4545 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4546 wdCopy.dump(fd);
4547 }
4548#endif
4549}
4550
4551uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4552{
4553 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4554}
4555
4556uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4557{
4558 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4559}
4560
4561void AudioFlinger::MixerThread::cacheParameters_l()
4562{
4563 PlaybackThread::cacheParameters_l();
4564
4565 // FIXME: Relaxed timing because of a certain device that can't meet latency
4566 // Should be reduced to 2x after the vendor fixes the driver issue
4567 // increase threshold again due to low power audio mode. The way this warning
4568 // threshold is calculated and its usefulness should be reconsidered anyway.
4569 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4570}
4571
4572// ----------------------------------------------------------------------------
4573
4574AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent51716182016-02-29 18:00:56 -08004575 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady,
4576 uint32_t bitRate)
4577 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady, bitRate)
Eric Laurent81784c32012-11-19 14:55:58 -08004578 // mLeftVolFloat, mRightVolFloat
4579{
4580}
4581
Eric Laurentbfb1b832013-01-07 09:53:42 -08004582AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4583 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurent51716182016-02-29 18:00:56 -08004584 ThreadBase::type_t type, bool systemReady, uint32_t bitRate)
4585 : PlaybackThread(audioFlinger, output, id, device, type, systemReady, bitRate)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004586 // mLeftVolFloat, mRightVolFloat
4587{
4588}
4589
Eric Laurent81784c32012-11-19 14:55:58 -08004590AudioFlinger::DirectOutputThread::~DirectOutputThread()
4591{
4592}
4593
Eric Laurentbfb1b832013-01-07 09:53:42 -08004594void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
4595{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004596 float left, right;
4597
4598 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4599 left = right = 0;
4600 } else {
4601 float typeVolume = mStreamTypes[track->streamType()].volume;
4602 float v = mMasterVolume * typeVolume;
4603 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004604 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4605 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4606 if (left > GAIN_FLOAT_UNITY) {
4607 left = GAIN_FLOAT_UNITY;
4608 }
4609 left *= v;
4610 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4611 if (right > GAIN_FLOAT_UNITY) {
4612 right = GAIN_FLOAT_UNITY;
4613 }
4614 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004615 }
4616
4617 if (lastTrack) {
4618 if (left != mLeftVolFloat || right != mRightVolFloat) {
4619 mLeftVolFloat = left;
4620 mRightVolFloat = right;
4621
4622 // Convert volumes from float to 8.24
4623 uint32_t vl = (uint32_t)(left * (1 << 24));
4624 uint32_t vr = (uint32_t)(right * (1 << 24));
4625
4626 // Delegate volume control to effect in track effect chain if needed
4627 // only one effect chain can be present on DirectOutputThread, so if
4628 // there is one, the track is connected to it
4629 if (!mEffectChains.isEmpty()) {
4630 mEffectChains[0]->setVolume_l(&vl, &vr);
4631 left = (float)vl / (1 << 24);
4632 right = (float)vr / (1 << 24);
4633 }
4634 if (mOutput->stream->set_volume) {
4635 mOutput->stream->set_volume(mOutput->stream, left, right);
4636 }
4637 }
4638 }
4639}
4640
Phil Burk43b4dcc2015-06-09 16:53:44 -07004641void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
4642{
4643 sp<Track> previousTrack = mPreviousTrack.promote();
4644 sp<Track> latestTrack = mLatestActiveTrack.promote();
4645
Eric Laurent0f0631e2015-07-06 18:01:25 -07004646 if (previousTrack != 0 && latestTrack != 0) {
4647 if (mType == DIRECT) {
4648 if (previousTrack.get() != latestTrack.get()) {
4649 mFlushPending = true;
4650 }
4651 } else /* mType == OFFLOAD */ {
4652 if (previousTrack->sessionId() != latestTrack->sessionId()) {
4653 mFlushPending = true;
4654 }
4655 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004656 }
4657 PlaybackThread::onAddNewTrack_l();
4658}
Eric Laurentbfb1b832013-01-07 09:53:42 -08004659
Eric Laurent81784c32012-11-19 14:55:58 -08004660AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4661 Vector< sp<Track> > *tracksToRemove
4662)
4663{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004664 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004665 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004666 bool doHwPause = false;
4667 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004668
4669 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07004670 for (size_t i = 0; i < count; i++) {
4671 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08004672 // The track died recently
4673 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004674 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08004675 }
4676
Phil Burk43b4dcc2015-06-09 16:53:44 -07004677 if (t->isInvalid()) {
4678 ALOGW("An invalidated track shouldn't be in active list");
4679 tracksToRemove->add(t);
4680 continue;
4681 }
4682
Eric Laurent81784c32012-11-19 14:55:58 -08004683 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004684#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08004685 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004686#endif
Eric Laurentfd477972013-10-25 18:10:40 -07004687 // Only consider last track started for volume and mixer state control.
4688 // In theory an older track could underrun and restart after the new one starts
4689 // but as we only care about the transition phase between two tracks on a
4690 // direct output, it is not a problem to ignore the underrun case.
4691 sp<Track> l = mLatestActiveTrack.promote();
4692 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004693
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004694 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004695 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004696 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004697 doHwPause = true;
4698 mHwPaused = true;
4699 }
4700 tracksToRemove->add(track);
4701 } else if (track->isFlushPending()) {
4702 track->flushAck();
4703 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004704 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004705 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004706 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004707 track->resumeAck();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004708 if (last && mHwPaused) {
4709 doHwResume = true;
4710 mHwPaused = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004711 }
4712 }
4713
Eric Laurent81784c32012-11-19 14:55:58 -08004714 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004715 // for all its buffers to be filled before processing it.
4716 // Allow draining the buffer in case the client
4717 // app does not call stop() and relies on underrun to stop:
4718 // hence the test on (track->mRetryCount > 1).
4719 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07004720 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08004721 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004722 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08004723 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004724 minFrames = mNormalFrameCount;
4725 } else {
4726 minFrames = 1;
4727 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004728
Eric Laurentab5cdba2014-06-09 17:22:27 -07004729 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4730 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004731 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004732 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004733
4734 if (track->mFillingUpStatus == Track::FS_FILLED) {
4735 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004736 // make sure processVolume_l() will apply new volume even if 0
4737 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004738 if (!mHwSupportsPause) {
4739 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004740 }
4741 }
4742
4743 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004744 processVolume_l(track, last);
4745 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004746 sp<Track> previousTrack = mPreviousTrack.promote();
4747 if (previousTrack != 0) {
4748 if (track != previousTrack.get()) {
4749 // Flush any data still being written from last track
4750 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07004751 // Invalidate previous track to force a seek when resuming.
4752 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004753 }
4754 }
4755 mPreviousTrack = track;
4756
Eric Laurentd595b7c2013-04-03 17:27:56 -07004757 // reset retry count
4758 track->mRetryCount = kMaxTrackRetriesDirect;
4759 mActiveTrack = t;
4760 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07004761 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004762 doHwResume = true;
4763 mHwPaused = false;
4764 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004765 }
Eric Laurent81784c32012-11-19 14:55:58 -08004766 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004767 // clear effect chain input buffer if the last active track started underruns
4768 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004769 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004770 mEffectChains[0]->clearInputBuffer();
4771 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004772 if (track->isStopping_1()) {
4773 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07004774 if (last && mHwPaused) {
4775 doHwResume = true;
4776 mHwPaused = false;
4777 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004778 }
4779 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4780 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004781 // We have consumed all the buffers of this track.
4782 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004783 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08004784 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004785 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4786 } else {
4787 audioHALFrames = 0;
4788 }
4789
Andy Hung818e7a32016-02-16 18:08:07 -08004790 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004791 if (mStandby || !last ||
4792 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004793 if (track->isStopping_2()) {
4794 track->mState = TrackBase::STOPPED;
4795 }
Eric Laurent81784c32012-11-19 14:55:58 -08004796 if (track->isStopped()) {
4797 track->reset();
4798 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004799 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004800 }
4801 } else {
4802 // No buffers for this track. Give it a few chances to
4803 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004804 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004805 if (--(track->mRetryCount) <= 0) {
4806 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004807 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004808 // indicate to client process that the track was disabled because of underrun;
4809 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004810 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004811 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07004812 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
4813 "minFrames = %u, mFormat = %#x",
4814 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08004815 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07004816 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004817 doHwPause = true;
4818 mHwPaused = true;
4819 }
Eric Laurent81784c32012-11-19 14:55:58 -08004820 }
4821 }
4822 }
4823 }
4824
Eric Laurentd1f69b02014-12-15 14:33:13 -08004825 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07004826 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004827 for (size_t i = 0; i < mTracks.size(); i++) {
4828 if (mTracks[i]->isFlushPending()) {
4829 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004830 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004831 }
4832 }
4833 }
4834
4835 // make sure the pause/flush/resume sequence is executed in the right order.
4836 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4837 // before flush and then resume HW. This can happen in case of pause/flush/resume
4838 // if resume is received before pause is executed.
4839 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07004840 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004841 mOutput->stream->pause(mOutput->stream);
4842 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004843 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004844 flushHw_l();
4845 }
4846 if (mHwSupportsPause && !mStandby && doHwResume) {
4847 mOutput->stream->resume(mOutput->stream);
4848 }
Eric Laurent81784c32012-11-19 14:55:58 -08004849 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004850 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004851
4852 return mixerStatus;
4853}
4854
4855void AudioFlinger::DirectOutputThread::threadLoop_mix()
4856{
Eric Laurent81784c32012-11-19 14:55:58 -08004857 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08004858 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004859 // output audio to hardware
4860 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07004861 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004862 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08004863 status_t status = mActiveTrack->getNextBuffer(&buffer);
4864 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08004865 // no need to pad with 0 for compressed audio
4866 if (audio_has_proportional_frames(mFormat)) {
4867 memset(curBuf, 0, frameCount * mFrameSize);
4868 }
Eric Laurent81784c32012-11-19 14:55:58 -08004869 break;
4870 }
4871 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
4872 frameCount -= buffer.frameCount;
4873 curBuf += buffer.frameCount * mFrameSize;
4874 mActiveTrack->releaseBuffer(&buffer);
4875 }
Andy Hung2098f272014-02-27 14:00:06 -08004876 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004877 mSleepTimeUs = 0;
4878 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004879 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004880}
4881
4882void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
4883{
Eric Laurentd1f69b02014-12-15 14:33:13 -08004884 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004885 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004886 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004887 return;
4888 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004889 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004890 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurent51716182016-02-29 18:00:56 -08004891 // For compressed offload, use faster sleep time when underruning until more than an
4892 // entire buffer was written to the audio HAL
4893 if (!audio_has_proportional_frames(mFormat) &&
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004894 (mType == OFFLOAD) && (mBytesWritten < (int64_t) mBufferSize)) {
Eric Laurent51716182016-02-29 18:00:56 -08004895 mSleepTimeUs = kDirectMinSleepTimeUs;
4896 } else {
4897 mSleepTimeUs = mActiveSleepTimeUs;
4898 }
Eric Laurent81784c32012-11-19 14:55:58 -08004899 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004900 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004901 }
Phil Burkfdb3c072016-02-09 10:47:02 -08004902 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08004903 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004904 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004905 }
4906}
4907
Eric Laurentd1f69b02014-12-15 14:33:13 -08004908void AudioFlinger::DirectOutputThread::threadLoop_exit()
4909{
4910 {
4911 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08004912 for (size_t i = 0; i < mTracks.size(); i++) {
4913 if (mTracks[i]->isFlushPending()) {
4914 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004915 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004916 }
4917 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004918 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004919 flushHw_l();
4920 }
4921 }
4922 PlaybackThread::threadLoop_exit();
4923}
4924
4925// must be called with thread mutex locked
4926bool AudioFlinger::DirectOutputThread::shouldStandby_l()
4927{
4928 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07004929 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004930
vivek mehta9cd7ad12016-03-17 00:18:29 -07004931 if ((mType == DIRECT) && audio_is_linear_pcm(mFormat) && !usesHwAvSync()) {
4932 return !mStandby;
4933 }
4934
Eric Laurentd1f69b02014-12-15 14:33:13 -08004935 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4936 // after a timeout and we will enter standby then.
4937 if (mTracks.size() > 0) {
4938 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07004939 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
4940 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004941 }
4942
Eric Laurent5cff4032015-05-26 13:49:58 -07004943 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08004944}
4945
Eric Laurent81784c32012-11-19 14:55:58 -08004946// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004947int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Glenn Kastend848eb42016-03-08 13:42:11 -08004948 audio_format_t format __unused, audio_session_t sessionId __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004949{
4950 return 0;
4951}
4952
4953// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004954void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004955{
4956}
4957
Eric Laurent10351942014-05-08 18:49:52 -07004958// checkForNewParameter_l() must be called with ThreadBase::mLock held
4959bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
4960 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004961{
4962 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08004963 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004964
Eric Laurent10351942014-05-08 18:49:52 -07004965 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004966
Eric Laurent10351942014-05-08 18:49:52 -07004967 AudioParameter param = AudioParameter(keyValuePair);
4968 int value;
4969 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4970 // forward device change to effects that have requested to be
4971 // aware of attached audio device.
4972 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08004973 a2dpDeviceChanged =
4974 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07004975 mOutDevice = value;
4976 for (size_t i = 0; i < mEffectChains.size(); i++) {
4977 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07004978 }
4979 }
Eric Laurent81784c32012-11-19 14:55:58 -08004980 }
Eric Laurent10351942014-05-08 18:49:52 -07004981 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4982 // do not accept frame count changes if tracks are open as the track buffer
4983 // size depends on frame count and correct behavior would not be garantied
4984 // if frame count is changed after track creation
4985 if (!mTracks.isEmpty()) {
4986 status = INVALID_OPERATION;
4987 } else {
4988 reconfig = true;
4989 }
4990 }
4991 if (status == NO_ERROR) {
4992 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4993 keyValuePair.string());
4994 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004995 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004996 mStandby = true;
4997 mBytesWritten = 0;
4998 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4999 keyValuePair.string());
5000 }
5001 if (status == NO_ERROR && reconfig) {
5002 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07005003 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005004 }
5005 }
5006
Eric Laurent42537be2016-01-08 17:16:42 -08005007 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005008}
5009
5010uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
5011{
5012 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005013 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005014 time = PlaybackThread::activeSleepTimeUs();
5015 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005016 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005017 }
5018 return time;
5019}
5020
5021uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
5022{
5023 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005024 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005025 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
5026 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005027 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005028 }
5029 return time;
5030}
5031
5032uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
5033{
5034 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005035 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005036 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
5037 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005038 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005039 }
5040 return time;
5041}
5042
5043void AudioFlinger::DirectOutputThread::cacheParameters_l()
5044{
5045 PlaybackThread::cacheParameters_l();
5046
5047 // use shorter standby delay as on normal output to release
5048 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07005049 // no delay on outputs with HW A/V sync
5050 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005051 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08005052 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005053 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07005054 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005055 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07005056 }
Eric Laurent81784c32012-11-19 14:55:58 -08005057}
5058
Eric Laurente659ef42014-09-29 13:06:46 -07005059void AudioFlinger::DirectOutputThread::flushHw_l()
5060{
Phil Burk062e67a2015-02-11 13:40:50 -08005061 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08005062 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005063 mFlushPending = false;
Eric Laurente659ef42014-09-29 13:06:46 -07005064}
5065
Eric Laurent81784c32012-11-19 14:55:58 -08005066// ----------------------------------------------------------------------------
5067
Eric Laurentbfb1b832013-01-07 09:53:42 -08005068AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07005069 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005070 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07005071 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07005072 mWriteAckSequence(0),
5073 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005074{
5075}
5076
5077AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
5078{
5079}
5080
5081void AudioFlinger::AsyncCallbackThread::onFirstRef()
5082{
5083 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
5084}
5085
5086bool AudioFlinger::AsyncCallbackThread::threadLoop()
5087{
5088 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005089 uint32_t writeAckSequence;
5090 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005091
5092 {
5093 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005094 while (!((mWriteAckSequence & 1) ||
5095 (mDrainSequence & 1) ||
5096 exitPending())) {
5097 mWaitWorkCV.wait(mLock);
5098 }
5099
Eric Laurentbfb1b832013-01-07 09:53:42 -08005100 if (exitPending()) {
5101 break;
5102 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005103 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
5104 mWriteAckSequence, mDrainSequence);
5105 writeAckSequence = mWriteAckSequence;
5106 mWriteAckSequence &= ~1;
5107 drainSequence = mDrainSequence;
5108 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005109 }
5110 {
Eric Laurent4de95592013-09-26 15:28:21 -07005111 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
5112 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005113 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005114 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005115 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005116 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005117 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005118 }
5119 }
5120 }
5121 }
5122 return false;
5123}
5124
5125void AudioFlinger::AsyncCallbackThread::exit()
5126{
5127 ALOGV("AsyncCallbackThread::exit");
5128 Mutex::Autolock _l(mLock);
5129 requestExit();
5130 mWaitWorkCV.broadcast();
5131}
5132
Eric Laurent3b4529e2013-09-05 18:09:19 -07005133void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005134{
5135 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005136 // bit 0 is cleared
5137 mWriteAckSequence = sequence << 1;
5138}
5139
5140void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5141{
5142 Mutex::Autolock _l(mLock);
5143 // ignore unexpected callbacks
5144 if (mWriteAckSequence & 2) {
5145 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005146 mWaitWorkCV.signal();
5147 }
5148}
5149
Eric Laurent3b4529e2013-09-05 18:09:19 -07005150void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005151{
5152 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005153 // bit 0 is cleared
5154 mDrainSequence = sequence << 1;
5155}
5156
5157void AudioFlinger::AsyncCallbackThread::resetDraining()
5158{
5159 Mutex::Autolock _l(mLock);
5160 // ignore unexpected callbacks
5161 if (mDrainSequence & 2) {
5162 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005163 mWaitWorkCV.signal();
5164 }
5165}
5166
5167
5168// ----------------------------------------------------------------------------
5169AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent51716182016-02-29 18:00:56 -08005170 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady,
5171 uint32_t bitRate)
5172 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady, bitRate),
Eric Laurent64667972016-03-30 18:19:46 -07005173 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005174{
Eric Laurentfd477972013-10-25 18:10:40 -07005175 //FIXME: mStandby should be set to true by ThreadBase constructor
5176 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07005177 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005178}
5179
Eric Laurentbfb1b832013-01-07 09:53:42 -08005180void AudioFlinger::OffloadThread::threadLoop_exit()
5181{
5182 if (mFlushPending || mHwPaused) {
5183 // If a flush is pending or track was paused, just discard buffered data
5184 flushHw_l();
5185 } else {
5186 mMixerStatus = MIXER_DRAIN_ALL;
5187 threadLoop_drain();
5188 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005189 if (mUseAsyncWrite) {
5190 ALOG_ASSERT(mCallbackThread != 0);
5191 mCallbackThread->exit();
5192 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005193 PlaybackThread::threadLoop_exit();
5194}
5195
5196AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5197 Vector< sp<Track> > *tracksToRemove
5198)
5199{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005200 size_t count = mActiveTracks.size();
5201
5202 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005203 bool doHwPause = false;
5204 bool doHwResume = false;
5205
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005206 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07005207
Eric Laurentbfb1b832013-01-07 09:53:42 -08005208 // find out which tracks need to be processed
5209 for (size_t i = 0; i < count; i++) {
5210 sp<Track> t = mActiveTracks[i].promote();
5211 // The track died recently
5212 if (t == 0) {
5213 continue;
5214 }
5215 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005216#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08005217 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005218#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005219 // Only consider last track started for volume and mixer state control.
5220 // In theory an older track could underrun and restart after the new one starts
5221 // but as we only care about the transition phase between two tracks on a
5222 // direct output, it is not a problem to ignore the underrun case.
5223 sp<Track> l = mLatestActiveTrack.promote();
5224 bool last = l.get() == track;
5225
Haynes Mathew George7844f672014-01-15 12:32:55 -08005226 if (track->isInvalid()) {
5227 ALOGW("An invalidated track shouldn't be in active list");
5228 tracksToRemove->add(track);
5229 continue;
5230 }
5231
5232 if (track->mState == TrackBase::IDLE) {
5233 ALOGW("An idle track shouldn't be in active list");
5234 continue;
5235 }
5236
Eric Laurentbfb1b832013-01-07 09:53:42 -08005237 if (track->isPausing()) {
5238 track->setPaused();
5239 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005240 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005241 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005242 mHwPaused = true;
5243 }
5244 // If we were part way through writing the mixbuffer to
5245 // the HAL we must save this until we resume
5246 // BUG - this will be wrong if a different track is made active,
5247 // in that case we want to discard the pending data in the
5248 // mixbuffer and tell the client to present it again when the
5249 // track is resumed
5250 mPausedWriteLength = mCurrentWriteLength;
5251 mPausedBytesRemaining = mBytesRemaining;
5252 mBytesRemaining = 0; // stop writing
5253 }
5254 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005255 } else if (track->isFlushPending()) {
Eric Laurent51716182016-02-29 18:00:56 -08005256 track->mRetryCount = kMaxTrackRetriesOffload;
Haynes Mathew George7844f672014-01-15 12:32:55 -08005257 track->flushAck();
5258 if (last) {
5259 mFlushPending = true;
5260 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005261 } else if (track->isResumePending()){
5262 track->resumeAck();
5263 if (last) {
5264 if (mPausedBytesRemaining) {
5265 // Need to continue write that was interrupted
5266 mCurrentWriteLength = mPausedWriteLength;
5267 mBytesRemaining = mPausedBytesRemaining;
5268 mPausedBytesRemaining = 0;
5269 }
5270 if (mHwPaused) {
5271 doHwResume = true;
5272 mHwPaused = false;
5273 // threadLoop_mix() will handle the case that we need to
5274 // resume an interrupted write
5275 }
5276 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005277 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005278
5279 // Do not handle new data in this iteration even if track->framesReady()
5280 mixerStatus = MIXER_TRACKS_ENABLED;
5281 }
5282 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005283 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005284 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005285 if (track->mFillingUpStatus == Track::FS_FILLED) {
5286 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07005287 // make sure processVolume_l() will apply new volume even if 0
5288 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005289 }
5290
5291 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005292 sp<Track> previousTrack = mPreviousTrack.promote();
5293 if (previousTrack != 0) {
5294 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005295 // Flush any data still being written from last track
5296 mBytesRemaining = 0;
5297 if (mPausedBytesRemaining) {
5298 // Last track was paused so we also need to flush saved
5299 // mixbuffer state and invalidate track so that it will
5300 // re-submit that unwritten data when it is next resumed
5301 mPausedBytesRemaining = 0;
5302 // Invalidate is a bit drastic - would be more efficient
5303 // to have a flag to tell client that some of the
5304 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005305 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005306 }
5307 // flush data already sent to the DSP if changing audio session as audio
5308 // comes from a different source. Also invalidate previous track to force a
5309 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005310 if (previousTrack->sessionId() != track->sessionId()) {
5311 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005312 }
5313 }
5314 }
5315 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005316 // reset retry count
5317 track->mRetryCount = kMaxTrackRetriesOffload;
5318 mActiveTrack = t;
5319 mixerStatus = MIXER_TRACKS_READY;
5320 }
5321 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005322 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005323 if (track->isStopping_1()) {
5324 // Hardware buffer can hold a large amount of audio so we must
5325 // wait for all current track's data to drain before we say
5326 // that the track is stopped.
5327 if (mBytesRemaining == 0) {
5328 // Only start draining when all data in mixbuffer
5329 // has been written
5330 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5331 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005332 // do not drain if no data was ever sent to HAL (mStandby == true)
5333 if (last && !mStandby) {
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005334 // do not modify drain sequence if we are already draining. This happens
5335 // when resuming from pause after drain.
5336 if ((mDrainSequence & 1) == 0) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005337 mSleepTimeUs = 0;
5338 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005339 mixerStatus = MIXER_DRAIN_TRACK;
5340 mDrainSequence += 2;
5341 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005342 if (mHwPaused) {
5343 // It is possible to move from PAUSED to STOPPING_1 without
5344 // a resume so we must ensure hardware is running
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005345 doHwResume = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005346 mHwPaused = false;
5347 }
5348 }
5349 }
5350 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005351 // Drain has completed or we are in standby, signal presentation complete
5352 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005353 track->mState = TrackBase::STOPPED;
5354 size_t audioHALFrames =
5355 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005356 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005357 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005358 track->presentationComplete(framesWritten, audioHALFrames);
5359 track->reset();
5360 tracksToRemove->add(track);
5361 }
5362 } else {
5363 // No buffers for this track. Give it a few chances to
5364 // fill a buffer, then remove it from active list.
5365 if (--(track->mRetryCount) <= 0) {
5366 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5367 track->name());
5368 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005369 // indicate to client process that the track was disabled because of underrun;
5370 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005371 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005372 } else if (last){
5373 mixerStatus = MIXER_TRACKS_ENABLED;
5374 }
5375 }
5376 }
5377 // compute volume for this track
5378 processVolume_l(track, last);
5379 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005380
Eric Laurentea0fade2013-10-04 16:23:48 -07005381 // make sure the pause/flush/resume sequence is executed in the right order.
5382 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5383 // before flush and then resume HW. This can happen in case of pause/flush/resume
5384 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07005385 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07005386 mOutput->stream->pause(mOutput->stream);
5387 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005388 if (mFlushPending) {
5389 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005390 }
Eric Laurentfd477972013-10-25 18:10:40 -07005391 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07005392 mOutput->stream->resume(mOutput->stream);
5393 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005394
Eric Laurentbfb1b832013-01-07 09:53:42 -08005395 // remove all the tracks that need to be...
5396 removeTracks_l(*tracksToRemove);
5397
5398 return mixerStatus;
5399}
5400
Eric Laurentbfb1b832013-01-07 09:53:42 -08005401// must be called with thread mutex locked
5402bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5403{
Eric Laurent3b4529e2013-09-05 18:09:19 -07005404 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5405 mWriteAckSequence, mDrainSequence);
5406 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005407 return true;
5408 }
5409 return false;
5410}
5411
Eric Laurentbfb1b832013-01-07 09:53:42 -08005412bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5413{
5414 Mutex::Autolock _l(mLock);
5415 return waitingAsyncCallback_l();
5416}
5417
5418void AudioFlinger::OffloadThread::flushHw_l()
5419{
Eric Laurente659ef42014-09-29 13:06:46 -07005420 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005421 // Flush anything still waiting in the mixbuffer
5422 mCurrentWriteLength = 0;
5423 mBytesRemaining = 0;
5424 mPausedWriteLength = 0;
5425 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07005426 // reset bytes written count to reflect that DSP buffers are empty after flush.
5427 mBytesWritten = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08005428
Eric Laurentbfb1b832013-01-07 09:53:42 -08005429 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005430 // discard any pending drain or write ack by incrementing sequence
5431 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5432 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005433 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005434 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5435 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005436 }
5437}
5438
Eric Laurent51716182016-02-29 18:00:56 -08005439uint32_t AudioFlinger::OffloadThread::activeSleepTimeUs() const
5440{
5441 uint32_t time;
5442 if (audio_has_proportional_frames(mFormat)) {
5443 time = PlaybackThread::activeSleepTimeUs();
5444 } else {
5445 // sleep time is half the duration of an audio HAL buffer.
5446 // Note: This can be problematic in case of underrun with variable bit rate and
5447 // current rate is much less than initial rate.
5448 time = (uint32_t)max(kDirectMinSleepTimeUs, mBufferDurationUs / 2);
5449 }
5450 return time;
5451}
5452
Haynes Mathew George05317d22016-05-03 16:34:26 -07005453void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
5454{
5455 Mutex::Autolock _l(mLock);
5456 mFlushPending = true;
5457 PlaybackThread::invalidateTracks_l(streamType);
5458}
5459
Eric Laurentbfb1b832013-01-07 09:53:42 -08005460// ----------------------------------------------------------------------------
5461
Eric Laurent81784c32012-11-19 14:55:58 -08005462AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005463 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005464 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07005465 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08005466 mWaitTimeMs(UINT_MAX)
5467{
5468 addOutputTrack(mainThread);
5469}
5470
5471AudioFlinger::DuplicatingThread::~DuplicatingThread()
5472{
5473 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5474 mOutputTracks[i]->destroy();
5475 }
5476}
5477
5478void AudioFlinger::DuplicatingThread::threadLoop_mix()
5479{
5480 // mix buffers...
5481 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08005482 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08005483 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005484 if (mMixerBufferValid) {
5485 memset(mMixerBuffer, 0, mMixerBufferSize);
5486 } else {
5487 memset(mSinkBuffer, 0, mSinkBufferSize);
5488 }
Eric Laurent81784c32012-11-19 14:55:58 -08005489 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005490 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005491 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005492 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005493 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005494}
5495
5496void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5497{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005498 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005499 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005500 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005501 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005502 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005503 }
5504 } else if (mBytesWritten != 0) {
5505 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5506 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005507 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005508 } else {
5509 // flush remaining overflow buffers in output tracks
5510 writeFrames = 0;
5511 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005512 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005513 }
5514}
5515
Eric Laurentbfb1b832013-01-07 09:53:42 -08005516ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005517{
5518 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005519 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005520 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005521 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005522 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005523}
5524
5525void AudioFlinger::DuplicatingThread::threadLoop_standby()
5526{
5527 // DuplicatingThread implements standby by stopping all tracks
5528 for (size_t i = 0; i < outputTracks.size(); i++) {
5529 outputTracks[i]->stop();
5530 }
5531}
5532
5533void AudioFlinger::DuplicatingThread::saveOutputTracks()
5534{
5535 outputTracks = mOutputTracks;
5536}
5537
5538void AudioFlinger::DuplicatingThread::clearOutputTracks()
5539{
5540 outputTracks.clear();
5541}
5542
5543void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5544{
5545 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005546 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5547 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5548 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5549 const size_t frameCount =
5550 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5551 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5552 // from different OutputTracks and their associated MixerThreads (e.g. one may
5553 // nearly empty and the other may be dropping data).
5554
5555 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005556 this,
5557 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005558 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005559 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005560 frameCount,
5561 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08005562 if (outputTrack->cblk() != NULL) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005563 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
Eric Laurent81784c32012-11-19 14:55:58 -08005564 mOutputTracks.add(outputTrack);
Andy Hungc25b84a2015-01-14 19:04:10 -08005565 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005566 updateWaitTime_l();
5567 }
5568}
5569
5570void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5571{
5572 Mutex::Autolock _l(mLock);
5573 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5574 if (mOutputTracks[i]->thread() == thread) {
5575 mOutputTracks[i]->destroy();
5576 mOutputTracks.removeAt(i);
5577 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07005578 if (thread->getOutput() == mOutput) {
5579 mOutput = NULL;
5580 }
Eric Laurent81784c32012-11-19 14:55:58 -08005581 return;
5582 }
5583 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07005584 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005585}
5586
5587// caller must hold mLock
5588void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5589{
5590 mWaitTimeMs = UINT_MAX;
5591 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5592 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5593 if (strong != 0) {
5594 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5595 if (waitTimeMs < mWaitTimeMs) {
5596 mWaitTimeMs = waitTimeMs;
5597 }
5598 }
5599 }
5600}
5601
5602
5603bool AudioFlinger::DuplicatingThread::outputsReady(
5604 const SortedVector< sp<OutputTrack> > &outputTracks)
5605{
5606 for (size_t i = 0; i < outputTracks.size(); i++) {
5607 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5608 if (thread == 0) {
5609 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5610 outputTracks[i].get());
5611 return false;
5612 }
5613 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5614 // see note at standby() declaration
5615 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5616 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5617 thread.get());
5618 return false;
5619 }
5620 }
5621 return true;
5622}
5623
5624uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5625{
5626 return (mWaitTimeMs * 1000) / 2;
5627}
5628
5629void AudioFlinger::DuplicatingThread::cacheParameters_l()
5630{
5631 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5632 updateWaitTime_l();
5633
5634 MixerThread::cacheParameters_l();
5635}
5636
5637// ----------------------------------------------------------------------------
5638// Record
5639// ----------------------------------------------------------------------------
5640
5641AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5642 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005643 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005644 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07005645 audio_devices_t inDevice,
5646 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08005647#ifdef TEE_SINK
5648 , const sp<NBAIO_Sink>& teeSink
5649#endif
5650 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07005651 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005652 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005653 // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005654 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005655#ifdef TEE_SINK
5656 , mTeeSink(teeSink)
5657#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005658 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5659 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005660 // mFastCapture below
5661 , mFastCaptureFutex(0)
5662 // mInputSource
5663 // mPipeSink
5664 // mPipeSource
5665 , mPipeFramesP2(0)
5666 // mPipeMemory
5667 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005668 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005669{
Glenn Kastend7dca052015-03-05 16:05:54 -08005670 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5671 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08005672
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005673 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005674
5675 // create an NBAIO source for the HAL input stream, and negotiate
5676 mInputSource = new AudioStreamInSource(input->stream);
5677 size_t numCounterOffers = 0;
5678 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005679#if !LOG_NDEBUG
5680 ssize_t index =
5681#else
5682 (void)
5683#endif
5684 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005685 ALOG_ASSERT(index == 0);
5686
5687 // initialize fast capture depending on configuration
5688 bool initFastCapture;
5689 switch (kUseFastCapture) {
5690 case FastCapture_Never:
5691 initFastCapture = false;
5692 break;
5693 case FastCapture_Always:
5694 initFastCapture = true;
5695 break;
5696 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07005697 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005698 break;
5699 // case FastCapture_Dynamic:
5700 }
5701
5702 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07005703 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005704 NBAIO_Format format = mInputSource->format();
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005705 size_t pipeFramesP2 = roundup(mSampleRate / 25); // double-buffering of 20 ms each
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005706 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5707 void *pipeBuffer;
5708 const sp<MemoryDealer> roHeap(readOnlyHeap());
5709 sp<IMemory> pipeMemory;
5710 if ((roHeap == 0) ||
5711 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5712 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5713 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5714 goto failed;
5715 }
5716 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5717 memset(pipeBuffer, 0, pipeSize);
5718 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5719 const NBAIO_Format offers[1] = {format};
5720 size_t numCounterOffers = 0;
5721 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5722 ALOG_ASSERT(index == 0);
5723 mPipeSink = pipe;
5724 PipeReader *pipeReader = new PipeReader(*pipe);
5725 numCounterOffers = 0;
5726 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5727 ALOG_ASSERT(index == 0);
5728 mPipeSource = pipeReader;
5729 mPipeFramesP2 = pipeFramesP2;
5730 mPipeMemory = pipeMemory;
5731
5732 // create fast capture
5733 mFastCapture = new FastCapture();
5734 FastCaptureStateQueue *sq = mFastCapture->sq();
5735#ifdef STATE_QUEUE_DUMP
5736 // FIXME
5737#endif
5738 FastCaptureState *state = sq->begin();
5739 state->mCblk = NULL;
5740 state->mInputSource = mInputSource.get();
5741 state->mInputSourceGen++;
5742 state->mPipeSink = pipe;
5743 state->mPipeSinkGen++;
5744 state->mFrameCount = mFrameCount;
5745 state->mCommand = FastCaptureState::COLD_IDLE;
5746 // already done in constructor initialization list
5747 //mFastCaptureFutex = 0;
5748 state->mColdFutexAddr = &mFastCaptureFutex;
5749 state->mColdGen++;
5750 state->mDumpState = &mFastCaptureDumpState;
5751#ifdef TEE_SINK
5752 // FIXME
5753#endif
5754 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
5755 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
5756 sq->end();
5757 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5758
5759 // start the fast capture
5760 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
5761 pid_t tid = mFastCapture->getTid();
Glenn Kasten8379b722016-03-18 14:54:17 -07005762 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005763#ifdef AUDIO_WATCHDOG
5764 // FIXME
5765#endif
5766
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005767 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005768 }
5769failed: ;
5770
5771 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08005772}
5773
Eric Laurent81784c32012-11-19 14:55:58 -08005774AudioFlinger::RecordThread::~RecordThread()
5775{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005776 if (mFastCapture != 0) {
5777 FastCaptureStateQueue *sq = mFastCapture->sq();
5778 FastCaptureState *state = sq->begin();
5779 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5780 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5781 if (old == -1) {
5782 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5783 }
5784 }
5785 state->mCommand = FastCaptureState::EXIT;
5786 sq->end();
5787 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5788 mFastCapture->join();
5789 mFastCapture.clear();
5790 }
5791 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07005792 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07005793 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08005794}
5795
5796void AudioFlinger::RecordThread::onFirstRef()
5797{
Glenn Kastend7dca052015-03-05 16:05:54 -08005798 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08005799}
5800
Eric Laurent81784c32012-11-19 14:55:58 -08005801bool AudioFlinger::RecordThread::threadLoop()
5802{
Eric Laurent81784c32012-11-19 14:55:58 -08005803 nsecs_t lastWarning = 0;
5804
5805 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08005806
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005807reacquire_wakelock:
5808 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08005809 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005810 {
5811 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005812 size_t size = mActiveTracks.size();
5813 activeTracksGen = mActiveTracksGen;
5814 if (size > 0) {
5815 // FIXME an arbitrary choice
5816 activeTrack = mActiveTracks[0];
5817 acquireWakeLock_l(activeTrack->uid());
5818 if (size > 1) {
5819 SortedVector<int> tmp;
5820 for (size_t i = 0; i < size; i++) {
5821 tmp.add(mActiveTracks[i]->uid());
5822 }
5823 updateWakeLockUids_l(tmp);
5824 }
5825 } else {
5826 acquireWakeLock_l(-1);
5827 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005828 }
5829
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005830 // used to request a deferred sleep, to be executed later while mutex is unlocked
5831 uint32_t sleepUs = 0;
5832
5833 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005834 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005835 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07005836
Glenn Kasten5edadd42013-08-14 16:30:49 -07005837 // sleep with mutex unlocked
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005838 if (sleepUs > 0) {
Glenn Kastene7754022014-10-31 12:11:26 -07005839 ATRACE_BEGIN("sleep");
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005840 usleep(sleepUs);
Glenn Kastene7754022014-10-31 12:11:26 -07005841 ATRACE_END();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005842 sleepUs = 0;
Glenn Kasten5edadd42013-08-14 16:30:49 -07005843 }
5844
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005845 // activeTracks accumulates a copy of a subset of mActiveTracks
5846 Vector< sp<RecordTrack> > activeTracks;
5847
Glenn Kasten735f45f2014-08-18 15:51:59 -07005848 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005849 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07005850
Glenn Kasten735f45f2014-08-18 15:51:59 -07005851 // reference to a fast track which is about to be removed
5852 sp<RecordTrack> fastTrackToRemove;
5853
Eric Laurent81784c32012-11-19 14:55:58 -08005854 { // scope for mLock
5855 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08005856
Eric Laurent021cf962014-05-13 10:18:14 -07005857 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005858
Eric Laurent000a4192014-01-29 15:17:32 -08005859 // check exitPending here because checkForNewParameters_l() and
5860 // checkForNewParameters_l() can temporarily release mLock
5861 if (exitPending()) {
5862 break;
5863 }
5864
Glenn Kasten2b806402013-11-20 16:37:38 -08005865 // if no active track(s), then standby and release wakelock
5866 size_t size = mActiveTracks.size();
5867 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07005868 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005869 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08005870 releaseWakeLock_l();
5871 ALOGV("RecordThread: loop stopping");
5872 // go to sleep
5873 mWaitWorkCV.wait(mLock);
5874 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005875 goto reacquire_wakelock;
5876 }
5877
Glenn Kasten2b806402013-11-20 16:37:38 -08005878 if (mActiveTracksGen != activeTracksGen) {
5879 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005880 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08005881 for (size_t i = 0; i < size; i++) {
5882 tmp.add(mActiveTracks[i]->uid());
5883 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005884 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08005885 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005886
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005887 bool doBroadcast = false;
5888 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07005889
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005890 activeTrack = mActiveTracks[i];
5891 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07005892 if (activeTrack->isFastTrack()) {
5893 ALOG_ASSERT(fastTrackToRemove == 0);
5894 fastTrackToRemove = activeTrack;
5895 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005896 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08005897 mActiveTracks.remove(activeTrack);
5898 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005899 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07005900 continue;
5901 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005902
5903 TrackBase::track_state activeTrackState = activeTrack->mState;
5904 switch (activeTrackState) {
5905
5906 case TrackBase::PAUSING:
5907 mActiveTracks.remove(activeTrack);
5908 mActiveTracksGen++;
5909 doBroadcast = true;
5910 size--;
5911 continue;
5912
5913 case TrackBase::STARTING_1:
5914 sleepUs = 10000;
5915 i++;
5916 continue;
5917
5918 case TrackBase::STARTING_2:
5919 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005920 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07005921 activeTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005922 break;
5923
5924 case TrackBase::ACTIVE:
5925 break;
5926
5927 case TrackBase::IDLE:
5928 i++;
5929 continue;
5930
5931 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08005932 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07005933 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005934
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005935 activeTracks.add(activeTrack);
5936 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07005937
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005938 if (activeTrack->isFastTrack()) {
5939 ALOG_ASSERT(!mFastTrackAvail);
5940 ALOG_ASSERT(fastTrack == 0);
5941 fastTrack = activeTrack;
5942 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005943 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005944 if (doBroadcast) {
5945 mStartStopCond.broadcast();
5946 }
5947
5948 // sleep if there are no active tracks to process
5949 if (activeTracks.size() == 0) {
5950 if (sleepUs == 0) {
5951 sleepUs = kRecordThreadSleepUs;
5952 }
5953 continue;
5954 }
5955 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07005956
Eric Laurent81784c32012-11-19 14:55:58 -08005957 lockEffectChains_l(effectChains);
5958 }
5959
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005960 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07005961
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005962 size_t size = effectChains.size();
5963 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005964 // thread mutex is not locked, but effect chain is locked
5965 effectChains[i]->process_l();
5966 }
5967
Glenn Kasten735f45f2014-08-18 15:51:59 -07005968 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005969 if (mFastCapture != 0) {
5970 FastCaptureStateQueue *sq = mFastCapture->sq();
5971 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07005972 bool didModify = false;
5973 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005974 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
5975 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
5976 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5977 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5978 if (old == -1) {
5979 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5980 }
5981 }
5982 state->mCommand = FastCaptureState::READ_WRITE;
5983#if 0 // FIXME
5984 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08005985 FastThreadDumpState::kSamplingNforLowRamDevice :
5986 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005987#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07005988 didModify = true;
5989 }
5990 audio_track_cblk_t *cblkOld = state->mCblk;
5991 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
5992 if (cblkNew != cblkOld) {
5993 state->mCblk = cblkNew;
5994 // block until acked if removing a fast track
5995 if (cblkOld != NULL) {
5996 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
5997 }
5998 didModify = true;
5999 }
6000 sq->end(didModify);
6001 if (didModify) {
6002 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006003#if 0
6004 if (kUseFastCapture == FastCapture_Dynamic) {
6005 mNormalSource = mPipeSource;
6006 }
6007#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006008 }
6009 }
6010
Glenn Kasten735f45f2014-08-18 15:51:59 -07006011 // now run the fast track destructor with thread mutex unlocked
6012 fastTrackToRemove.clear();
6013
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006014 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
6015 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
6016 // slow, then this RecordThread will overrun by not calling HAL read often enough.
6017 // If destination is non-contiguous, first read past the nominal end of buffer, then
6018 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006019
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006020 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006021 ssize_t framesRead;
6022
6023 // If an NBAIO source is present, use it to read the normal capture's data
6024 if (mPipeSource != 0) {
6025 size_t framesToRead = mBufferSize / mFrameSize;
Andy Hung57446612015-04-19 23:56:46 -07006026 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
Glenn Kastend79072e2016-01-06 08:41:20 -08006027 framesToRead);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006028 if (framesRead == 0) {
6029 // since pipe is non-blocking, simulate blocking input
6030 sleepUs = (framesToRead * 1000000LL) / mSampleRate;
6031 }
6032 // otherwise use the HAL / AudioStreamIn directly
6033 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07006034 ATRACE_BEGIN("read");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006035 ssize_t bytesRead = mInput->stream->read(mInput->stream,
Andy Hung57446612015-04-19 23:56:46 -07006036 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize);
Glenn Kastenec6a7032016-03-14 07:40:23 -07006037 ATRACE_END();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006038 if (bytesRead < 0) {
6039 framesRead = bytesRead;
6040 } else {
6041 framesRead = bytesRead / mFrameSize;
6042 }
6043 }
6044
Andy Hung3f0c9022016-01-15 17:49:46 -08006045 // Update server timestamp with server stats
6046 // systemTime() is optional if the hardware supports timestamps.
6047 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
6048 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6049
6050 // Update server timestamp with kernel stats
6051 if (mInput->stream->get_capture_position != nullptr) {
6052 int64_t position, time;
6053 int ret = mInput->stream->get_capture_position(mInput->stream, &position, &time);
6054 if (ret == NO_ERROR) {
6055 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
6056 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
6057 // Note: In general record buffers should tend to be empty in
6058 // a properly running pipeline.
6059 //
6060 // Also, it is not advantageous to call get_presentation_position during the read
6061 // as the read obtains a lock, preventing the timestamp call from executing.
6062 }
6063 }
6064 // Use this to track timestamp information
6065 // ALOGD("%s", mTimestamp.toString().c_str());
6066
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006067 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006068 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006069 // Force input into standby so that it tries to recover at next read attempt
6070 inputStandBy();
6071 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006072 }
6073 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006074 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006075 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006076 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006077
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006078 if (mTeeSink != 0) {
Andy Hung57446612015-04-19 23:56:46 -07006079 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006080 }
6081 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006082 {
6083 size_t part1 = mRsmpInFramesP2 - rear;
6084 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07006085 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006086 (framesRead - part1) * mFrameSize);
6087 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006088 }
6089 rear = mRsmpInRear += framesRead;
6090
6091 size = activeTracks.size();
6092 // loop over each active track
6093 for (size_t i = 0; i < size; i++) {
6094 activeTrack = activeTracks[i];
6095
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006096 // skip fast tracks, as those are handled directly by FastCapture
6097 if (activeTrack->isFastTrack()) {
6098 continue;
6099 }
6100
Andy Hung73c02e42015-03-29 01:13:58 -07006101 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07006102 // TODO: Update the activeTrack buffer converter in case of reconfigure.
6103
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006104 enum {
6105 OVERRUN_UNKNOWN,
6106 OVERRUN_TRUE,
6107 OVERRUN_FALSE
6108 } overrun = OVERRUN_UNKNOWN;
6109
6110 // loop over getNextBuffer to handle circular sink
6111 for (;;) {
6112
6113 activeTrack->mSink.frameCount = ~0;
6114 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
6115 size_t framesOut = activeTrack->mSink.frameCount;
6116 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
6117
Andy Hung73c02e42015-03-29 01:13:58 -07006118 // check available frames and handle overrun conditions
6119 // if the record track isn't draining fast enough.
6120 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006121 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07006122 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
6123 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006124 overrun = OVERRUN_TRUE;
6125 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006126 if (framesOut == 0 || framesIn == 0) {
6127 break;
6128 }
6129
Andy Hung6770c6f2015-04-07 13:43:36 -07006130 // Don't allow framesOut to be larger than what is possible with resampling
6131 // from framesIn.
6132 // This isn't strictly necessary but helps limit buffer resizing in
6133 // RecordBufferConverter. TODO: remove when no longer needed.
6134 framesOut = min(framesOut,
6135 destinationFramesPossible(
6136 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07006137 // process frames from the RecordThread buffer provider to the RecordTrack buffer
6138 framesOut = activeTrack->mRecordBufferConverter->convert(
6139 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006140
6141 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
6142 overrun = OVERRUN_FALSE;
6143 }
6144
6145 if (activeTrack->mFramesToDrop == 0) {
6146 if (framesOut > 0) {
6147 activeTrack->mSink.frameCount = framesOut;
6148 activeTrack->releaseBuffer(&activeTrack->mSink);
6149 }
6150 } else {
6151 // FIXME could do a partial drop of framesOut
6152 if (activeTrack->mFramesToDrop > 0) {
6153 activeTrack->mFramesToDrop -= framesOut;
6154 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006155 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006156 }
6157 } else {
6158 activeTrack->mFramesToDrop += framesOut;
6159 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
6160 activeTrack->mSyncStartEvent->isCancelled()) {
6161 ALOGW("Synced record %s, session %d, trigger session %d",
6162 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
6163 activeTrack->sessionId(),
6164 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08006165 activeTrack->mSyncStartEvent->triggerSession() :
6166 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006167 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006168 }
6169 }
6170 }
6171
6172 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006173 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006174 }
6175 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006176
6177 switch (overrun) {
6178 case OVERRUN_TRUE:
6179 // client isn't retrieving buffers fast enough
6180 if (!activeTrack->setOverflow()) {
6181 nsecs_t now = systemTime();
6182 // FIXME should lastWarning per track?
6183 if ((now - lastWarning) > kWarningThrottleNs) {
6184 ALOGW("RecordThread: buffer overflow");
6185 lastWarning = now;
6186 }
6187 }
6188 break;
6189 case OVERRUN_FALSE:
6190 activeTrack->clearOverflow();
6191 break;
6192 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006193 break;
6194 }
6195
Andy Hung3f0c9022016-01-15 17:49:46 -08006196 // update frame information and push timestamp out
6197 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08006198 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08006199 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
6200 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006201 }
6202
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006203unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08006204 // enable changes in effect chain
6205 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006206 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08006207 }
6208
Glenn Kasten93e471f2013-08-19 08:40:07 -07006209 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08006210
6211 {
6212 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07006213 for (size_t i = 0; i < mTracks.size(); i++) {
6214 sp<RecordTrack> track = mTracks[i];
6215 track->invalidate();
6216 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006217 mActiveTracks.clear();
6218 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08006219 mStartStopCond.broadcast();
6220 }
6221
6222 releaseWakeLock();
6223
6224 ALOGV("RecordThread %p exiting", this);
6225 return false;
6226}
6227
Glenn Kasten93e471f2013-08-19 08:40:07 -07006228void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08006229{
6230 if (!mStandby) {
6231 inputStandBy();
6232 mStandby = true;
6233 }
6234}
6235
6236void AudioFlinger::RecordThread::inputStandBy()
6237{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006238 // Idle the fast capture if it's currently running
6239 if (mFastCapture != 0) {
6240 FastCaptureStateQueue *sq = mFastCapture->sq();
6241 FastCaptureState *state = sq->begin();
6242 if (!(state->mCommand & FastCaptureState::IDLE)) {
6243 state->mCommand = FastCaptureState::COLD_IDLE;
6244 state->mColdFutexAddr = &mFastCaptureFutex;
6245 state->mColdGen++;
6246 mFastCaptureFutex = 0;
6247 sq->end();
6248 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
6249 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
6250#if 0
6251 if (kUseFastCapture == FastCapture_Dynamic) {
6252 // FIXME
6253 }
6254#endif
6255#ifdef AUDIO_WATCHDOG
6256 // FIXME
6257#endif
6258 } else {
6259 sq->end(false /*didModify*/);
6260 }
6261 }
Eric Laurent81784c32012-11-19 14:55:58 -08006262 mInput->stream->common.standby(&mInput->stream->common);
6263}
6264
Glenn Kasten05997e22014-03-13 15:08:33 -07006265// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07006266sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08006267 const sp<AudioFlinger::Client>& client,
6268 uint32_t sampleRate,
6269 audio_format_t format,
6270 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08006271 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08006272 audio_session_t sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07006273 size_t *notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006274 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07006275 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08006276 pid_t tid,
6277 status_t *status)
6278{
Glenn Kasten74935e42013-12-19 08:56:45 -08006279 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08006280 sp<RecordTrack> track;
6281 status_t lStatus;
6282
Glenn Kasten90e58b12013-07-31 16:16:02 -07006283 // client expresses a preference for FAST, but we get the final say
6284 if (*flags & IAudioFlinger::TRACK_FAST) {
6285 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07006286 // we formerly checked for a callback handler (non-0 tid),
6287 // but that is no longer required for TRANSFER_OBTAIN mode
6288 //
Glenn Kasten74105912014-07-03 12:28:53 -07006289 // frame count is not specified, or is exactly the pipe depth
6290 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006291 // PCM data
6292 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006293 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006294 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006295 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006296 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006297 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07006298 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006299 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006300 hasFastCapture() &&
6301 // there are sufficient fast track slots available
6302 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07006303 ) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006304 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
Glenn Kasten90e58b12013-07-31 16:16:02 -07006305 frameCount, mFrameCount);
6306 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006307 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
Glenn Kasten74105912014-07-03 12:28:53 -07006308 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006309 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07006310 frameCount, mFrameCount, mPipeFramesP2,
6311 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
6312 hasFastCapture(), tid, mFastTrackAvail);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006313 *flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kasten74105912014-07-03 12:28:53 -07006314 }
6315 }
6316
6317 // compute track buffer size in frames, and suggest the notification frame count
6318 if (*flags & IAudioFlinger::TRACK_FAST) {
6319 // fast track: frame count is exactly the pipe depth
6320 frameCount = mPipeFramesP2;
6321 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
6322 *notificationFrames = mFrameCount;
6323 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006324 // not fast track: max notification period is resampled equivalent of one HAL buffer time
6325 // or 20 ms if there is a fast capture
6326 // TODO This could be a roundupRatio inline, and const
6327 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
6328 * sampleRate + mSampleRate - 1) / mSampleRate;
6329 // minimum number of notification periods is at least kMinNotifications,
6330 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
6331 static const size_t kMinNotifications = 3;
6332 static const uint32_t kMinMs = 30;
6333 // TODO This could be a roundupRatio inline
6334 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
6335 // TODO This could be a roundupRatio inline
6336 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
6337 maxNotificationFrames;
6338 const size_t minFrameCount = maxNotificationFrames *
6339 max(kMinNotifications, minNotificationsByMs);
6340 frameCount = max(frameCount, minFrameCount);
6341 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
6342 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07006343 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07006344 }
Glenn Kasten74935e42013-12-19 08:56:45 -08006345 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07006346
Glenn Kasten15e57982013-09-24 11:52:37 -07006347 lStatus = initCheck();
6348 if (lStatus != NO_ERROR) {
6349 ALOGE("createRecordTrack_l() audio driver not initialized");
6350 goto Exit;
6351 }
Eric Laurent81784c32012-11-19 14:55:58 -08006352
6353 { // scope for mLock
6354 Mutex::Autolock _l(mLock);
6355
6356 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07006357 format, channelMask, frameCount, NULL, sessionId, uid,
6358 *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08006359
Glenn Kasten03003332013-08-06 15:40:54 -07006360 lStatus = track->initCheck();
6361 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07006362 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08006363 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08006364 goto Exit;
6365 }
6366 mTracks.add(track);
6367
6368 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6369 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6370 mAudioFlinger->btNrecIsOff();
6371 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6372 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006373
6374 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
6375 pid_t callingPid = IPCThreadState::self()->getCallingPid();
6376 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
6377 // so ask activity manager to do this on our behalf
6378 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
6379 }
Eric Laurent81784c32012-11-19 14:55:58 -08006380 }
Glenn Kasten05997e22014-03-13 15:08:33 -07006381
Eric Laurent81784c32012-11-19 14:55:58 -08006382 lStatus = NO_ERROR;
6383
6384Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07006385 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08006386 return track;
6387}
6388
6389status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6390 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08006391 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08006392{
6393 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6394 sp<ThreadBase> strongMe = this;
6395 status_t status = NO_ERROR;
6396
6397 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006398 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006399 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006400 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08006401 triggerSession,
6402 recordTrack->sessionId(),
6403 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006404 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08006405 // Sync event can be cancelled by the trigger session if the track is not in a
6406 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006407 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006408 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006409 } else {
6410 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006411 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006412 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08006413 }
6414 }
6415
6416 {
Glenn Kasten47c20702013-08-13 15:37:35 -07006417 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08006418 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006419 if (mActiveTracks.indexOf(recordTrack) >= 0) {
6420 if (recordTrack->mState == TrackBase::PAUSING) {
6421 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006422 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006423 } else {
6424 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08006425 }
6426 return status;
6427 }
6428
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006429 // TODO consider other ways of handling this, such as changing the state to :STARTING and
6430 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6431 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006432 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08006433 mActiveTracks.add(recordTrack);
6434 mActiveTracksGen++;
Eric Laurent83b88082014-06-20 18:31:16 -07006435 status_t status = NO_ERROR;
6436 if (recordTrack->isExternalTrack()) {
6437 mLock.unlock();
Glenn Kastend848eb42016-03-08 13:42:11 -08006438 status = AudioSystem::startInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006439 mLock.lock();
6440 // FIXME should verify that recordTrack is still in mActiveTracks
6441 if (status != NO_ERROR) {
6442 mActiveTracks.remove(recordTrack);
6443 mActiveTracksGen++;
6444 recordTrack->clearSyncStartEvent();
6445 ALOGV("RecordThread::start error %d", status);
6446 return status;
6447 }
Eric Laurent81784c32012-11-19 14:55:58 -08006448 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006449 // Catch up with current buffer indices if thread is already running.
6450 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
6451 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6452 // see previously buffered data before it called start(), but with greater risk of overrun.
6453
Andy Hung73c02e42015-03-29 01:13:58 -07006454 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07006455 // clear any converter state as new data will be discontinuous
6456 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006457 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08006458 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08006459 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08006460 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006461 ALOGV("Record failed to start");
6462 status = BAD_VALUE;
6463 goto startError;
6464 }
Eric Laurent81784c32012-11-19 14:55:58 -08006465 return status;
6466 }
Glenn Kasten7c027242012-12-26 14:43:16 -08006467
Eric Laurent81784c32012-11-19 14:55:58 -08006468startError:
Eric Laurent83b88082014-06-20 18:31:16 -07006469 if (recordTrack->isExternalTrack()) {
Glenn Kastend848eb42016-03-08 13:42:11 -08006470 AudioSystem::stopInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006471 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006472 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006473 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08006474 return status;
6475}
6476
Eric Laurent81784c32012-11-19 14:55:58 -08006477void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6478{
6479 sp<SyncEvent> strongEvent = event.promote();
6480
6481 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08006482 sp<RefBase> ptr = strongEvent->cookie().promote();
6483 if (ptr != 0) {
6484 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6485 recordTrack->handleSyncStartEvent(strongEvent);
6486 }
Eric Laurent81784c32012-11-19 14:55:58 -08006487 }
6488}
6489
Glenn Kastena8356f62013-07-25 14:37:52 -07006490bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08006491 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07006492 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006493 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08006494 return false;
6495 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006496 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006497 recordTrack->mState = TrackBase::PAUSING;
6498 // do not wait for mStartStopCond if exiting
6499 if (exitPending()) {
6500 return true;
6501 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006502 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08006503 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006504 // if we have been restarted, recordTrack is in mActiveTracks here
6505 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006506 ALOGV("Record stopped OK");
6507 return true;
6508 }
6509 return false;
6510}
6511
Glenn Kasten0f11b512014-01-31 16:18:54 -08006512bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08006513{
6514 return false;
6515}
6516
Glenn Kasten0f11b512014-01-31 16:18:54 -08006517status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006518{
6519#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6520 if (!isValidSyncEvent(event)) {
6521 return BAD_VALUE;
6522 }
6523
Glenn Kastend848eb42016-03-08 13:42:11 -08006524 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08006525 status_t ret = NAME_NOT_FOUND;
6526
6527 Mutex::Autolock _l(mLock);
6528
6529 for (size_t i = 0; i < mTracks.size(); i++) {
6530 sp<RecordTrack> track = mTracks[i];
6531 if (eventSession == track->sessionId()) {
6532 (void) track->setSyncEvent(event);
6533 ret = NO_ERROR;
6534 }
6535 }
6536 return ret;
6537#else
6538 return BAD_VALUE;
6539#endif
6540}
6541
6542// destroyTrack_l() must be called with ThreadBase::mLock held
6543void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6544{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006545 track->terminate();
6546 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006547 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006548 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006549 removeTrack_l(track);
6550 }
6551}
6552
6553void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6554{
6555 mTracks.remove(track);
6556 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006557 if (track->isFastTrack()) {
6558 ALOG_ASSERT(!mFastTrackAvail);
6559 mFastTrackAvail = true;
6560 }
Eric Laurent81784c32012-11-19 14:55:58 -08006561}
6562
6563void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6564{
6565 dumpInternals(fd, args);
6566 dumpTracks(fd, args);
6567 dumpEffectChains(fd, args);
6568}
6569
6570void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6571{
Elliott Hughes87cebad2014-05-22 10:14:43 -07006572 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08006573
Glenn Kasten44182c22015-03-05 17:12:23 -08006574 dumpBase(fd, args);
6575
6576 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006577 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006578 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006579 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006580 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08006581
Glenn Kasten2f90c512015-12-02 11:40:09 -08006582 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
6583 // while we are dumping it. It may be inconsistent, but it won't mutate!
6584 // This is a large object so we place it on the heap.
6585 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
6586 const FastCaptureDumpState *copy = new FastCaptureDumpState(mFastCaptureDumpState);
6587 copy->dump(fd);
6588 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08006589}
6590
Glenn Kasten0f11b512014-01-31 16:18:54 -08006591void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006592{
6593 const size_t SIZE = 256;
6594 char buffer[SIZE];
6595 String8 result;
6596
Marco Nelissenb2208842014-02-07 14:00:50 -08006597 size_t numtracks = mTracks.size();
6598 size_t numactive = mActiveTracks.size();
6599 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006600 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006601 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006602 dprintf(fd, " of which %zu are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006603 RecordTrack::appendDumpHeader(result);
6604 for (size_t i = 0; i < numtracks ; ++i) {
6605 sp<RecordTrack> track = mTracks[i];
6606 if (track != 0) {
6607 bool active = mActiveTracks.indexOf(track) >= 0;
6608 if (active) {
6609 numactiveseen++;
6610 }
6611 track->dump(buffer, SIZE, active);
6612 result.append(buffer);
6613 }
Eric Laurent81784c32012-11-19 14:55:58 -08006614 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006615 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006616 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006617 }
6618
Marco Nelissenb2208842014-02-07 14:00:50 -08006619 if (numactiveseen != numactive) {
6620 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6621 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006622 result.append(buffer);
6623 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006624 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006625 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006626 if (mTracks.indexOf(track) < 0) {
6627 track->dump(buffer, SIZE, true);
6628 result.append(buffer);
6629 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006630 }
Eric Laurent81784c32012-11-19 14:55:58 -08006631
6632 }
6633 write(fd, result.string(), result.size());
6634}
6635
Andy Hung73c02e42015-03-29 01:13:58 -07006636
6637void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
6638{
6639 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6640 RecordThread *recordThread = (RecordThread *) threadBase.get();
6641 mRsmpInFront = recordThread->mRsmpInRear;
6642 mRsmpInUnrel = 0;
6643}
6644
6645void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
6646 size_t *framesAvailable, bool *hasOverrun)
6647{
6648 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6649 RecordThread *recordThread = (RecordThread *) threadBase.get();
6650 const int32_t rear = recordThread->mRsmpInRear;
6651 const int32_t front = mRsmpInFront;
6652 const ssize_t filled = rear - front;
6653
6654 size_t framesIn;
6655 bool overrun = false;
6656 if (filled < 0) {
6657 // should not happen, but treat like a massive overrun and re-sync
6658 framesIn = 0;
6659 mRsmpInFront = rear;
6660 overrun = true;
6661 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
6662 framesIn = (size_t) filled;
6663 } else {
6664 // client is not keeping up with server, but give it latest data
6665 framesIn = recordThread->mRsmpInFrames;
6666 mRsmpInFront = /* front = */ rear - framesIn;
6667 overrun = true;
6668 }
6669 if (framesAvailable != NULL) {
6670 *framesAvailable = framesIn;
6671 }
6672 if (hasOverrun != NULL) {
6673 *hasOverrun = overrun;
6674 }
6675}
6676
Eric Laurent81784c32012-11-19 14:55:58 -08006677// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006678status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08006679 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006680{
Andy Hung73c02e42015-03-29 01:13:58 -07006681 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006682 if (threadBase == 0) {
6683 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006684 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006685 return NOT_ENOUGH_DATA;
6686 }
6687 RecordThread *recordThread = (RecordThread *) threadBase.get();
6688 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07006689 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07006690 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006691 // FIXME should not be P2 (don't want to increase latency)
6692 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006693 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07006694 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006695 front &= recordThread->mRsmpInFramesP2 - 1;
6696 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07006697 if (part1 > (size_t) filled) {
6698 part1 = filled;
6699 }
6700 size_t ask = buffer->frameCount;
6701 ALOG_ASSERT(ask > 0);
6702 if (part1 > ask) {
6703 part1 = ask;
6704 }
6705 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07006706 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07006707 buffer->raw = NULL;
6708 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07006709 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07006710 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08006711 }
6712
Andy Hung57446612015-04-19 23:56:46 -07006713 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07006714 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07006715 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08006716 return NO_ERROR;
6717}
6718
6719// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006720void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
6721 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006722{
Glenn Kasten85948432013-08-19 12:09:05 -07006723 size_t stepCount = buffer->frameCount;
6724 if (stepCount == 0) {
6725 return;
6726 }
Andy Hung73c02e42015-03-29 01:13:58 -07006727 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
6728 mRsmpInUnrel -= stepCount;
6729 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006730 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006731 buffer->frameCount = 0;
6732}
6733
Andy Hung97a893e2015-03-29 01:03:07 -07006734AudioFlinger::RecordThread::RecordBufferConverter::RecordBufferConverter(
6735 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6736 uint32_t srcSampleRate,
6737 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6738 uint32_t dstSampleRate) :
6739 mSrcChannelMask(AUDIO_CHANNEL_INVALID), // updateParameters will set following vars
6740 // mSrcFormat
6741 // mSrcSampleRate
6742 // mDstChannelMask
6743 // mDstFormat
6744 // mDstSampleRate
6745 // mSrcChannelCount
6746 // mDstChannelCount
6747 // mDstFrameSize
6748 mBuf(NULL), mBufFrames(0), mBufFrameSize(0),
Andy Hungd330ee42015-04-20 13:23:41 -07006749 mResampler(NULL),
6750 mIsLegacyDownmix(false),
6751 mIsLegacyUpmix(false),
6752 mRequiresFloat(false),
6753 mInputConverterProvider(NULL)
Andy Hung97a893e2015-03-29 01:03:07 -07006754{
6755 (void)updateParameters(srcChannelMask, srcFormat, srcSampleRate,
6756 dstChannelMask, dstFormat, dstSampleRate);
6757}
6758
6759AudioFlinger::RecordThread::RecordBufferConverter::~RecordBufferConverter() {
6760 free(mBuf);
6761 delete mResampler;
Andy Hungd330ee42015-04-20 13:23:41 -07006762 delete mInputConverterProvider;
Andy Hung97a893e2015-03-29 01:03:07 -07006763}
6764
6765size_t AudioFlinger::RecordThread::RecordBufferConverter::convert(void *dst,
6766 AudioBufferProvider *provider, size_t frames)
6767{
Andy Hungd330ee42015-04-20 13:23:41 -07006768 if (mInputConverterProvider != NULL) {
6769 mInputConverterProvider->setBufferProvider(provider);
6770 provider = mInputConverterProvider;
6771 }
6772
6773 if (mResampler == NULL) {
Andy Hung97a893e2015-03-29 01:03:07 -07006774 ALOGVV("NO RESAMPLING sampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6775 mSrcSampleRate, mSrcFormat, mDstFormat);
6776
6777 AudioBufferProvider::Buffer buffer;
6778 for (size_t i = frames; i > 0; ) {
6779 buffer.frameCount = i;
Glenn Kastend79072e2016-01-06 08:41:20 -08006780 status_t status = provider->getNextBuffer(&buffer);
Andy Hung97a893e2015-03-29 01:03:07 -07006781 if (status != OK || buffer.frameCount == 0) {
6782 frames -= i; // cannot fill request.
6783 break;
6784 }
Andy Hungd330ee42015-04-20 13:23:41 -07006785 // format convert to destination buffer
6786 convertNoResampler(dst, buffer.raw, buffer.frameCount);
Andy Hung97a893e2015-03-29 01:03:07 -07006787
6788 dst = (int8_t*)dst + buffer.frameCount * mDstFrameSize;
6789 i -= buffer.frameCount;
6790 provider->releaseBuffer(&buffer);
6791 }
6792 } else {
6793 ALOGVV("RESAMPLING mSrcSampleRate:%u mDstSampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6794 mSrcSampleRate, mDstSampleRate, mSrcFormat, mDstFormat);
6795
Andy Hungd330ee42015-04-20 13:23:41 -07006796 // reallocate buffer if needed
6797 if (mBufFrameSize != 0 && mBufFrames < frames) {
6798 free(mBuf);
6799 mBufFrames = frames;
6800 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6801 }
Andy Hung97a893e2015-03-29 01:03:07 -07006802 // resampler accumulates, but we only have one source track
Andy Hungd330ee42015-04-20 13:23:41 -07006803 memset(mBuf, 0, frames * mBufFrameSize);
6804 frames = mResampler->resample((int32_t*)mBuf, frames, provider);
6805 // format convert to destination buffer
6806 convertResampler(dst, mBuf, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006807 }
6808 return frames;
6809}
6810
6811status_t AudioFlinger::RecordThread::RecordBufferConverter::updateParameters(
6812 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6813 uint32_t srcSampleRate,
6814 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6815 uint32_t dstSampleRate)
6816{
6817 // quick evaluation if there is any change.
6818 if (mSrcFormat == srcFormat
6819 && mSrcChannelMask == srcChannelMask
6820 && mSrcSampleRate == srcSampleRate
6821 && mDstFormat == dstFormat
6822 && mDstChannelMask == dstChannelMask
6823 && mDstSampleRate == dstSampleRate) {
6824 return NO_ERROR;
6825 }
6826
Andy Hungdb4c0312015-05-06 08:46:52 -07006827 ALOGV("RecordBufferConverter updateParameters srcMask:%#x dstMask:%#x"
6828 " srcFormat:%#x dstFormat:%#x srcRate:%u dstRate:%u",
6829 srcChannelMask, dstChannelMask, srcFormat, dstFormat, srcSampleRate, dstSampleRate);
Andy Hung97a893e2015-03-29 01:03:07 -07006830 const bool valid =
6831 audio_is_input_channel(srcChannelMask)
6832 && audio_is_input_channel(dstChannelMask)
6833 && audio_is_valid_format(srcFormat) && audio_is_linear_pcm(srcFormat)
6834 && audio_is_valid_format(dstFormat) && audio_is_linear_pcm(dstFormat)
6835 && (srcSampleRate <= dstSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX)
6836 ; // no upsampling checks for now
6837 if (!valid) {
6838 return BAD_VALUE;
6839 }
6840
6841 mSrcFormat = srcFormat;
6842 mSrcChannelMask = srcChannelMask;
6843 mSrcSampleRate = srcSampleRate;
6844 mDstFormat = dstFormat;
6845 mDstChannelMask = dstChannelMask;
6846 mDstSampleRate = dstSampleRate;
6847
6848 // compute derived parameters
6849 mSrcChannelCount = audio_channel_count_from_in_mask(srcChannelMask);
6850 mDstChannelCount = audio_channel_count_from_in_mask(dstChannelMask);
6851 mDstFrameSize = mDstChannelCount * audio_bytes_per_sample(mDstFormat);
6852
Andy Hungd330ee42015-04-20 13:23:41 -07006853 // do we need to resample?
6854 delete mResampler;
6855 mResampler = NULL;
6856 if (mSrcSampleRate != mDstSampleRate) {
6857 mResampler = AudioResampler::create(AUDIO_FORMAT_PCM_FLOAT,
6858 mSrcChannelCount, mDstSampleRate);
6859 mResampler->setSampleRate(mSrcSampleRate);
6860 mResampler->setVolume(AudioMixer::UNITY_GAIN_FLOAT, AudioMixer::UNITY_GAIN_FLOAT);
6861 }
6862
6863 // are we running legacy channel conversion modes?
6864 mIsLegacyDownmix = (mSrcChannelMask == AUDIO_CHANNEL_IN_STEREO
6865 || mSrcChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK)
6866 && mDstChannelMask == AUDIO_CHANNEL_IN_MONO;
6867 mIsLegacyUpmix = mSrcChannelMask == AUDIO_CHANNEL_IN_MONO
6868 && (mDstChannelMask == AUDIO_CHANNEL_IN_STEREO
6869 || mDstChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK);
6870
6871 // do we need to process in float?
6872 mRequiresFloat = mResampler != NULL || mIsLegacyDownmix || mIsLegacyUpmix;
6873
6874 // do we need a staging buffer to convert for destination (we can still optimize this)?
6875 // we use mBufFrameSize > 0 to indicate both frame size as well as buffer necessity
6876 if (mResampler != NULL) {
6877 mBufFrameSize = max(mSrcChannelCount, FCC_2)
6878 * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
Andy Hunga97630b2015-07-22 23:27:24 -07006879 } else if (mIsLegacyUpmix || mIsLegacyDownmix) { // legacy modes always float
Andy Hungd330ee42015-04-20 13:23:41 -07006880 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
6881 } else if (mSrcChannelMask != mDstChannelMask && mDstFormat != mSrcFormat) {
Andy Hung97a893e2015-03-29 01:03:07 -07006882 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(mSrcFormat);
6883 } else {
6884 mBufFrameSize = 0;
6885 }
6886 mBufFrames = 0; // force the buffer to be resized.
6887
Andy Hungd330ee42015-04-20 13:23:41 -07006888 // do we need an input converter buffer provider to give us float?
6889 delete mInputConverterProvider;
6890 mInputConverterProvider = NULL;
6891 if (mRequiresFloat && mSrcFormat != AUDIO_FORMAT_PCM_FLOAT) {
6892 mInputConverterProvider = new ReformatBufferProvider(
6893 audio_channel_count_from_in_mask(mSrcChannelMask),
6894 mSrcFormat,
6895 AUDIO_FORMAT_PCM_FLOAT,
6896 256 /* provider buffer frame count */);
6897 }
6898
6899 // do we need a remixer to do channel mask conversion
6900 if (!mIsLegacyDownmix && !mIsLegacyUpmix && mSrcChannelMask != mDstChannelMask) {
6901 (void) memcpy_by_index_array_initialization_from_channel_mask(
6902 mIdxAry, ARRAY_SIZE(mIdxAry), mDstChannelMask, mSrcChannelMask);
Andy Hung97a893e2015-03-29 01:03:07 -07006903 }
6904 return NO_ERROR;
6905}
6906
Andy Hungd330ee42015-04-20 13:23:41 -07006907void AudioFlinger::RecordThread::RecordBufferConverter::convertNoResampler(
6908 void *dst, const void *src, size_t frames)
Andy Hung97a893e2015-03-29 01:03:07 -07006909{
Andy Hungd330ee42015-04-20 13:23:41 -07006910 // src is native type unless there is legacy upmix or downmix, whereupon it is float.
Andy Hung97a893e2015-03-29 01:03:07 -07006911 if (mBufFrameSize != 0 && mBufFrames < frames) {
6912 free(mBuf);
6913 mBufFrames = frames;
6914 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6915 }
Andy Hungd330ee42015-04-20 13:23:41 -07006916 // do we need to do legacy upmix and downmix?
6917 if (mIsLegacyUpmix || mIsLegacyDownmix) {
Andy Hung97a893e2015-03-29 01:03:07 -07006918 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07006919 if (mIsLegacyUpmix) {
6920 upmix_to_stereo_float_from_mono_float((float *)dstBuf,
6921 (const float *)src, frames);
6922 } else /*mIsLegacyDownmix */ {
6923 downmix_to_mono_float_from_stereo_float((float *)dstBuf,
6924 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006925 }
Andy Hungd330ee42015-04-20 13:23:41 -07006926 if (mBuf != NULL) {
6927 memcpy_by_audio_format(dst, mDstFormat, mBuf, AUDIO_FORMAT_PCM_FLOAT,
6928 frames * mDstChannelCount);
6929 }
6930 return;
6931 }
6932 // do we need to do channel mask conversion?
6933 if (mSrcChannelMask != mDstChannelMask) {
Andy Hung97a893e2015-03-29 01:03:07 -07006934 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07006935 memcpy_by_index_array(dstBuf, mDstChannelCount,
6936 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mSrcFormat), frames);
6937 if (dstBuf == dst) {
6938 return; // format is the same
6939 }
6940 }
6941 // convert to destination buffer
6942 const void *convertBuf = mBuf != NULL ? mBuf : src;
6943 memcpy_by_audio_format(dst, mDstFormat, convertBuf, mSrcFormat,
6944 frames * mDstChannelCount);
6945}
6946
6947void AudioFlinger::RecordThread::RecordBufferConverter::convertResampler(
6948 void *dst, /*not-a-const*/ void *src, size_t frames)
6949{
6950 // src buffer format is ALWAYS float when entering this routine
6951 if (mIsLegacyUpmix) {
6952 ; // mono to stereo already handled by resampler
6953 } else if (mIsLegacyDownmix
6954 || (mSrcChannelMask == mDstChannelMask && mSrcChannelCount == 1)) {
6955 // the resampler outputs stereo for mono input channel (a feature?)
6956 // must convert to mono
6957 downmix_to_mono_float_from_stereo_float((float *)src,
6958 (const float *)src, frames);
6959 } else if (mSrcChannelMask != mDstChannelMask) {
6960 // convert to mono channel again for channel mask conversion (could be skipped
6961 // with further optimization).
Andy Hung97a893e2015-03-29 01:03:07 -07006962 if (mSrcChannelCount == 1) {
Andy Hungd330ee42015-04-20 13:23:41 -07006963 downmix_to_mono_float_from_stereo_float((float *)src,
6964 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006965 }
Andy Hungd330ee42015-04-20 13:23:41 -07006966 // convert to destination format (in place, OK as float is larger than other types)
6967 if (mDstFormat != AUDIO_FORMAT_PCM_FLOAT) {
6968 memcpy_by_audio_format(src, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
6969 frames * mSrcChannelCount);
6970 }
6971 // channel convert and save to dst
6972 memcpy_by_index_array(dst, mDstChannelCount,
6973 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mDstFormat), frames);
6974 return;
Andy Hung97a893e2015-03-29 01:03:07 -07006975 }
Andy Hungd330ee42015-04-20 13:23:41 -07006976 // convert to destination format and save to dst
6977 memcpy_by_audio_format(dst, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
6978 frames * mDstChannelCount);
Andy Hung97a893e2015-03-29 01:03:07 -07006979}
6980
Eric Laurent10351942014-05-08 18:49:52 -07006981bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
6982 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006983{
6984 bool reconfig = false;
6985
Eric Laurent10351942014-05-08 18:49:52 -07006986 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006987
Eric Laurent10351942014-05-08 18:49:52 -07006988 audio_format_t reqFormat = mFormat;
6989 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07006990 // 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 -07006991 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
6992
6993 AudioParameter param = AudioParameter(keyValuePair);
6994 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07006995
6996 // scope for AutoPark extends to end of method
6997 AutoPark<FastCapture> park(mFastCapture);
6998
Eric Laurent10351942014-05-08 18:49:52 -07006999 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
7000 // channel count change can be requested. Do we mandate the first client defines the
7001 // HAL sampling rate and channel count or do we allow changes on the fly?
7002 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
7003 samplingRate = value;
7004 reconfig = true;
7005 }
7006 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07007007 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07007008 status = BAD_VALUE;
7009 } else {
7010 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08007011 reconfig = true;
7012 }
Eric Laurent10351942014-05-08 18:49:52 -07007013 }
7014 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
7015 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07007016 if (!audio_is_input_channel(mask) ||
7017 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007018 status = BAD_VALUE;
7019 } else {
7020 channelMask = mask;
7021 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007022 }
Eric Laurent10351942014-05-08 18:49:52 -07007023 }
7024 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7025 // do not accept frame count changes if tracks are open as the track buffer
7026 // size depends on frame count and correct behavior would not be guaranteed
7027 // if frame count is changed after track creation
7028 if (mActiveTracks.size() > 0) {
7029 status = INVALID_OPERATION;
7030 } else {
7031 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007032 }
Eric Laurent10351942014-05-08 18:49:52 -07007033 }
7034 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7035 // forward device change to effects that have requested to be
7036 // aware of attached audio device.
7037 for (size_t i = 0; i < mEffectChains.size(); i++) {
7038 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08007039 }
Eric Laurent81784c32012-11-19 14:55:58 -08007040
Eric Laurent10351942014-05-08 18:49:52 -07007041 // store input device and output device but do not forward output device to audio HAL.
7042 // Note that status is ignored by the caller for output device
7043 // (see AudioFlinger::setParameters()
7044 if (audio_is_output_devices(value)) {
7045 mOutDevice = value;
7046 status = BAD_VALUE;
7047 } else {
7048 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07007049 if (value != AUDIO_DEVICE_NONE) {
7050 mPrevInDevice = value;
7051 }
Eric Laurent10351942014-05-08 18:49:52 -07007052 // disable AEC and NS if the device is a BT SCO headset supporting those
7053 // pre processings
7054 if (mTracks.size() > 0) {
7055 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7056 mAudioFlinger->btNrecIsOff();
7057 for (size_t i = 0; i < mTracks.size(); i++) {
7058 sp<RecordTrack> track = mTracks[i];
7059 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7060 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08007061 }
7062 }
7063 }
Eric Laurent10351942014-05-08 18:49:52 -07007064 }
7065 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
7066 mAudioSource != (audio_source_t)value) {
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]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08007071 }
Eric Laurent10351942014-05-08 18:49:52 -07007072 mAudioSource = (audio_source_t)value;
7073 }
Glenn Kastene198c362013-08-13 09:13:36 -07007074
Eric Laurent10351942014-05-08 18:49:52 -07007075 if (status == NO_ERROR) {
7076 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7077 keyValuePair.string());
7078 if (status == INVALID_OPERATION) {
7079 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08007080 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7081 keyValuePair.string());
Eric Laurent10351942014-05-08 18:49:52 -07007082 }
7083 if (reconfig) {
7084 if (status == BAD_VALUE &&
Andy Hung97a893e2015-03-29 01:03:07 -07007085 audio_is_linear_pcm(mInput->stream->common.get_format(&mInput->stream->common)) &&
7086 audio_is_linear_pcm(reqFormat) &&
Eric Laurent10351942014-05-08 18:49:52 -07007087 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
Andy Hung97a893e2015-03-29 01:03:07 -07007088 <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate)) &&
Andy Hunge5412692014-05-16 11:25:07 -07007089 audio_channel_count_from_in_mask(
Andy Hungd1abb8f2015-05-05 23:42:34 -07007090 mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007091 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007092 }
Eric Laurent10351942014-05-08 18:49:52 -07007093 if (status == NO_ERROR) {
7094 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007095 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08007096 }
7097 }
Eric Laurent81784c32012-11-19 14:55:58 -08007098 }
Eric Laurent10351942014-05-08 18:49:52 -07007099
Eric Laurent81784c32012-11-19 14:55:58 -08007100 return reconfig;
7101}
7102
7103String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
7104{
Eric Laurent81784c32012-11-19 14:55:58 -08007105 Mutex::Autolock _l(mLock);
7106 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07007107 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08007108 }
7109
Glenn Kastend8ea6992013-07-16 14:17:15 -07007110 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
7111 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08007112 free(s);
7113 return out_s8;
7114}
7115
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007116void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007117 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7118
7119 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08007120
7121 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007122 case AUDIO_INPUT_OPENED:
7123 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07007124 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07007125 desc->mChannelMask = mChannelMask;
7126 desc->mSamplingRate = mSampleRate;
7127 desc->mFormat = mFormat;
7128 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07007129 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07007130 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007131 break;
7132
Eric Laurent73e26b62015-04-27 16:55:58 -07007133 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08007134 default:
7135 break;
7136 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007137 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08007138}
7139
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007140void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007141{
Eric Laurent81784c32012-11-19 14:55:58 -08007142 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
7143 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Andy Hunge5412692014-05-16 11:25:07 -07007144 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Andy Hungd330ee42015-04-20 13:23:41 -07007145 if (mChannelCount > FCC_8) {
7146 ALOGE("HAL channel count %d > %d", mChannelCount, FCC_8);
7147 }
Andy Hung463be252014-07-10 16:56:07 -07007148 mHALFormat = mInput->stream->common.get_format(&mInput->stream->common);
7149 mFormat = mHALFormat;
Andy Hungd330ee42015-04-20 13:23:41 -07007150 if (!audio_is_linear_pcm(mFormat)) {
7151 ALOGE("HAL format %#x is not linear pcm", mFormat);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07007152 }
Eric Laurent665470b2014-07-03 16:37:08 -07007153 mFrameSize = audio_stream_in_frame_size(mInput->stream);
Glenn Kasten548efc92012-11-29 08:48:51 -08007154 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
7155 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007156 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08007157 // 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 -07007158 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08007159 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007160 // A larger value should allow more old data to be read after a track calls start(),
7161 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07007162 //
7163 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08007164 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07007165 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07007166 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07007167 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007168
7169 // TODO optimize audio capture buffer sizes ...
7170 // Here we calculate the size of the sliding buffer used as a source
7171 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
7172 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
7173 // be better to have it derived from the pipe depth in the long term.
7174 // The current value is higher than necessary. However it should not add to latency.
7175
Glenn Kasten85948432013-08-19 12:09:05 -07007176 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Andy Hung0a01c2f2015-09-21 12:44:54 -07007177 size_t bufferSize = (mRsmpInFramesP2 + mFrameCount - 1) * mFrameSize;
7178 (void)posix_memalign(&mRsmpInBuffer, 32, bufferSize);
7179 memset(mRsmpInBuffer, 0, bufferSize); // if posix_memalign fails, will segv here.
Eric Laurent81784c32012-11-19 14:55:58 -08007180
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007181 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
7182 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08007183}
7184
Glenn Kasten5f972c02014-01-13 09:59:31 -08007185uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08007186{
7187 Mutex::Autolock _l(mLock);
7188 if (initCheck() != NO_ERROR) {
7189 return 0;
7190 }
7191
7192 return mInput->stream->get_input_frames_lost(mInput->stream);
7193}
7194
Glenn Kastend848eb42016-03-08 13:42:11 -08007195uint32_t AudioFlinger::RecordThread::hasAudioSession(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08007196{
7197 Mutex::Autolock _l(mLock);
7198 uint32_t result = 0;
7199 if (getEffectChain_l(sessionId) != 0) {
7200 result = EFFECT_SESSION;
7201 }
7202
7203 for (size_t i = 0; i < mTracks.size(); ++i) {
7204 if (sessionId == mTracks[i]->sessionId()) {
7205 result |= TRACK_SESSION;
7206 break;
7207 }
7208 }
7209
7210 return result;
7211}
7212
Glenn Kastend848eb42016-03-08 13:42:11 -08007213KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08007214{
Glenn Kastend848eb42016-03-08 13:42:11 -08007215 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08007216 Mutex::Autolock _l(mLock);
7217 for (size_t j = 0; j < mTracks.size(); ++j) {
7218 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08007219 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08007220 if (ids.indexOfKey(sessionId) < 0) {
7221 ids.add(sessionId, true);
7222 }
7223 }
7224 return ids;
7225}
7226
7227AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7228{
7229 Mutex::Autolock _l(mLock);
7230 AudioStreamIn *input = mInput;
7231 mInput = NULL;
7232 return input;
7233}
7234
7235// this method must always be called either with ThreadBase mLock held or inside the thread loop
7236audio_stream_t* AudioFlinger::RecordThread::stream() const
7237{
7238 if (mInput == NULL) {
7239 return NULL;
7240 }
7241 return &mInput->stream->common;
7242}
7243
7244status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7245{
7246 // only one chain per input thread
7247 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07007248 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08007249 return INVALID_OPERATION;
7250 }
7251 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07007252 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08007253 chain->setInBuffer(NULL);
7254 chain->setOutBuffer(NULL);
7255
7256 checkSuspendOnAddEffectChain_l(chain);
7257
Eric Laurent1b928682014-10-02 19:41:47 -07007258 // make sure enabled pre processing effects state is communicated to the HAL as we
7259 // just moved them to a new input stream.
7260 chain->syncHalEffectsState();
7261
Eric Laurent81784c32012-11-19 14:55:58 -08007262 mEffectChains.add(chain);
7263
7264 return NO_ERROR;
7265}
7266
7267size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7268{
7269 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7270 ALOGW_IF(mEffectChains.size() != 1,
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007271 "removeEffectChain_l() %p invalid chain size %zu on thread %p",
Eric Laurent81784c32012-11-19 14:55:58 -08007272 chain.get(), mEffectChains.size(), this);
7273 if (mEffectChains.size() == 1) {
7274 mEffectChains.removeAt(0);
7275 }
7276 return 0;
7277}
7278
Eric Laurent1c333e22014-05-20 10:48:17 -07007279status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7280 audio_patch_handle_t *handle)
7281{
7282 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007283
7284 // store new device and send to effects
7285 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07007286 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07007287 for (size_t i = 0; i < mEffectChains.size(); i++) {
7288 mEffectChains[i]->setDevice_l(mInDevice);
7289 }
7290
7291 // disable AEC and NS if the device is a BT SCO headset supporting those
7292 // pre processings
7293 if (mTracks.size() > 0) {
7294 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7295 mAudioFlinger->btNrecIsOff();
7296 for (size_t i = 0; i < mTracks.size(); i++) {
7297 sp<RecordTrack> track = mTracks[i];
7298 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7299 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
7300 }
7301 }
7302
7303 // store new source and send to effects
7304 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7305 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07007306 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07007307 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07007308 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007309 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007310
Eric Laurent054d9d32015-04-24 08:48:48 -07007311 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007312 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
7313 status = hwDevice->create_audio_patch(hwDevice,
7314 patch->num_sources,
7315 patch->sources,
7316 patch->num_sinks,
7317 patch->sinks,
7318 handle);
7319 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007320 char *address;
7321 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7322 address = audio_device_address_to_parameter(
7323 patch->sources[0].ext.device.type,
7324 patch->sources[0].ext.device.address);
7325 } else {
7326 address = (char *)calloc(1, 1);
7327 }
7328 AudioParameter param = AudioParameter(String8(address));
7329 free(address);
7330 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING),
7331 (int)patch->sources[0].ext.device.type);
7332 param.addInt(String8(AUDIO_PARAMETER_STREAM_INPUT_SOURCE),
7333 (int)patch->sinks[0].ext.mix.usecase.source);
7334 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7335 param.toString().string());
7336 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07007337 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007338
Eric Laurente8726fe2015-06-26 09:39:24 -07007339 if (mInDevice != mPrevInDevice) {
7340 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7341 mPrevInDevice = mInDevice;
7342 }
Eric Laurent296fb132015-05-01 11:38:42 -07007343
Eric Laurent1c333e22014-05-20 10:48:17 -07007344 return status;
7345}
7346
7347status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7348{
7349 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007350
7351 mInDevice = AUDIO_DEVICE_NONE;
7352
Eric Laurent1c333e22014-05-20 10:48:17 -07007353 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
7354 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
7355 status = hwDevice->release_audio_patch(hwDevice, handle);
7356 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007357 AudioParameter param;
7358 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
7359 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7360 param.toString().string());
Eric Laurent1c333e22014-05-20 10:48:17 -07007361 }
7362 return status;
7363}
7364
Eric Laurent83b88082014-06-20 18:31:16 -07007365void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
7366{
7367 Mutex::Autolock _l(mLock);
7368 mTracks.add(record);
7369}
7370
7371void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
7372{
7373 Mutex::Autolock _l(mLock);
7374 destroyTrack_l(record);
7375}
7376
7377void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
7378{
7379 ThreadBase::getAudioPortConfig(config);
7380 config->role = AUDIO_PORT_ROLE_SINK;
7381 config->ext.mix.hw_module = mInput->audioHwDev->handle();
7382 config->ext.mix.usecase.source = mAudioSource;
7383}
Eric Laurent1c333e22014-05-20 10:48:17 -07007384
Glenn Kasten63238ef2015-03-02 15:50:29 -08007385} // namespace android