blob: 08834d8c821aad8ec1af3598e3266a98675937a8 [file] [log] [blame]
Eric Laurent81784c32012-11-19 14:55:58 -08001/*
2**
3** Copyright 2012, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
Alex Ray371eb972012-11-30 11:11:54 -080021#define ATRACE_TAG ATRACE_TAG_AUDIO
Eric Laurent81784c32012-11-19 14:55:58 -080022
Glenn Kasten153b9fe2013-07-15 11:23:36 -070023#include "Configuration.h"
Eric Laurent81784c32012-11-19 14:55:58 -080024#include <math.h>
25#include <fcntl.h>
Glenn Kastenad8510a2015-02-17 16:24:07 -080026#include <linux/futex.h>
Eric Laurent81784c32012-11-19 14:55:58 -080027#include <sys/stat.h>
Glenn Kastenad8510a2015-02-17 16:24:07 -080028#include <sys/syscall.h>
Eric Laurent81784c32012-11-19 14:55:58 -080029#include <cutils/properties.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070030#include <media/AudioParameter.h>
Andy Hungcd044842014-08-07 11:04:34 -070031#include <media/AudioResamplerPublic.h>
Eric Laurent81784c32012-11-19 14:55:58 -080032#include <utils/Log.h>
Alex Ray371eb972012-11-30 11:11:54 -080033#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080034
35#include <private/media/AudioTrackShared.h>
36#include <hardware/audio.h>
37#include <audio_effects/effect_ns.h>
38#include <audio_effects/effect_aec.h>
Andy Hung2ddee192015-12-18 17:34:44 -080039#include <audio_utils/conversion.h>
Eric Laurent81784c32012-11-19 14:55:58 -080040#include <audio_utils/primitives.h>
Andy Hung98ef9782014-03-04 14:46:50 -080041#include <audio_utils/format.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070042#include <audio_utils/minifloat.h>
Eric Laurent81784c32012-11-19 14:55:58 -080043
44// NBAIO implementations
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070045#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080046#include <media/nbaio/AudioStreamOutSink.h>
47#include <media/nbaio/MonoPipe.h>
48#include <media/nbaio/MonoPipeReader.h>
49#include <media/nbaio/Pipe.h>
50#include <media/nbaio/PipeReader.h>
51#include <media/nbaio/SourceAudioBufferProvider.h>
Wei Jia3f273d12015-11-24 09:06:49 -080052#include <mediautils/BatteryNotifier.h>
Eric Laurent81784c32012-11-19 14:55:58 -080053
54#include <powermanager/PowerManager.h>
55
Eric Laurent81784c32012-11-19 14:55:58 -080056#include "AudioFlinger.h"
57#include "AudioMixer.h"
Andy Hungd330ee42015-04-20 13:23:41 -070058#include "BufferProviders.h"
Eric Laurent81784c32012-11-19 14:55:58 -080059#include "FastMixer.h"
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070060#include "FastCapture.h"
Eric Laurent81784c32012-11-19 14:55:58 -080061#include "ServiceUtilities.h"
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -070062#include "mediautils/SchedulingPolicyService.h"
Eric Laurent81784c32012-11-19 14:55:58 -080063
Eric Laurent81784c32012-11-19 14:55:58 -080064#ifdef ADD_BATTERY_DATA
65#include <media/IMediaPlayerService.h>
66#include <media/IMediaDeathNotifier.h>
67#endif
68
Eric Laurent81784c32012-11-19 14:55:58 -080069#ifdef DEBUG_CPU_USAGE
70#include <cpustats/CentralTendencyStatistics.h>
71#include <cpustats/ThreadCpuUsage.h>
72#endif
73
Glenn Kastenc05b8d72016-03-24 09:48:17 -070074#include "AutoPark.h"
75
Eric Laurent81784c32012-11-19 14:55:58 -080076// ----------------------------------------------------------------------------
77
78// Note: the following macro is used for extremely verbose logging message. In
79// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
80// 0; but one side effect of this is to turn all LOGV's as well. Some messages
81// are so verbose that we want to suppress them even when we have ALOG_ASSERT
82// turned on. Do not uncomment the #def below unless you really know what you
83// are doing and want to see all of the extremely verbose messages.
84//#define VERY_VERY_VERBOSE_LOGGING
85#ifdef VERY_VERY_VERBOSE_LOGGING
86#define ALOGVV ALOGV
87#else
88#define ALOGVV(a...) do { } while(0)
89#endif
90
Andy Hung6770c6f2015-04-07 13:43:36 -070091// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -070092#define max(a, b) ((a) > (b) ? (a) : (b))
Andy Hung6770c6f2015-04-07 13:43:36 -070093template <typename T>
94static inline T min(const T& a, const T& b)
95{
96 return a < b ? a : b;
97}
Glenn Kasten49d00ad2014-07-21 11:22:03 -070098
Andy Hungd330ee42015-04-20 13:23:41 -070099#ifndef ARRAY_SIZE
100#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
101#endif
102
Eric Laurent81784c32012-11-19 14:55:58 -0800103namespace android {
104
105// retry counts for buffer fill timeout
106// 50 * ~20msecs = 1 second
107static const int8_t kMaxTrackRetries = 50;
108static const int8_t kMaxTrackStartupRetries = 50;
109// allow less retry attempts on direct output thread.
110// direct outputs can be a scarce resource in audio hardware and should
111// be released as quickly as possible.
112static const int8_t kMaxTrackRetriesDirect = 2;
Eric Laurente93cc032016-05-05 10:15:10 -0700113
Eric Laurent51716182016-02-29 18:00:56 -0800114
Eric Laurent81784c32012-11-19 14:55:58 -0800115
116// don't warn about blocked writes or record buffer overflows more often than this
117static const nsecs_t kWarningThrottleNs = seconds(5);
118
119// RecordThread loop sleep time upon application overrun or audio HAL read error
120static const int kRecordThreadSleepUs = 5000;
121
Eric Laurent10351942014-05-08 18:49:52 -0700122// maximum time to wait in sendConfigEvent_l() for a status to be received
123static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800124
125// minimum sleep time for the mixer thread loop when tracks are active but in underrun
126static const uint32_t kMinThreadSleepTimeUs = 5000;
127// maximum divider applied to the active sleep time in the mixer thread loop
128static const uint32_t kMaxThreadSleepTimeShift = 2;
129
Andy Hung09a50072014-02-27 14:30:47 -0800130// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700131// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800132static const uint32_t kMinNormalSinkBufferSizeMs = 20;
133// maximum normal sink buffer size
134static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800135
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700136// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
137// FIXME This should be based on experimentally observed scheduling jitter
138static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
139
Eric Laurent972a1732013-09-04 09:42:59 -0700140// Offloaded output thread standby delay: allows track transition without going to standby
141static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
142
Eric Laurent51716182016-02-29 18:00:56 -0800143// Direct output thread minimum sleep time in idle or active(underrun) state
144static const nsecs_t kDirectMinSleepTimeUs = 10000;
145
Eric Laurent51716182016-02-29 18:00:56 -0800146
Eric Laurent81784c32012-11-19 14:55:58 -0800147// Whether to use fast mixer
148static const enum {
149 FastMixer_Never, // never initialize or use: for debugging only
150 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
151 // normal mixer multiplier is 1
152 FastMixer_Static, // initialize if needed, then use all the time if initialized,
153 // multiplier is calculated based on min & max normal mixer buffer size
154 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
155 // multiplier is calculated based on min & max normal mixer buffer size
156 // FIXME for FastMixer_Dynamic:
157 // Supporting this option will require fixing HALs that can't handle large writes.
158 // For example, one HAL implementation returns an error from a large write,
159 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
160 // We could either fix the HAL implementations, or provide a wrapper that breaks
161 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
162} kUseFastMixer = FastMixer_Static;
163
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700164// Whether to use fast capture
165static const enum {
166 FastCapture_Never, // never initialize or use: for debugging only
167 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
168 FastCapture_Static, // initialize if needed, then use all the time if initialized
169} kUseFastCapture = FastCapture_Static;
170
Eric Laurent81784c32012-11-19 14:55:58 -0800171// Priorities for requestPriority
172static const int kPriorityAudioApp = 2;
173static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700174static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800175
Glenn Kastenea38ee72016-04-18 11:08:01 -0700176// IAudioFlinger::createTrack() has an in/out parameter 'pFrameCount' for the total size of the
177// track buffer in shared memory. Zero on input means to use a default value. For fast tracks,
178// AudioFlinger derives the default from HAL buffer size and 'fast track multiplier'.
Glenn Kasten03490092014-05-27 12:30:54 -0700179
180// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800181static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800182
Glenn Kasten03490092014-05-27 12:30:54 -0700183// The minimum and maximum allowed values
184static const int kFastTrackMultiplierMin = 1;
185static const int kFastTrackMultiplierMax = 2;
186
187// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
188static int sFastTrackMultiplier = kFastTrackMultiplier;
189
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700190// See Thread::readOnlyHeap().
191// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
192// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
193// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Glenn Kasten9f81de32014-07-27 15:02:23 -0700194static const size_t kRecordThreadReadOnlyHeapSize = 0x2000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700195
Eric Laurent81784c32012-11-19 14:55:58 -0800196// ----------------------------------------------------------------------------
197
Glenn Kasten03490092014-05-27 12:30:54 -0700198static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
199
200static void sFastTrackMultiplierInit()
201{
202 char value[PROPERTY_VALUE_MAX];
203 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
204 char *endptr;
205 unsigned long ul = strtoul(value, &endptr, 0);
206 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
207 sFastTrackMultiplier = (int) ul;
208 }
209 }
210}
211
212// ----------------------------------------------------------------------------
213
Eric Laurent81784c32012-11-19 14:55:58 -0800214#ifdef ADD_BATTERY_DATA
215// To collect the amplifier usage
216static void addBatteryData(uint32_t params) {
217 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
218 if (service == NULL) {
219 // it already logged
220 return;
221 }
222
223 service->addBatteryData(params);
224}
225#endif
226
Andy Hung3f0c9022016-01-15 17:49:46 -0800227// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
228struct {
229 // call when you acquire a partial wakelock
230 void acquire(const sp<IBinder> &wakeLockToken) {
231 pthread_mutex_lock(&mLock);
232 if (wakeLockToken.get() == nullptr) {
233 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
234 } else {
235 if (mCount == 0) {
236 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
237 }
238 ++mCount;
239 }
240 pthread_mutex_unlock(&mLock);
241 }
242
243 // call when you release a partial wakelock.
244 void release(const sp<IBinder> &wakeLockToken) {
245 if (wakeLockToken.get() == nullptr) {
246 return;
247 }
248 pthread_mutex_lock(&mLock);
249 if (--mCount < 0) {
250 ALOGE("negative wakelock count");
251 mCount = 0;
252 }
253 pthread_mutex_unlock(&mLock);
254 }
255
256 // retrieves the boottime timebase offset from monotonic.
257 int64_t getBoottimeOffset() {
258 pthread_mutex_lock(&mLock);
259 int64_t boottimeOffset = mBoottimeOffset;
260 pthread_mutex_unlock(&mLock);
261 return boottimeOffset;
262 }
263
264 // Adjusts the timebase offset between TIMEBASE_MONOTONIC
265 // and the selected timebase.
266 // Currently only TIMEBASE_BOOTTIME is allowed.
267 //
268 // This only needs to be called upon acquiring the first partial wakelock
269 // after all other partial wakelocks are released.
270 //
271 // We do an empirical measurement of the offset rather than parsing
272 // /proc/timer_list since the latter is not a formal kernel ABI.
273 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
274 int clockbase;
275 switch (timebase) {
276 case ExtendedTimestamp::TIMEBASE_BOOTTIME:
277 clockbase = SYSTEM_TIME_BOOTTIME;
278 break;
279 default:
280 LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
281 break;
282 }
283 // try three times to get the clock offset, choose the one
284 // with the minimum gap in measurements.
285 const int tries = 3;
286 nsecs_t bestGap, measured;
287 for (int i = 0; i < tries; ++i) {
288 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
289 const nsecs_t tbase = systemTime(clockbase);
290 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
291 const nsecs_t gap = tmono2 - tmono;
292 if (i == 0 || gap < bestGap) {
293 bestGap = gap;
294 measured = tbase - ((tmono + tmono2) >> 1);
295 }
296 }
297
298 // to avoid micro-adjusting, we don't change the timebase
299 // unless it is significantly different.
300 //
301 // Assumption: It probably takes more than toleranceNs to
302 // suspend and resume the device.
303 static int64_t toleranceNs = 10000; // 10 us
304 if (llabs(*offset - measured) > toleranceNs) {
305 ALOGV("Adjusting timebase offset old: %lld new: %lld",
306 (long long)*offset, (long long)measured);
307 *offset = measured;
308 }
309 }
310
311 pthread_mutex_t mLock;
312 int32_t mCount;
313 int64_t mBoottimeOffset;
314} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
Eric Laurent81784c32012-11-19 14:55:58 -0800315
316// ----------------------------------------------------------------------------
317// CPU Stats
318// ----------------------------------------------------------------------------
319
320class CpuStats {
321public:
322 CpuStats();
323 void sample(const String8 &title);
324#ifdef DEBUG_CPU_USAGE
325private:
326 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
327 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
328
329 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
330
331 int mCpuNum; // thread's current CPU number
332 int mCpukHz; // frequency of thread's current CPU in kHz
333#endif
334};
335
336CpuStats::CpuStats()
337#ifdef DEBUG_CPU_USAGE
338 : mCpuNum(-1), mCpukHz(-1)
339#endif
340{
341}
342
Glenn Kasten0f11b512014-01-31 16:18:54 -0800343void CpuStats::sample(const String8 &title
344#ifndef DEBUG_CPU_USAGE
345 __unused
346#endif
347 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800348#ifdef DEBUG_CPU_USAGE
349 // get current thread's delta CPU time in wall clock ns
350 double wcNs;
351 bool valid = mCpuUsage.sampleAndEnable(wcNs);
352
353 // record sample for wall clock statistics
354 if (valid) {
355 mWcStats.sample(wcNs);
356 }
357
358 // get the current CPU number
359 int cpuNum = sched_getcpu();
360
361 // get the current CPU frequency in kHz
362 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
363
364 // check if either CPU number or frequency changed
365 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
366 mCpuNum = cpuNum;
367 mCpukHz = cpukHz;
368 // ignore sample for purposes of cycles
369 valid = false;
370 }
371
372 // if no change in CPU number or frequency, then record sample for cycle statistics
373 if (valid && mCpukHz > 0) {
374 double cycles = wcNs * cpukHz * 0.000001;
375 mHzStats.sample(cycles);
376 }
377
378 unsigned n = mWcStats.n();
379 // mCpuUsage.elapsed() is expensive, so don't call it every loop
380 if ((n & 127) == 1) {
381 long long elapsed = mCpuUsage.elapsed();
382 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
383 double perLoop = elapsed / (double) n;
384 double perLoop100 = perLoop * 0.01;
385 double perLoop1k = perLoop * 0.001;
386 double mean = mWcStats.mean();
387 double stddev = mWcStats.stddev();
388 double minimum = mWcStats.minimum();
389 double maximum = mWcStats.maximum();
390 double meanCycles = mHzStats.mean();
391 double stddevCycles = mHzStats.stddev();
392 double minCycles = mHzStats.minimum();
393 double maxCycles = mHzStats.maximum();
394 mCpuUsage.resetElapsed();
395 mWcStats.reset();
396 mHzStats.reset();
397 ALOGD("CPU usage for %s over past %.1f secs\n"
398 " (%u mixer loops at %.1f mean ms per loop):\n"
399 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
400 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
401 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
402 title.string(),
403 elapsed * .000000001, n, perLoop * .000001,
404 mean * .001,
405 stddev * .001,
406 minimum * .001,
407 maximum * .001,
408 mean / perLoop100,
409 stddev / perLoop100,
410 minimum / perLoop100,
411 maximum / perLoop100,
412 meanCycles / perLoop1k,
413 stddevCycles / perLoop1k,
414 minCycles / perLoop1k,
415 maxCycles / perLoop1k);
416
417 }
418 }
419#endif
420};
421
422// ----------------------------------------------------------------------------
423// ThreadBase
424// ----------------------------------------------------------------------------
425
Glenn Kasten97b7b752014-09-28 13:04:24 -0700426// static
427const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
428{
429 switch (type) {
430 case MIXER:
431 return "MIXER";
432 case DIRECT:
433 return "DIRECT";
434 case DUPLICATING:
435 return "DUPLICATING";
436 case RECORD:
437 return "RECORD";
438 case OFFLOAD:
439 return "OFFLOAD";
440 default:
441 return "unknown";
442 }
443}
444
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800445String8 devicesToString(audio_devices_t devices)
446{
447 static const struct mapping {
448 audio_devices_t mDevices;
449 const char * mString;
450 } mappingsOut[] = {
Glenn Kasten818da522015-12-02 13:53:26 -0800451 {AUDIO_DEVICE_OUT_EARPIECE, "EARPIECE"},
452 {AUDIO_DEVICE_OUT_SPEAKER, "SPEAKER"},
453 {AUDIO_DEVICE_OUT_WIRED_HEADSET, "WIRED_HEADSET"},
454 {AUDIO_DEVICE_OUT_WIRED_HEADPHONE, "WIRED_HEADPHONE"},
455 {AUDIO_DEVICE_OUT_BLUETOOTH_SCO, "BLUETOOTH_SCO"},
456 {AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET, "BLUETOOTH_SCO_HEADSET"},
457 {AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT, "BLUETOOTH_SCO_CARKIT"},
458 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, "BLUETOOTH_A2DP"},
459 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,"BLUETOOTH_A2DP_HEADPHONES"},
460 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER, "BLUETOOTH_A2DP_SPEAKER"},
461 {AUDIO_DEVICE_OUT_AUX_DIGITAL, "AUX_DIGITAL"},
462 {AUDIO_DEVICE_OUT_HDMI, "HDMI"},
463 {AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET,"ANLG_DOCK_HEADSET"},
464 {AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET,"DGTL_DOCK_HEADSET"},
465 {AUDIO_DEVICE_OUT_USB_ACCESSORY, "USB_ACCESSORY"},
466 {AUDIO_DEVICE_OUT_USB_DEVICE, "USB_DEVICE"},
467 {AUDIO_DEVICE_OUT_TELEPHONY_TX, "TELEPHONY_TX"},
468 {AUDIO_DEVICE_OUT_LINE, "LINE"},
469 {AUDIO_DEVICE_OUT_HDMI_ARC, "HDMI_ARC"},
470 {AUDIO_DEVICE_OUT_SPDIF, "SPDIF"},
471 {AUDIO_DEVICE_OUT_FM, "FM"},
472 {AUDIO_DEVICE_OUT_AUX_LINE, "AUX_LINE"},
473 {AUDIO_DEVICE_OUT_SPEAKER_SAFE, "SPEAKER_SAFE"},
474 {AUDIO_DEVICE_OUT_IP, "IP"},
Eric Laurent58545be2016-02-22 18:54:20 -0800475 {AUDIO_DEVICE_OUT_BUS, "BUS"},
Glenn Kasten818da522015-12-02 13:53:26 -0800476 {AUDIO_DEVICE_NONE, "NONE"}, // must be last
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800477 }, mappingsIn[] = {
Glenn Kasten818da522015-12-02 13:53:26 -0800478 {AUDIO_DEVICE_IN_COMMUNICATION, "COMMUNICATION"},
479 {AUDIO_DEVICE_IN_AMBIENT, "AMBIENT"},
480 {AUDIO_DEVICE_IN_BUILTIN_MIC, "BUILTIN_MIC"},
481 {AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET, "BLUETOOTH_SCO_HEADSET"},
482 {AUDIO_DEVICE_IN_WIRED_HEADSET, "WIRED_HEADSET"},
483 {AUDIO_DEVICE_IN_AUX_DIGITAL, "AUX_DIGITAL"},
484 {AUDIO_DEVICE_IN_VOICE_CALL, "VOICE_CALL"},
485 {AUDIO_DEVICE_IN_TELEPHONY_RX, "TELEPHONY_RX"},
486 {AUDIO_DEVICE_IN_BACK_MIC, "BACK_MIC"},
487 {AUDIO_DEVICE_IN_REMOTE_SUBMIX, "REMOTE_SUBMIX"},
488 {AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET, "ANLG_DOCK_HEADSET"},
489 {AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET, "DGTL_DOCK_HEADSET"},
490 {AUDIO_DEVICE_IN_USB_ACCESSORY, "USB_ACCESSORY"},
491 {AUDIO_DEVICE_IN_USB_DEVICE, "USB_DEVICE"},
492 {AUDIO_DEVICE_IN_FM_TUNER, "FM_TUNER"},
493 {AUDIO_DEVICE_IN_TV_TUNER, "TV_TUNER"},
494 {AUDIO_DEVICE_IN_LINE, "LINE"},
495 {AUDIO_DEVICE_IN_SPDIF, "SPDIF"},
496 {AUDIO_DEVICE_IN_BLUETOOTH_A2DP, "BLUETOOTH_A2DP"},
497 {AUDIO_DEVICE_IN_LOOPBACK, "LOOPBACK"},
498 {AUDIO_DEVICE_IN_IP, "IP"},
Eric Laurent58545be2016-02-22 18:54:20 -0800499 {AUDIO_DEVICE_IN_BUS, "BUS"},
Glenn Kasten818da522015-12-02 13:53:26 -0800500 {AUDIO_DEVICE_NONE, "NONE"}, // must be last
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800501 };
502 String8 result;
503 audio_devices_t allDevices = AUDIO_DEVICE_NONE;
504 const mapping *entry;
505 if (devices & AUDIO_DEVICE_BIT_IN) {
506 devices &= ~AUDIO_DEVICE_BIT_IN;
507 entry = mappingsIn;
508 } else {
509 entry = mappingsOut;
510 }
511 for ( ; entry->mDevices != AUDIO_DEVICE_NONE; entry++) {
512 allDevices = (audio_devices_t) (allDevices | entry->mDevices);
513 if (devices & entry->mDevices) {
514 if (!result.isEmpty()) {
515 result.append("|");
516 }
517 result.append(entry->mString);
518 }
519 }
520 if (devices & ~allDevices) {
521 if (!result.isEmpty()) {
522 result.append("|");
523 }
524 result.appendFormat("0x%X", devices & ~allDevices);
525 }
526 if (result.isEmpty()) {
527 result.append(entry->mString);
528 }
529 return result;
530}
531
532String8 inputFlagsToString(audio_input_flags_t flags)
533{
534 static const struct mapping {
535 audio_input_flags_t mFlag;
536 const char * mString;
537 } mappings[] = {
Glenn Kasten818da522015-12-02 13:53:26 -0800538 {AUDIO_INPUT_FLAG_FAST, "FAST"},
539 {AUDIO_INPUT_FLAG_HW_HOTWORD, "HW_HOTWORD"},
540 {AUDIO_INPUT_FLAG_RAW, "RAW"},
541 {AUDIO_INPUT_FLAG_SYNC, "SYNC"},
542 {AUDIO_INPUT_FLAG_NONE, "NONE"}, // must be last
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800543 };
544 String8 result;
545 audio_input_flags_t allFlags = AUDIO_INPUT_FLAG_NONE;
546 const mapping *entry;
547 for (entry = mappings; entry->mFlag != AUDIO_INPUT_FLAG_NONE; entry++) {
548 allFlags = (audio_input_flags_t) (allFlags | entry->mFlag);
549 if (flags & entry->mFlag) {
550 if (!result.isEmpty()) {
551 result.append("|");
552 }
553 result.append(entry->mString);
554 }
555 }
556 if (flags & ~allFlags) {
557 if (!result.isEmpty()) {
558 result.append("|");
559 }
560 result.appendFormat("0x%X", flags & ~allFlags);
561 }
562 if (result.isEmpty()) {
563 result.append(entry->mString);
564 }
565 return result;
566}
567
568String8 outputFlagsToString(audio_output_flags_t flags)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700569{
570 static const struct mapping {
571 audio_output_flags_t mFlag;
572 const char * mString;
573 } mappings[] = {
Glenn Kasten818da522015-12-02 13:53:26 -0800574 {AUDIO_OUTPUT_FLAG_DIRECT, "DIRECT"},
575 {AUDIO_OUTPUT_FLAG_PRIMARY, "PRIMARY"},
576 {AUDIO_OUTPUT_FLAG_FAST, "FAST"},
577 {AUDIO_OUTPUT_FLAG_DEEP_BUFFER, "DEEP_BUFFER"},
578 {AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,"COMPRESS_OFFLOAD"},
579 {AUDIO_OUTPUT_FLAG_NON_BLOCKING, "NON_BLOCKING"},
580 {AUDIO_OUTPUT_FLAG_HW_AV_SYNC, "HW_AV_SYNC"},
581 {AUDIO_OUTPUT_FLAG_RAW, "RAW"},
582 {AUDIO_OUTPUT_FLAG_SYNC, "SYNC"},
583 {AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO, "IEC958_NONAUDIO"},
584 {AUDIO_OUTPUT_FLAG_NONE, "NONE"}, // must be last
Glenn Kasten97b7b752014-09-28 13:04:24 -0700585 };
586 String8 result;
587 audio_output_flags_t allFlags = AUDIO_OUTPUT_FLAG_NONE;
588 const mapping *entry;
589 for (entry = mappings; entry->mFlag != AUDIO_OUTPUT_FLAG_NONE; entry++) {
590 allFlags = (audio_output_flags_t) (allFlags | entry->mFlag);
591 if (flags & entry->mFlag) {
592 if (!result.isEmpty()) {
593 result.append("|");
594 }
595 result.append(entry->mString);
596 }
597 }
598 if (flags & ~allFlags) {
599 if (!result.isEmpty()) {
600 result.append("|");
601 }
602 result.appendFormat("0x%X", flags & ~allFlags);
603 }
604 if (result.isEmpty()) {
605 result.append(entry->mString);
606 }
607 return result;
608}
609
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800610const char *sourceToString(audio_source_t source)
611{
612 switch (source) {
613 case AUDIO_SOURCE_DEFAULT: return "default";
614 case AUDIO_SOURCE_MIC: return "mic";
615 case AUDIO_SOURCE_VOICE_UPLINK: return "voice uplink";
616 case AUDIO_SOURCE_VOICE_DOWNLINK: return "voice downlink";
617 case AUDIO_SOURCE_VOICE_CALL: return "voice call";
618 case AUDIO_SOURCE_CAMCORDER: return "camcorder";
619 case AUDIO_SOURCE_VOICE_RECOGNITION: return "voice recognition";
620 case AUDIO_SOURCE_VOICE_COMMUNICATION: return "voice communication";
621 case AUDIO_SOURCE_REMOTE_SUBMIX: return "remote submix";
rago8a397d52015-12-02 11:27:57 -0800622 case AUDIO_SOURCE_UNPROCESSED: return "unprocessed";
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800623 case AUDIO_SOURCE_FM_TUNER: return "FM tuner";
624 case AUDIO_SOURCE_HOTWORD: return "hotword";
625 default: return "unknown";
626 }
627}
628
Eric Laurent81784c32012-11-19 14:55:58 -0800629AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -0700630 audio_devices_t outDevice, audio_devices_t inDevice, type_t type, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -0800631 : Thread(false /*canCallJava*/),
632 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700633 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700634 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800635 // are set by PlaybackThread::readOutputParameters_l() or
636 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700637 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800638 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700639 mPrevOutDevice(AUDIO_DEVICE_NONE), mPrevInDevice(AUDIO_DEVICE_NONE),
640 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800641 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700642 mDeathRecipient(new PMDeathRecipient(this)),
Wei Jia3f273d12015-11-24 09:06:49 -0800643 mSystemReady(systemReady),
644 mNotifiedBatteryStart(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800645{
Eric Laurent296fb132015-05-01 11:38:42 -0700646 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800647}
648
649AudioFlinger::ThreadBase::~ThreadBase()
650{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700651 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700652 mConfigEvents.clear();
653
Eric Laurent81784c32012-11-19 14:55:58 -0800654 // do not lock the mutex in destructor
655 releaseWakeLock_l();
656 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800657 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800658 binder->unlinkToDeath(mDeathRecipient);
659 }
660}
661
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700662status_t AudioFlinger::ThreadBase::readyToRun()
663{
664 status_t status = initCheck();
665 if (status == NO_ERROR) {
666 ALOGI("AudioFlinger's thread %p ready to run", this);
667 } else {
668 ALOGE("No working audio driver found.");
669 }
670 return status;
671}
672
Eric Laurent81784c32012-11-19 14:55:58 -0800673void AudioFlinger::ThreadBase::exit()
674{
675 ALOGV("ThreadBase::exit");
676 // do any cleanup required for exit to succeed
677 preExit();
678 {
679 // This lock prevents the following race in thread (uniprocessor for illustration):
680 // if (!exitPending()) {
681 // // context switch from here to exit()
682 // // exit() calls requestExit(), what exitPending() observes
683 // // exit() calls signal(), which is dropped since no waiters
684 // // context switch back from exit() to here
685 // mWaitWorkCV.wait(...);
686 // // now thread is hung
687 // }
688 AutoMutex lock(mLock);
689 requestExit();
690 mWaitWorkCV.broadcast();
691 }
692 // When Thread::requestExitAndWait is made virtual and this method is renamed to
693 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
694 requestExitAndWait();
695}
696
697status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
698{
Eric Laurent81784c32012-11-19 14:55:58 -0800699 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
700 Mutex::Autolock _l(mLock);
701
Eric Laurent10351942014-05-08 18:49:52 -0700702 return sendSetParameterConfigEvent_l(keyValuePairs);
703}
704
705// sendConfigEvent_l() must be called with ThreadBase::mLock held
706// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
707status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
708{
709 status_t status = NO_ERROR;
710
Eric Laurent72e3f392015-05-20 14:43:50 -0700711 if (event->mRequiresSystemReady && !mSystemReady) {
712 event->mWaitStatus = false;
713 mPendingConfigEvents.add(event);
714 return status;
715 }
Eric Laurent10351942014-05-08 18:49:52 -0700716 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700717 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800718 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700719 mLock.unlock();
720 {
721 Mutex::Autolock _l(event->mLock);
722 while (event->mWaitStatus) {
723 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
724 event->mStatus = TIMED_OUT;
725 event->mWaitStatus = false;
726 }
727 }
728 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800729 }
Eric Laurent10351942014-05-08 18:49:52 -0700730 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800731 return status;
732}
733
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700734void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800735{
736 Mutex::Autolock _l(mLock);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700737 sendIoConfigEvent_l(event, pid);
Eric Laurent81784c32012-11-19 14:55:58 -0800738}
739
740// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700741void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800742{
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700743 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid);
Eric Laurent10351942014-05-08 18:49:52 -0700744 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800745}
746
Eric Laurent72e3f392015-05-20 14:43:50 -0700747void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio)
748{
749 Mutex::Autolock _l(mLock);
750 sendPrioConfigEvent_l(pid, tid, prio);
751}
752
Eric Laurent81784c32012-11-19 14:55:58 -0800753// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
754void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
755{
Eric Laurent10351942014-05-08 18:49:52 -0700756 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio);
757 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800758}
759
Eric Laurent10351942014-05-08 18:49:52 -0700760// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
761status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800762{
Andy Hung2ddee192015-12-18 17:34:44 -0800763 sp<ConfigEvent> configEvent;
764 AudioParameter param(keyValuePair);
765 int value;
766 if (param.getInt(String8(AUDIO_PARAMETER_MONO_OUTPUT), value) == NO_ERROR) {
767 setMasterMono_l(value != 0);
768 if (param.size() == 1) {
769 return NO_ERROR; // should be a solo parameter - we don't pass down
770 }
771 param.remove(String8(AUDIO_PARAMETER_MONO_OUTPUT));
772 configEvent = new SetParameterConfigEvent(param.toString());
773 } else {
774 configEvent = new SetParameterConfigEvent(keyValuePair);
775 }
Eric Laurent10351942014-05-08 18:49:52 -0700776 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700777}
778
Eric Laurent1c333e22014-05-20 10:48:17 -0700779status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
780 const struct audio_patch *patch,
781 audio_patch_handle_t *handle)
782{
783 Mutex::Autolock _l(mLock);
784 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
785 status_t status = sendConfigEvent_l(configEvent);
786 if (status == NO_ERROR) {
787 CreateAudioPatchConfigEventData *data =
788 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
789 *handle = data->mHandle;
790 }
791 return status;
792}
793
794status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
795 const audio_patch_handle_t handle)
796{
797 Mutex::Autolock _l(mLock);
798 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
799 return sendConfigEvent_l(configEvent);
800}
801
802
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700803// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700804void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700805{
Eric Laurent10351942014-05-08 18:49:52 -0700806 bool configChanged = false;
807
Eric Laurent81784c32012-11-19 14:55:58 -0800808 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700809 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700810 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800811 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700812 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700813 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700814 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
815 // FIXME Need to understand why this has to be done asynchronously
816 int err = requestPriority(data->mPid, data->mTid, data->mPrio,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700817 true /*asynchronous*/);
818 if (err != 0) {
819 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700820 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700821 }
822 } break;
823 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700824 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700825 ioConfigChanged(data->mEvent, data->mPid);
Eric Laurent10351942014-05-08 18:49:52 -0700826 } break;
827 case CFG_EVENT_SET_PARAMETER: {
828 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
829 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
830 configChanged = true;
Glenn Kastend5418eb2013-08-14 13:11:06 -0700831 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700832 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700833 case CFG_EVENT_CREATE_AUDIO_PATCH: {
834 CreateAudioPatchConfigEventData *data =
835 (CreateAudioPatchConfigEventData *)event->mData.get();
836 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
837 } break;
838 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
839 ReleaseAudioPatchConfigEventData *data =
840 (ReleaseAudioPatchConfigEventData *)event->mData.get();
841 event->mStatus = releaseAudioPatch_l(data->mHandle);
842 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700843 default:
Eric Laurent10351942014-05-08 18:49:52 -0700844 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700845 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800846 }
Eric Laurent10351942014-05-08 18:49:52 -0700847 {
848 Mutex::Autolock _l(event->mLock);
849 if (event->mWaitStatus) {
850 event->mWaitStatus = false;
851 event->mCond.signal();
852 }
853 }
854 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
855 }
856
857 if (configChanged) {
858 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800859 }
Eric Laurent81784c32012-11-19 14:55:58 -0800860}
861
Marco Nelissenb2208842014-02-07 14:00:50 -0800862String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
863 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700864 const audio_channel_representation_t representation =
865 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700866
867 switch (representation) {
868 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
869 if (output) {
870 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
871 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
872 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
873 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
874 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
875 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
876 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
877 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
878 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
879 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
880 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
881 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
882 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
883 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
884 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
885 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
886 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
887 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
888 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
889 } else {
890 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
891 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
892 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
893 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
894 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
895 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
896 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
897 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
898 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
899 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
900 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
901 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
902 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
903 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
904 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
905 }
906 const int len = s.length();
907 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -0700908 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -0700909 s.unlockBuffer(len - 2); // remove trailing ", "
910 }
911 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800912 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700913 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
914 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
915 return s;
916 default:
917 s.appendFormat("unknown mask, representation:%d bits:%#x",
918 representation, audio_channel_mask_get_bits(mask));
919 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800920 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800921}
922
Glenn Kasten0f11b512014-01-31 16:18:54 -0800923void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800924{
925 const size_t SIZE = 256;
926 char buffer[SIZE];
927 String8 result;
928
929 bool locked = AudioFlinger::dumpTryLock(mLock);
930 if (!locked) {
Glenn Kasten97b7b752014-09-28 13:04:24 -0700931 dprintf(fd, "thread %p may be deadlocked\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -0800932 }
933
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800934 dprintf(fd, " Thread name: %s\n", mThreadName);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700935 dprintf(fd, " I/O handle: %d\n", mId);
936 dprintf(fd, " TID: %d\n", getTid());
937 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700938 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700939 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700940 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat));
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700941 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700942 dprintf(fd, " Channel count: %u\n", mChannelCount);
943 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800944 channelMaskToString(mChannelMask, mType != RECORD).string());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700945 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat));
946 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700947 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800948 size_t numConfig = mConfigEvents.size();
949 if (numConfig) {
950 for (size_t i = 0; i < numConfig; i++) {
951 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700952 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800953 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700954 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800955 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700956 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800957 }
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800958 dprintf(fd, " Output device: %#x (%s)\n", mOutDevice, devicesToString(mOutDevice).string());
959 dprintf(fd, " Input device: %#x (%s)\n", mInDevice, devicesToString(mInDevice).string());
960 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, sourceToString(mAudioSource));
Eric Laurent81784c32012-11-19 14:55:58 -0800961
962 if (locked) {
963 mLock.unlock();
964 }
965}
966
967void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
968{
969 const size_t SIZE = 256;
970 char buffer[SIZE];
971 String8 result;
972
Marco Nelissenb2208842014-02-07 14:00:50 -0800973 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000974 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800975 write(fd, buffer, strlen(buffer));
976
Marco Nelissenb2208842014-02-07 14:00:50 -0800977 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800978 sp<EffectChain> chain = mEffectChains[i];
979 if (chain != 0) {
980 chain->dump(fd, args);
981 }
982 }
983}
984
Marco Nelissene14a5d62013-10-03 08:51:24 -0700985void AudioFlinger::ThreadBase::acquireWakeLock(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800986{
987 Mutex::Autolock _l(mLock);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700988 acquireWakeLock_l(uid);
Eric Laurent81784c32012-11-19 14:55:58 -0800989}
990
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100991String16 AudioFlinger::ThreadBase::getWakeLockTag()
992{
993 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -0800994 case MIXER:
995 return String16("AudioMix");
996 case DIRECT:
997 return String16("AudioDirectOut");
998 case DUPLICATING:
999 return String16("AudioDup");
1000 case RECORD:
1001 return String16("AudioIn");
1002 case OFFLOAD:
1003 return String16("AudioOffload");
1004 default:
1005 ALOG_ASSERT(false);
1006 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001007 }
1008}
1009
Marco Nelissene14a5d62013-10-03 08:51:24 -07001010void AudioFlinger::ThreadBase::acquireWakeLock_l(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -08001011{
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001012 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001013 if (mPowerManager != 0) {
1014 sp<IBinder> binder = new BBinder();
Marco Nelissene14a5d62013-10-03 08:51:24 -07001015 status_t status;
1016 if (uid >= 0) {
Eric Laurent547789d2013-10-04 11:46:55 -07001017 status = mPowerManager->acquireWakeLockWithUid(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -07001018 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001019 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -07001020 String16("audioserver"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -07001021 uid,
1022 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -07001023 } else {
Eric Laurent547789d2013-10-04 11:46:55 -07001024 status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -07001025 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001026 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -07001027 String16("audioserver"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -07001028 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -07001029 }
Eric Laurent81784c32012-11-19 14:55:58 -08001030 if (status == NO_ERROR) {
1031 mWakeLockToken = binder;
1032 }
Glenn Kastend7dca052015-03-05 16:05:54 -08001033 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -08001034 }
Wei Jia3f273d12015-11-24 09:06:49 -08001035
1036 if (!mNotifiedBatteryStart) {
1037 BatteryNotifier::getInstance().noteStartAudio();
1038 mNotifiedBatteryStart = true;
1039 }
Andy Hung3f0c9022016-01-15 17:49:46 -08001040 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -08001041 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
1042 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -08001043}
1044
1045void AudioFlinger::ThreadBase::releaseWakeLock()
1046{
1047 Mutex::Autolock _l(mLock);
1048 releaseWakeLock_l();
1049}
1050
1051void AudioFlinger::ThreadBase::releaseWakeLock_l()
1052{
Andy Hung3f0c9022016-01-15 17:49:46 -08001053 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -08001054 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001055 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001056 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -07001057 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
1058 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -08001059 }
1060 mWakeLockToken.clear();
1061 }
Wei Jia3f273d12015-11-24 09:06:49 -08001062
1063 if (mNotifiedBatteryStart) {
1064 BatteryNotifier::getInstance().noteStopAudio();
1065 mNotifiedBatteryStart = false;
1066 }
Eric Laurent81784c32012-11-19 14:55:58 -08001067}
1068
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001069void AudioFlinger::ThreadBase::updateWakeLockUids(const SortedVector<int> &uids) {
1070 Mutex::Autolock _l(mLock);
1071 updateWakeLockUids_l(uids);
1072}
1073
1074void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -07001075 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001076 // use checkService() to avoid blocking if power service is not up yet
1077 sp<IBinder> binder =
1078 defaultServiceManager()->checkService(String16("power"));
1079 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001080 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001081 } else {
1082 mPowerManager = interface_cast<IPowerManager>(binder);
1083 binder->linkToDeath(mDeathRecipient);
1084 }
1085 }
1086}
1087
1088void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<int> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001089 getPowerManager_l();
Andy Hung438e7572015-12-14 15:51:17 -08001090 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
1091 if (mSystemReady) {
1092 ALOGE("no wake lock to update, but system ready!");
1093 } else {
1094 ALOGW("no wake lock to update, system not ready yet");
1095 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001096 return;
1097 }
1098 if (mPowerManager != 0) {
1099 sp<IBinder> binder = new BBinder();
1100 status_t status;
Glenn Kasten3abc2de2014-09-05 16:45:52 -07001101 status = mPowerManager->updateWakeLockUids(mWakeLockToken, uids.size(), uids.array(),
1102 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent4d231dc2016-03-11 18:38:23 -08001103 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001104 }
1105}
1106
Eric Laurent81784c32012-11-19 14:55:58 -08001107void AudioFlinger::ThreadBase::clearPowerManager()
1108{
1109 Mutex::Autolock _l(mLock);
1110 releaseWakeLock_l();
1111 mPowerManager.clear();
1112}
1113
Glenn Kasten0f11b512014-01-31 16:18:54 -08001114void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001115{
1116 sp<ThreadBase> thread = mThread.promote();
1117 if (thread != 0) {
1118 thread->clearPowerManager();
1119 }
1120 ALOGW("power manager service died !!!");
1121}
1122
1123void AudioFlinger::ThreadBase::setEffectSuspended(
Glenn Kastend848eb42016-03-08 13:42:11 -08001124 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001125{
1126 Mutex::Autolock _l(mLock);
1127 setEffectSuspended_l(type, suspend, sessionId);
1128}
1129
1130void AudioFlinger::ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001131 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001132{
1133 sp<EffectChain> chain = getEffectChain_l(sessionId);
1134 if (chain != 0) {
1135 if (type != NULL) {
1136 chain->setEffectSuspended_l(type, suspend);
1137 } else {
1138 chain->setEffectSuspendedAll_l(suspend);
1139 }
1140 }
1141
1142 updateSuspendedSessions_l(type, suspend, sessionId);
1143}
1144
1145void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1146{
1147 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1148 if (index < 0) {
1149 return;
1150 }
1151
1152 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1153 mSuspendedSessions.valueAt(index);
1154
1155 for (size_t i = 0; i < sessionEffects.size(); i++) {
1156 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1157 for (int j = 0; j < desc->mRefCount; j++) {
1158 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1159 chain->setEffectSuspendedAll_l(true);
1160 } else {
1161 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1162 desc->mType.timeLow);
1163 chain->setEffectSuspended_l(&desc->mType, true);
1164 }
1165 }
1166 }
1167}
1168
1169void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1170 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001171 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001172{
1173 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1174
1175 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1176
1177 if (suspend) {
1178 if (index >= 0) {
1179 sessionEffects = mSuspendedSessions.valueAt(index);
1180 } else {
1181 mSuspendedSessions.add(sessionId, sessionEffects);
1182 }
1183 } else {
1184 if (index < 0) {
1185 return;
1186 }
1187 sessionEffects = mSuspendedSessions.valueAt(index);
1188 }
1189
1190
1191 int key = EffectChain::kKeyForSuspendAll;
1192 if (type != NULL) {
1193 key = type->timeLow;
1194 }
1195 index = sessionEffects.indexOfKey(key);
1196
1197 sp<SuspendedSessionDesc> desc;
1198 if (suspend) {
1199 if (index >= 0) {
1200 desc = sessionEffects.valueAt(index);
1201 } else {
1202 desc = new SuspendedSessionDesc();
1203 if (type != NULL) {
1204 desc->mType = *type;
1205 }
1206 sessionEffects.add(key, desc);
1207 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1208 }
1209 desc->mRefCount++;
1210 } else {
1211 if (index < 0) {
1212 return;
1213 }
1214 desc = sessionEffects.valueAt(index);
1215 if (--desc->mRefCount == 0) {
1216 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1217 sessionEffects.removeItemsAt(index);
1218 if (sessionEffects.isEmpty()) {
1219 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1220 sessionId);
1221 mSuspendedSessions.removeItem(sessionId);
1222 }
1223 }
1224 }
1225 if (!sessionEffects.isEmpty()) {
1226 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1227 }
1228}
1229
1230void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1231 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001232 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001233{
1234 Mutex::Autolock _l(mLock);
1235 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1236}
1237
1238void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1239 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001240 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001241{
1242 if (mType != RECORD) {
1243 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1244 // another session. This gives the priority to well behaved effect control panels
1245 // and applications not using global effects.
1246 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1247 // global effects
1248 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1249 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1250 }
1251 }
1252
1253 sp<EffectChain> chain = getEffectChain_l(sessionId);
1254 if (chain != 0) {
1255 chain->checkSuspendOnEffectEnabled(effect, enabled);
1256 }
1257}
1258
Eric Laurent4c415062016-06-17 16:14:16 -07001259// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1260status_t AudioFlinger::RecordThread::checkEffectCompatibility_l(
1261 const effect_descriptor_t *desc, audio_session_t sessionId)
1262{
1263 // No global effect sessions on record threads
1264 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1265 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1266 desc->name, mThreadName);
1267 return BAD_VALUE;
1268 }
1269 // only pre processing effects on record thread
1270 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1271 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1272 desc->name, mThreadName);
1273 return BAD_VALUE;
1274 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001275
1276 // always allow effects without processing load or latency
1277 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1278 return NO_ERROR;
1279 }
1280
Eric Laurent4c415062016-06-17 16:14:16 -07001281 audio_input_flags_t flags = mInput->flags;
1282 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1283 if (flags & AUDIO_INPUT_FLAG_RAW) {
1284 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1285 desc->name, mThreadName);
1286 return BAD_VALUE;
1287 }
1288 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1289 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1290 desc->name, mThreadName);
1291 return BAD_VALUE;
1292 }
1293 }
1294 return NO_ERROR;
1295}
1296
1297// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1298status_t AudioFlinger::PlaybackThread::checkEffectCompatibility_l(
1299 const effect_descriptor_t *desc, audio_session_t sessionId)
1300{
1301 // no preprocessing on playback threads
1302 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
1303 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback"
1304 " thread %s", desc->name, mThreadName);
1305 return BAD_VALUE;
1306 }
1307
1308 switch (mType) {
1309 case MIXER: {
1310 // Reject any effect on mixer multichannel sinks.
1311 // TODO: fix both format and multichannel issues with effects.
1312 if (mChannelCount != FCC_2) {
1313 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d) on MIXER"
1314 " thread %s", desc->name, mChannelCount, mThreadName);
1315 return BAD_VALUE;
1316 }
1317 audio_output_flags_t flags = mOutput->flags;
1318 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1319 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1320 // global effects are applied only to non fast tracks if they are SW
1321 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1322 break;
1323 }
1324 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1325 // only post processing on output stage session
1326 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1327 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1328 " on output stage session", desc->name);
1329 return BAD_VALUE;
1330 }
1331 } else {
1332 // no restriction on effects applied on non fast tracks
1333 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1334 break;
1335 }
1336 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001337
1338 // always allow effects without processing load or latency
1339 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1340 break;
1341 }
Eric Laurent4c415062016-06-17 16:14:16 -07001342 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
1343 ALOGW("checkEffectCompatibility_l(): effect %s on playback thread in raw mode",
1344 desc->name);
1345 return BAD_VALUE;
1346 }
1347 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1348 ALOGW("checkEffectCompatibility_l(): non HW effect %s on playback thread"
1349 " in fast mode", desc->name);
1350 return BAD_VALUE;
1351 }
1352 }
1353 } break;
1354 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001355 // nothing actionable on offload threads, if the effect:
1356 // - is offloadable: the effect can be created
1357 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1358 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001359 break;
1360 case DIRECT:
1361 // Reject any effect on Direct output threads for now, since the format of
1362 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1363 ALOGW("checkEffectCompatibility_l(): effect %s on DIRECT output thread %s",
1364 desc->name, mThreadName);
1365 return BAD_VALUE;
1366 case DUPLICATING:
1367 // Reject any effect on mixer multichannel sinks.
1368 // TODO: fix both format and multichannel issues with effects.
1369 if (mChannelCount != FCC_2) {
1370 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d)"
1371 " on DUPLICATING thread %s", desc->name, mChannelCount, mThreadName);
1372 return BAD_VALUE;
1373 }
1374 if ((sessionId == AUDIO_SESSION_OUTPUT_STAGE) || (sessionId == AUDIO_SESSION_OUTPUT_MIX)) {
1375 ALOGW("checkEffectCompatibility_l(): global effect %s on DUPLICATING"
1376 " thread %s", desc->name, mThreadName);
1377 return BAD_VALUE;
1378 }
1379 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
1380 ALOGW("checkEffectCompatibility_l(): post processing effect %s on"
1381 " DUPLICATING thread %s", desc->name, mThreadName);
1382 return BAD_VALUE;
1383 }
1384 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1385 ALOGW("checkEffectCompatibility_l(): HW tunneled effect %s on"
1386 " DUPLICATING thread %s", desc->name, mThreadName);
1387 return BAD_VALUE;
1388 }
1389 break;
1390 default:
1391 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1392 }
1393
1394 return NO_ERROR;
1395}
1396
Eric Laurent81784c32012-11-19 14:55:58 -08001397// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1398sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1399 const sp<AudioFlinger::Client>& client,
1400 const sp<IEffectClient>& effectClient,
1401 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001402 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001403 effect_descriptor_t *desc,
1404 int *enabled,
Eric Laurentb378b732016-12-01 15:28:29 -08001405 status_t *status,
1406 bool pinned)
Eric Laurent81784c32012-11-19 14:55:58 -08001407{
1408 sp<EffectModule> effect;
1409 sp<EffectHandle> handle;
1410 status_t lStatus;
1411 sp<EffectChain> chain;
1412 bool chainCreated = false;
1413 bool effectCreated = false;
1414 bool effectRegistered = false;
1415
1416 lStatus = initCheck();
1417 if (lStatus != NO_ERROR) {
1418 ALOGW("createEffect_l() Audio driver not initialized.");
1419 goto Exit;
1420 }
1421
Eric Laurent81784c32012-11-19 14:55:58 -08001422 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1423
1424 { // scope for mLock
1425 Mutex::Autolock _l(mLock);
1426
Eric Laurent4c415062016-06-17 16:14:16 -07001427 lStatus = checkEffectCompatibility_l(desc, sessionId);
1428 if (lStatus != NO_ERROR) {
1429 goto Exit;
1430 }
1431
Eric Laurent81784c32012-11-19 14:55:58 -08001432 // check for existing effect chain with the requested audio session
1433 chain = getEffectChain_l(sessionId);
1434 if (chain == 0) {
1435 // create a new chain for this session
1436 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1437 chain = new EffectChain(this, sessionId);
1438 addEffectChain_l(chain);
1439 chain->setStrategy(getStrategyForSession_l(sessionId));
1440 chainCreated = true;
1441 } else {
1442 effect = chain->getEffectFromDesc_l(desc);
1443 }
1444
1445 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1446
1447 if (effect == 0) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08001448 audio_unique_id_t id = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001449 // Check CPU and memory usage
1450 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
1451 if (lStatus != NO_ERROR) {
1452 goto Exit;
1453 }
1454 effectRegistered = true;
1455 // create a new effect module if none present in the chain
Eric Laurentb378b732016-12-01 15:28:29 -08001456 lStatus = chain->createEffect_l(effect, this, desc, id, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001457 if (lStatus != NO_ERROR) {
1458 goto Exit;
1459 }
1460 effectCreated = true;
1461
1462 effect->setDevice(mOutDevice);
1463 effect->setDevice(mInDevice);
1464 effect->setMode(mAudioFlinger->getMode());
1465 effect->setAudioSource(mAudioSource);
1466 }
1467 // create effect handle and connect it to effect module
1468 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001469 lStatus = handle->initCheck();
1470 if (lStatus == OK) {
1471 lStatus = effect->addHandle(handle.get());
1472 }
Eric Laurent81784c32012-11-19 14:55:58 -08001473 if (enabled != NULL) {
1474 *enabled = (int)effect->isEnabled();
1475 }
1476 }
1477
1478Exit:
1479 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1480 Mutex::Autolock _l(mLock);
1481 if (effectCreated) {
1482 chain->removeEffect_l(effect);
1483 }
1484 if (effectRegistered) {
1485 AudioSystem::unregisterEffect(effect->id());
1486 }
1487 if (chainCreated) {
1488 removeEffectChain_l(chain);
1489 }
1490 handle.clear();
1491 }
1492
Glenn Kasten9156ef32013-08-06 15:39:08 -07001493 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001494 return handle;
1495}
1496
Eric Laurentb378b732016-12-01 15:28:29 -08001497void AudioFlinger::ThreadBase::disconnectEffectHandle(EffectHandle *handle,
1498 bool unpinIfLast)
1499{
1500 bool remove = false;
1501 sp<EffectModule> effect;
1502 {
1503 Mutex::Autolock _l(mLock);
1504
1505 effect = handle->effect().promote();
1506 if (effect == 0) {
1507 return;
1508 }
1509 // restore suspended effects if the disconnected handle was enabled and the last one.
1510 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1511 if (remove) {
1512 removeEffect_l(effect, true);
1513 }
1514 }
1515 if (remove) {
1516 mAudioFlinger->updateOrphanEffectChains(effect);
1517 AudioSystem::unregisterEffect(effect->id());
1518 if (handle->enabled()) {
1519 checkSuspendOnEffectEnabled(effect, false, effect->sessionId());
1520 }
1521 }
1522}
1523
Glenn Kastend848eb42016-03-08 13:42:11 -08001524sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1525 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001526{
1527 Mutex::Autolock _l(mLock);
1528 return getEffect_l(sessionId, effectId);
1529}
1530
Glenn Kastend848eb42016-03-08 13:42:11 -08001531sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1532 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001533{
1534 sp<EffectChain> chain = getEffectChain_l(sessionId);
1535 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1536}
1537
1538// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1539// PlaybackThread::mLock held
1540status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1541{
1542 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001543 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001544 sp<EffectChain> chain = getEffectChain_l(sessionId);
1545 bool chainCreated = false;
1546
Eric Laurent5baf2af2013-09-12 17:37:00 -07001547 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1548 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1549 this, effect->desc().name, effect->desc().flags);
1550
Eric Laurent81784c32012-11-19 14:55:58 -08001551 if (chain == 0) {
1552 // create a new chain for this session
1553 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1554 chain = new EffectChain(this, sessionId);
1555 addEffectChain_l(chain);
1556 chain->setStrategy(getStrategyForSession_l(sessionId));
1557 chainCreated = true;
1558 }
1559 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1560
1561 if (chain->getEffectFromId_l(effect->id()) != 0) {
1562 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1563 this, effect->desc().name, chain.get());
1564 return BAD_VALUE;
1565 }
1566
Eric Laurent5baf2af2013-09-12 17:37:00 -07001567 effect->setOffloaded(mType == OFFLOAD, mId);
1568
Eric Laurent81784c32012-11-19 14:55:58 -08001569 status_t status = chain->addEffect_l(effect);
1570 if (status != NO_ERROR) {
1571 if (chainCreated) {
1572 removeEffectChain_l(chain);
1573 }
1574 return status;
1575 }
1576
1577 effect->setDevice(mOutDevice);
1578 effect->setDevice(mInDevice);
1579 effect->setMode(mAudioFlinger->getMode());
1580 effect->setAudioSource(mAudioSource);
1581 return NO_ERROR;
1582}
1583
Eric Laurentb378b732016-12-01 15:28:29 -08001584void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001585
Eric Laurentb378b732016-12-01 15:28:29 -08001586 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001587 effect_descriptor_t desc = effect->desc();
1588 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1589 detachAuxEffect_l(effect->id());
1590 }
1591
1592 sp<EffectChain> chain = effect->chain().promote();
1593 if (chain != 0) {
1594 // remove effect chain if removing last effect
Eric Laurentb378b732016-12-01 15:28:29 -08001595 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001596 removeEffectChain_l(chain);
1597 }
1598 } else {
1599 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1600 }
1601}
1602
1603void AudioFlinger::ThreadBase::lockEffectChains_l(
1604 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1605{
1606 effectChains = mEffectChains;
1607 for (size_t i = 0; i < mEffectChains.size(); i++) {
1608 mEffectChains[i]->lock();
1609 }
1610}
1611
1612void AudioFlinger::ThreadBase::unlockEffectChains(
1613 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1614{
1615 for (size_t i = 0; i < effectChains.size(); i++) {
1616 effectChains[i]->unlock();
1617 }
1618}
1619
Glenn Kastend848eb42016-03-08 13:42:11 -08001620sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001621{
1622 Mutex::Autolock _l(mLock);
1623 return getEffectChain_l(sessionId);
1624}
1625
Glenn Kastend848eb42016-03-08 13:42:11 -08001626sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1627 const
Eric Laurent81784c32012-11-19 14:55:58 -08001628{
1629 size_t size = mEffectChains.size();
1630 for (size_t i = 0; i < size; i++) {
1631 if (mEffectChains[i]->sessionId() == sessionId) {
1632 return mEffectChains[i];
1633 }
1634 }
1635 return 0;
1636}
1637
1638void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1639{
1640 Mutex::Autolock _l(mLock);
1641 size_t size = mEffectChains.size();
1642 for (size_t i = 0; i < size; i++) {
1643 mEffectChains[i]->setMode_l(mode);
1644 }
1645}
1646
Eric Laurent83b88082014-06-20 18:31:16 -07001647void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1648{
1649 config->type = AUDIO_PORT_TYPE_MIX;
1650 config->ext.mix.handle = mId;
1651 config->sample_rate = mSampleRate;
1652 config->format = mFormat;
1653 config->channel_mask = mChannelMask;
1654 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1655 AUDIO_PORT_CONFIG_FORMAT;
1656}
1657
Eric Laurent72e3f392015-05-20 14:43:50 -07001658void AudioFlinger::ThreadBase::systemReady()
1659{
1660 Mutex::Autolock _l(mLock);
1661 if (mSystemReady) {
1662 return;
1663 }
1664 mSystemReady = true;
1665
1666 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1667 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1668 }
1669 mPendingConfigEvents.clear();
1670}
1671
Eric Laurent83b88082014-06-20 18:31:16 -07001672
Eric Laurent81784c32012-11-19 14:55:58 -08001673// ----------------------------------------------------------------------------
1674// Playback
1675// ----------------------------------------------------------------------------
1676
1677AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1678 AudioStreamOut* output,
1679 audio_io_handle_t id,
1680 audio_devices_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07001681 type_t type,
Eric Laurente93cc032016-05-05 10:15:10 -07001682 bool systemReady)
Eric Laurent72e3f392015-05-20 14:43:50 -07001683 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001684 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001685 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001686 mMixerBuffer(NULL),
1687 mMixerBufferSize(0),
1688 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1689 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001690 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001691 mEffectBuffer(NULL),
1692 mEffectBufferSize(0),
1693 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1694 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001695 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001696 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07001697 mSuspendedFrames(0),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001698 mActiveTracksGeneration(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001699 // mStreamTypes[] initialized in constructor body
1700 mOutput(output),
Andy Hung69488c42016-05-16 18:43:33 -07001701 mLastWriteTime(-1), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001702 mMixerStatus(MIXER_IDLE),
1703 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001704 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001705 mBytesRemaining(0),
1706 mCurrentWriteLength(0),
1707 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001708 mWriteAckSequence(0),
1709 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001710 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001711 mScreenState(AudioFlinger::mScreenState),
1712 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001713 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Andy Hunge10393e2015-06-12 13:59:33 -07001714 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001715{
Glenn Kastend7dca052015-03-05 16:05:54 -08001716 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1717 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001718
1719 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1720 // it would be safer to explicitly pass initial masterVolume/masterMute as
1721 // parameter.
1722 //
1723 // If the HAL we are using has support for master volume or master mute,
1724 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1725 // and the mute set to false).
1726 mMasterVolume = audioFlinger->masterVolume_l();
1727 mMasterMute = audioFlinger->masterMute_l();
1728 if (mOutput && mOutput->audioHwDev) {
1729 if (mOutput->audioHwDev->canSetMasterVolume()) {
1730 mMasterVolume = 1.0;
1731 }
1732
1733 if (mOutput->audioHwDev->canSetMasterMute()) {
1734 mMasterMute = false;
1735 }
1736 }
1737
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001738 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001739
Eric Laurent223fd5c2014-11-11 13:43:36 -08001740 // ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001741 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001742 stream = (audio_stream_type_t) (stream + 1)) {
1743 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1744 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1745 }
Eric Laurent81784c32012-11-19 14:55:58 -08001746}
1747
1748AudioFlinger::PlaybackThread::~PlaybackThread()
1749{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001750 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001751 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001752 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001753 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001754}
1755
1756void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1757{
1758 dumpInternals(fd, args);
1759 dumpTracks(fd, args);
1760 dumpEffectChains(fd, args);
Andy Hung1f82f952016-11-28 19:01:02 -08001761 mLocalLog.dump(fd, args, " " /* prefix */);
Eric Laurent81784c32012-11-19 14:55:58 -08001762}
1763
Glenn Kasten0f11b512014-01-31 16:18:54 -08001764void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001765{
1766 const size_t SIZE = 256;
1767 char buffer[SIZE];
1768 String8 result;
1769
Marco Nelissenb2208842014-02-07 14:00:50 -08001770 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001771 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1772 const stream_type_t *st = &mStreamTypes[i];
1773 if (i > 0) {
1774 result.appendFormat(", ");
1775 }
1776 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1777 if (st->mute) {
1778 result.append("M");
1779 }
1780 }
1781 result.append("\n");
1782 write(fd, result.string(), result.length());
1783 result.clear();
1784
Eric Laurent81784c32012-11-19 14:55:58 -08001785 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1786 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001787 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001788 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001789
1790 size_t numtracks = mTracks.size();
1791 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001792 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001793 size_t numactiveseen = 0;
1794 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001795 dprintf(fd, " of which %zu are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001796 Track::appendDumpHeader(result);
1797 for (size_t i = 0; i < numtracks; ++i) {
1798 sp<Track> track = mTracks[i];
1799 if (track != 0) {
1800 bool active = mActiveTracks.indexOf(track) >= 0;
1801 if (active) {
1802 numactiveseen++;
1803 }
1804 track->dump(buffer, SIZE, active);
1805 result.append(buffer);
1806 }
1807 }
1808 } else {
1809 result.append("\n");
1810 }
1811 if (numactiveseen != numactive) {
1812 // some tracks in the active list were not in the tracks list
1813 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1814 " not in the track list\n");
1815 result.append(buffer);
1816 Track::appendDumpHeader(result);
1817 for (size_t i = 0; i < numactive; ++i) {
1818 sp<Track> track = mActiveTracks[i].promote();
1819 if (track != 0 && mTracks.indexOf(track) < 0) {
1820 track->dump(buffer, SIZE, true);
1821 result.append(buffer);
1822 }
1823 }
1824 }
1825
1826 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001827}
1828
1829void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1830{
Glenn Kasten97b7b752014-09-28 13:04:24 -07001831 dprintf(fd, "\nOutput thread %p type %d (%s):\n", this, type(), threadTypeToString(type()));
Glenn Kasten44182c22015-03-05 17:12:23 -08001832
1833 dumpBase(fd, args);
1834
Elliott Hughes87cebad2014-05-22 10:14:43 -07001835 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001836 dprintf(fd, " Last write occurred (msecs): %llu\n",
1837 (unsigned long long) ns2ms(systemTime() - mLastWriteTime));
Elliott Hughes87cebad2014-05-22 10:14:43 -07001838 dprintf(fd, " Total writes: %d\n", mNumWrites);
1839 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1840 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1841 dprintf(fd, " Suspend count: %d\n", mSuspended);
1842 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1843 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1844 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1845 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08001846 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001847 AudioStreamOut *output = mOutput;
1848 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
1849 String8 flagsAsString = outputFlagsToString(flags);
1850 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n", output, flags, flagsAsString.string());
Andy Hung2c453932016-09-21 12:55:15 -07001851 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
1852 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
1853 if (mPipeSink.get() != nullptr) {
1854 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
1855 }
1856 if (output != nullptr) {
1857 dprintf(fd, " Hal stream dump:\n");
1858 (void)output->stream->common.dump(&output->stream->common, fd);
1859 }
Eric Laurent81784c32012-11-19 14:55:58 -08001860}
1861
1862// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001863
1864void AudioFlinger::PlaybackThread::onFirstRef()
1865{
Glenn Kastend7dca052015-03-05 16:05:54 -08001866 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001867}
1868
1869// ThreadBase virtuals
1870void AudioFlinger::PlaybackThread::preExit()
1871{
1872 ALOGV(" preExit()");
1873 // FIXME this is using hard-coded strings but in the future, this functionality will be
1874 // converted to use audio HAL extensions required to support tunneling
1875 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1876}
1877
1878// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1879sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1880 const sp<AudioFlinger::Client>& client,
1881 audio_stream_type_t streamType,
1882 uint32_t sampleRate,
1883 audio_format_t format,
1884 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001885 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001886 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08001887 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07001888 audio_output_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08001889 pid_t tid,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001890 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -08001891 status_t *status)
1892{
Glenn Kasten74935e42013-12-19 08:56:45 -08001893 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001894 sp<Track> track;
1895 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07001896 audio_output_flags_t outputFlags = mOutput->flags;
1897
1898 // special case for FAST flag considered OK if fast mixer is present
1899 if (hasFastMixer()) {
1900 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
1901 }
1902
1903 // Check if requested flags are compatible with output stream flags
1904 if ((*flags & outputFlags) != *flags) {
1905 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
1906 *flags, outputFlags);
1907 *flags = (audio_output_flags_t)(*flags & outputFlags);
1908 }
Eric Laurent81784c32012-11-19 14:55:58 -08001909
Eric Laurent81784c32012-11-19 14:55:58 -08001910 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07001911 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08001912 if (
Eric Laurent81784c32012-11-19 14:55:58 -08001913 // PCM data
1914 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001915 // TODO: extract as a data library function that checks that a computationally
1916 // expensive downmixer is not required: isFastOutputChannelConversion()
Andy Hung9a592762014-07-21 21:56:01 -07001917 (channelMask == mChannelMask ||
Andy Hung1f439e12015-05-19 12:57:41 -07001918 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1919 (channelMask == AUDIO_CHANNEL_OUT_MONO
1920 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001921 // hardware sample rate
1922 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001923 // normal mixer has an associated fast mixer
1924 hasFastMixer() &&
1925 // there are sufficient fast track slots available
1926 (mFastTrackAvailMask != 0)
1927 // FIXME test that MixerThread for this fast track has a capable output HAL
1928 // FIXME add a permission test also?
1929 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07001930 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
1931 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001932 // read the fast track multiplier property the first time it is needed
1933 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1934 if (ok != 0) {
1935 ALOGE("%s pthread_once failed: %d", __func__, ok);
1936 }
Andy Hunge0a269a2016-03-23 15:13:42 -07001937 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08001938 }
Eric Laurent4c415062016-06-17 16:14:16 -07001939
1940 // check compatibility with audio effects.
1941 { // scope for mLock
1942 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07001943 for (audio_session_t session : {
1944 AUDIO_SESSION_OUTPUT_STAGE,
1945 AUDIO_SESSION_OUTPUT_MIX,
1946 sessionId,
1947 }) {
1948 sp<EffectChain> chain = getEffectChain_l(session);
1949 if (chain.get() != nullptr) {
1950 audio_output_flags_t old = *flags;
1951 chain->checkOutputFlagCompatibility(flags);
1952 if (old != *flags) {
1953 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
1954 (int)session, (int)old, (int)*flags);
1955 }
Eric Laurent4c415062016-06-17 16:14:16 -07001956 }
1957 }
1958 }
Eric Laurent122f7e72016-06-29 11:53:29 -07001959 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07001960 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
1961 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08001962 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001963 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
1964 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07001965 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001966 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08001967 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001968 audio_is_linear_pcm(format),
1969 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07001970 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08001971 }
1972 }
1973 // For normal PCM streaming tracks, update minimum frame count.
1974 // For compatibility with AudioTrack calculation, buffer depth is forced
1975 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1976 // This is probably too conservative, but legacy application code may depend on it.
1977 // If you change this calculation, also review the start threshold which is related.
Eric Laurent05067782016-06-01 18:27:28 -07001978 if (!(*flags & AUDIO_OUTPUT_FLAG_FAST)
Phil Burkfdb3c072016-02-09 10:47:02 -08001979 && audio_has_proportional_frames(format) && sharedBuffer == 0) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001980 // this must match AudioTrack.cpp calculateMinFrameCount().
1981 // TODO: Move to a common library
Eric Laurent81784c32012-11-19 14:55:58 -08001982 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1983 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1984 if (minBufCount < 2) {
1985 minBufCount = 2;
1986 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07001987 // For normal mixing tracks, if speed is > 1.0f (normal), AudioTrack
1988 // or the client should compute and pass in a larger buffer request.
Andy Hung0e48d252015-01-26 11:43:15 -08001989 size_t minFrameCount =
Andy Hung8edb8dc2015-03-26 19:13:55 -07001990 minBufCount * sourceFramesNeededWithTimestretch(
1991 sampleRate, mNormalFrameCount,
1992 mSampleRate, AUDIO_TIMESTRETCH_SPEED_NORMAL /*speed*/);
Andy Hung0e48d252015-01-26 11:43:15 -08001993 if (frameCount < minFrameCount) { // including frameCount == 0
Eric Laurent81784c32012-11-19 14:55:58 -08001994 frameCount = minFrameCount;
1995 }
Eric Laurent81784c32012-11-19 14:55:58 -08001996 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001997 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001998
Glenn Kastenc3df8382014-03-13 15:05:25 -07001999 switch (mType) {
2000
2001 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002002 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002003 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002004 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2005 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002006 sampleRate, format, channelMask, mOutput, mFormat);
2007 lStatus = BAD_VALUE;
2008 goto Exit;
2009 }
2010 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002011 break;
2012
2013 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002014 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002015 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2016 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002017 sampleRate, format, channelMask, mOutput, mFormat);
2018 lStatus = BAD_VALUE;
2019 goto Exit;
2020 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002021 break;
2022
2023 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002024 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002025 ALOGE("createTrack_l() Bad parameter: format %#x \""
2026 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002027 format, mOutput, mFormat);
2028 lStatus = BAD_VALUE;
2029 goto Exit;
2030 }
Andy Hungcd044842014-08-07 11:04:34 -07002031 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002032 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2033 lStatus = BAD_VALUE;
2034 goto Exit;
2035 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002036 break;
2037
Eric Laurent81784c32012-11-19 14:55:58 -08002038 }
2039
2040 lStatus = initCheck();
2041 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002042 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002043 goto Exit;
2044 }
2045
2046 { // scope for mLock
2047 Mutex::Autolock _l(mLock);
2048
2049 // all tracks in same audio session must share the same routing strategy otherwise
2050 // conflicts will happen when tracks are moved from one output to another by audio policy
2051 // manager
2052 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
2053 for (size_t i = 0; i < mTracks.size(); ++i) {
2054 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002055 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002056 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
2057 if (sessionId == t->sessionId() && strategy != actual) {
2058 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2059 strategy, actual);
2060 lStatus = BAD_VALUE;
2061 goto Exit;
2062 }
2063 }
2064 }
2065
Glenn Kastend79072e2016-01-06 08:41:20 -08002066 track = new Track(this, client, streamType, sampleRate, format,
2067 channelMask, frameCount, NULL, sharedBuffer,
2068 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT);
Glenn Kasten03003332013-08-06 15:40:54 -07002069
Glenn Kasten03003332013-08-06 15:40:54 -07002070 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2071 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002072 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002073 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002074 goto Exit;
2075 }
2076 mTracks.add(track);
2077
2078 sp<EffectChain> chain = getEffectChain_l(sessionId);
2079 if (chain != 0) {
2080 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2081 track->setMainBuffer(chain->inBuffer());
2082 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
2083 chain->incTrackCnt();
2084 }
2085
Eric Laurent05067782016-06-01 18:27:28 -07002086 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002087 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2088 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2089 // so ask activity manager to do this on our behalf
2090 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
2091 }
2092 }
2093
2094 lStatus = NO_ERROR;
2095
2096Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002097 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002098 return track;
2099}
2100
2101uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2102{
2103 return latency;
2104}
2105
2106uint32_t AudioFlinger::PlaybackThread::latency() const
2107{
2108 Mutex::Autolock _l(mLock);
2109 return latency_l();
2110}
2111uint32_t AudioFlinger::PlaybackThread::latency_l() const
2112{
2113 if (initCheck() == NO_ERROR) {
2114 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
2115 } else {
2116 return 0;
2117 }
2118}
2119
2120void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2121{
2122 Mutex::Autolock _l(mLock);
2123 // Don't apply master volume in SW if our HAL can do it for us.
2124 if (mOutput && mOutput->audioHwDev &&
2125 mOutput->audioHwDev->canSetMasterVolume()) {
2126 mMasterVolume = 1.0;
2127 } else {
2128 mMasterVolume = value;
2129 }
2130}
2131
2132void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2133{
2134 Mutex::Autolock _l(mLock);
2135 // Don't apply master mute in SW if our HAL can do it for us.
2136 if (mOutput && mOutput->audioHwDev &&
2137 mOutput->audioHwDev->canSetMasterMute()) {
2138 mMasterMute = false;
2139 } else {
2140 mMasterMute = muted;
2141 }
2142}
2143
2144void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2145{
2146 Mutex::Autolock _l(mLock);
2147 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002148 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002149}
2150
2151void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2152{
2153 Mutex::Autolock _l(mLock);
2154 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002155 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002156}
2157
2158float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2159{
2160 Mutex::Autolock _l(mLock);
2161 return mStreamTypes[stream].volume;
2162}
2163
2164// addTrack_l() must be called with ThreadBase::mLock held
2165status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2166{
2167 status_t status = ALREADY_EXISTS;
2168
Eric Laurent81784c32012-11-19 14:55:58 -08002169 if (mActiveTracks.indexOf(track) < 0) {
2170 // the track is newly added, make sure it fills up all its
2171 // buffers before playing. This is to ensure the client will
2172 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002173 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002174 TrackBase::track_state state = track->mState;
2175 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002176 status = AudioSystem::startOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002177 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002178 mLock.lock();
2179 // abort track was stopped/paused while we released the lock
2180 if (state != track->mState) {
2181 if (status == NO_ERROR) {
2182 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002183 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002184 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002185 mLock.lock();
2186 }
2187 return INVALID_OPERATION;
2188 }
2189 // abort if start is rejected by audio policy manager
2190 if (status != NO_ERROR) {
2191 return PERMISSION_DENIED;
2192 }
2193#ifdef ADD_BATTERY_DATA
2194 // to track the speaker usage
2195 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2196#endif
2197 }
2198
Eric Laurent51716182016-02-29 18:00:56 -08002199 // set retry count for buffer fill
2200 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002201 if (track->isStopping_1()) {
2202 track->mRetryCount = kMaxTrackStopRetriesOffload;
2203 } else {
2204 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2205 }
2206 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002207 } else {
2208 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002209 track->mFillingUpStatus =
2210 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002211 }
2212
Eric Laurent81784c32012-11-19 14:55:58 -08002213 track->mResetDone = false;
2214 track->mPresentationCompleteFrames = 0;
2215 mActiveTracks.add(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002216 mWakeLockUids.add(track->uid());
2217 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07002218 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07002219 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2220 if (chain != 0) {
2221 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2222 track->sessionId());
2223 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002224 }
2225
Andy Hung1f82f952016-11-28 19:01:02 -08002226 char buffer[256];
2227 track->dump(buffer, ARRAY_SIZE(buffer), false /* active */);
2228 mLocalLog.log("addTrack_l (%p) %s", track.get(), buffer + 4); // log for analysis
2229
Eric Laurent81784c32012-11-19 14:55:58 -08002230 status = NO_ERROR;
2231 }
2232
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002233 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002234 return status;
2235}
2236
Eric Laurentbfb1b832013-01-07 09:53:42 -08002237bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002238{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002239 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002240 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002241 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2242 track->mState = TrackBase::STOPPED;
2243 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002244 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002245 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002246 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002247 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002248
2249 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002250}
2251
2252void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2253{
2254 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung1f82f952016-11-28 19:01:02 -08002255
2256 char buffer[256];
2257 track->dump(buffer, ARRAY_SIZE(buffer), false /* active */);
2258 mLocalLog.log("removeTrack_l (%p) %s", track.get(), buffer + 4); // log for analysis
2259
Eric Laurent81784c32012-11-19 14:55:58 -08002260 mTracks.remove(track);
2261 deleteTrackName_l(track->name());
2262 // redundant as track is about to be destroyed, for dumpsys only
2263 track->mName = -1;
2264 if (track->isFastTrack()) {
2265 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002266 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002267 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2268 mFastTrackAvailMask |= 1 << index;
2269 // redundant as track is about to be destroyed, for dumpsys only
2270 track->mFastIndex = -1;
2271 }
2272 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2273 if (chain != 0) {
2274 chain->decTrackCnt();
2275 }
2276}
2277
Eric Laurentede6c3b2013-09-19 14:37:46 -07002278void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002279{
2280 // Thread could be blocked waiting for async
2281 // so signal it to handle state changes immediately
2282 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
2283 // be lost so we also flag to prevent it blocking on mWaitWorkCV
2284 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002285 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002286}
2287
Eric Laurent81784c32012-11-19 14:55:58 -08002288String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2289{
Eric Laurent81784c32012-11-19 14:55:58 -08002290 Mutex::Autolock _l(mLock);
2291 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07002292 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002293 }
2294
Glenn Kastend8ea6992013-07-16 14:17:15 -07002295 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
2296 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08002297 free(s);
2298 return out_s8;
2299}
2300
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002301void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002302 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2303 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002304
Eric Laurent73e26b62015-04-27 16:55:58 -07002305 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002306
2307 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002308 case AUDIO_OUTPUT_OPENED:
2309 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002310 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002311 desc->mChannelMask = mChannelMask;
2312 desc->mSamplingRate = mSampleRate;
2313 desc->mFormat = mFormat;
2314 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002315 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002316 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002317 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002318 break;
2319
Eric Laurent73e26b62015-04-27 16:55:58 -07002320 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002321 default:
2322 break;
2323 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002324 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002325}
2326
Eric Laurentbfb1b832013-01-07 09:53:42 -08002327void AudioFlinger::PlaybackThread::writeCallback()
2328{
2329 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002330 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002331}
2332
2333void AudioFlinger::PlaybackThread::drainCallback()
2334{
2335 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002336 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002337}
2338
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002339void AudioFlinger::PlaybackThread::errorCallback()
2340{
2341 ALOG_ASSERT(mCallbackThread != 0);
2342 mCallbackThread->setAsyncError();
2343}
2344
Eric Laurent3b4529e2013-09-05 18:09:19 -07002345void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002346{
2347 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002348 // reject out of sequence requests
2349 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2350 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002351 mWaitWorkCV.signal();
2352 }
2353}
2354
Eric Laurent3b4529e2013-09-05 18:09:19 -07002355void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002356{
2357 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002358 // reject out of sequence requests
2359 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
2360 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002361 mWaitWorkCV.signal();
2362 }
2363}
2364
2365// static
2366int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
Glenn Kasten0f11b512014-01-31 16:18:54 -08002367 void *param __unused,
Eric Laurentbfb1b832013-01-07 09:53:42 -08002368 void *cookie)
2369{
2370 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
2371 ALOGV("asyncCallback() event %d", event);
2372 switch (event) {
2373 case STREAM_CBK_EVENT_WRITE_READY:
2374 me->writeCallback();
2375 break;
2376 case STREAM_CBK_EVENT_DRAIN_READY:
2377 me->drainCallback();
2378 break;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002379 case STREAM_CBK_EVENT_ERROR:
2380 me->errorCallback();
2381 break;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002382 default:
2383 ALOGW("asyncCallback() unknown event %d", event);
2384 break;
2385 }
2386 return 0;
2387}
2388
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002389void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002390{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002391 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002392 mSampleRate = mOutput->getSampleRate();
2393 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002394 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002395 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002396 }
Andy Hung9a592762014-07-21 21:56:01 -07002397 if ((mType == MIXER || mType == DUPLICATING)
2398 && !isValidPcmSinkChannelMask(mChannelMask)) {
2399 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2400 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002401 }
Andy Hunge5412692014-05-16 11:25:07 -07002402 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002403
2404 // Get actual HAL format.
Andy Hung463be252014-07-10 16:56:07 -07002405 mHALFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Phil Burkca5e6142015-07-14 09:42:29 -07002406 // Get format from the shim, which will be different than the HAL format
2407 // if playing compressed audio over HDMI passthrough.
2408 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002409 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002410 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002411 }
Andy Hung6146c082014-03-18 11:56:15 -07002412 if ((mType == MIXER || mType == DUPLICATING)
2413 && !isValidPcmSinkFormat(mFormat)) {
2414 LOG_FATAL("HAL format %#x not supported for mixed output",
2415 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002416 }
Phil Burk062e67a2015-02-11 13:40:50 -08002417 mFrameSize = mOutput->getFrameSize();
Glenn Kasten70949c42013-08-06 07:40:12 -07002418 mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
2419 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002420 if (mFrameCount & 15) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002421 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002422 mFrameCount);
2423 }
2424
Eric Laurentbfb1b832013-01-07 09:53:42 -08002425 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
2426 (mOutput->stream->set_callback != NULL)) {
2427 if (mOutput->stream->set_callback(mOutput->stream,
2428 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
2429 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002430 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002431 }
2432 }
2433
Eric Laurentd1f69b02014-12-15 14:33:13 -08002434 mHwSupportsPause = false;
2435 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
2436 if (mOutput->stream->pause != NULL) {
2437 if (mOutput->stream->resume != NULL) {
2438 mHwSupportsPause = true;
2439 } else {
2440 ALOGW("direct output implements pause but not resume");
2441 }
2442 } else if (mOutput->stream->resume != NULL) {
2443 ALOGW("direct output implements resume but not pause");
2444 }
2445 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002446 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2447 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2448 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002449
Andy Hungfbfc3952015-01-15 13:33:51 -08002450 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2451 // For best precision, we use float instead of the associated output
2452 // device format (typically PCM 16 bit).
2453
2454 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2455 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2456 mBufferSize = mFrameSize * mFrameCount;
2457
2458 // TODO: We currently use the associated output device channel mask and sample rate.
2459 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2460 // (if a valid mask) to avoid premature downmix.
2461 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2462 // instead of the output device sample rate to avoid loss of high frequency information.
2463 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2464 }
2465
Andy Hung09a50072014-02-27 14:30:47 -08002466 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002467 double multiplier = 1.0;
2468 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2469 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002470 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2471 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002472
Eric Laurent81784c32012-11-19 14:55:58 -08002473 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2474 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2475 maxNormalFrameCount = maxNormalFrameCount & ~15;
2476 if (maxNormalFrameCount < minNormalFrameCount) {
2477 maxNormalFrameCount = minNormalFrameCount;
2478 }
2479 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2480 if (multiplier <= 1.0) {
2481 multiplier = 1.0;
2482 } else if (multiplier <= 2.0) {
2483 if (2 * mFrameCount <= maxNormalFrameCount) {
2484 multiplier = 2.0;
2485 } else {
2486 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2487 }
2488 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002489 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002490 }
2491 }
2492 mNormalFrameCount = multiplier * mFrameCount;
2493 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002494 if (mType == MIXER || mType == DUPLICATING) {
2495 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2496 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002497 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002498 mNormalFrameCount);
2499
Andy Hung08fb1742015-05-31 23:22:10 -07002500 // Check if we want to throttle the processing to no more than 2x normal rate
2501 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002502 mThreadThrottleTimeMs = 0;
2503 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002504 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2505
Andy Hung010a1a12014-03-13 13:57:33 -07002506 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2507 // Originally this was int16_t[] array, need to remove legacy implications.
2508 free(mSinkBuffer);
2509 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002510 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2511 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2512 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002513 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002514
Andy Hung69aed5f2014-02-25 17:24:40 -08002515 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2516 // drives the output.
2517 free(mMixerBuffer);
2518 mMixerBuffer = NULL;
2519 if (mMixerBufferEnabled) {
2520 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2521 mMixerBufferSize = mNormalFrameCount * mChannelCount
2522 * audio_bytes_per_sample(mMixerBufferFormat);
2523 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2524 }
Andy Hung98ef9782014-03-04 14:46:50 -08002525 free(mEffectBuffer);
2526 mEffectBuffer = NULL;
2527 if (mEffectBufferEnabled) {
2528 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2529 mEffectBufferSize = mNormalFrameCount * mChannelCount
2530 * audio_bytes_per_sample(mEffectBufferFormat);
2531 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2532 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002533
Eric Laurent81784c32012-11-19 14:55:58 -08002534 // force reconfiguration of effect chains and engines to take new buffer size and audio
2535 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002536 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002537 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2538 // matter.
2539 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2540 Vector< sp<EffectChain> > effectChains = mEffectChains;
2541 for (size_t i = 0; i < effectChains.size(); i ++) {
2542 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2543 }
2544}
2545
2546
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002547status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002548{
2549 if (halFrames == NULL || dspFrames == NULL) {
2550 return BAD_VALUE;
2551 }
2552 Mutex::Autolock _l(mLock);
2553 if (initCheck() != NO_ERROR) {
2554 return INVALID_OPERATION;
2555 }
Andy Hung818e7a32016-02-16 18:08:07 -08002556 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002557 *halFrames = framesWritten;
2558
2559 if (isSuspended()) {
2560 // return an estimation of rendered frames when the output is suspended
2561 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002562 *dspFrames = (uint32_t)
2563 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002564 return NO_ERROR;
2565 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002566 status_t status;
2567 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002568 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002569 *dspFrames = (size_t)frames;
2570 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002571 }
2572}
2573
Eric Laurent4c415062016-06-17 16:14:16 -07002574// hasAudioSession_l() must be called with ThreadBase::mLock held
2575uint32_t AudioFlinger::PlaybackThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08002576{
Eric Laurent81784c32012-11-19 14:55:58 -08002577 uint32_t result = 0;
2578 if (getEffectChain_l(sessionId) != 0) {
2579 result = EFFECT_SESSION;
2580 }
2581
2582 for (size_t i = 0; i < mTracks.size(); ++i) {
2583 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002584 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002585 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07002586 if (track->isFastTrack()) {
2587 result |= FAST_SESSION;
2588 }
Eric Laurent81784c32012-11-19 14:55:58 -08002589 break;
2590 }
2591 }
2592
2593 return result;
2594}
2595
Glenn Kastend848eb42016-03-08 13:42:11 -08002596uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08002597{
2598 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2599 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2600 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2601 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2602 }
2603 for (size_t i = 0; i < mTracks.size(); i++) {
2604 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002605 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002606 return AudioSystem::getStrategyForStream(track->streamType());
2607 }
2608 }
2609 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2610}
2611
2612
Phil Burk062e67a2015-02-11 13:40:50 -08002613AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002614{
2615 Mutex::Autolock _l(mLock);
2616 return mOutput;
2617}
2618
Phil Burk062e67a2015-02-11 13:40:50 -08002619AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002620{
2621 Mutex::Autolock _l(mLock);
2622 AudioStreamOut *output = mOutput;
2623 mOutput = NULL;
2624 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2625 // must push a NULL and wait for ack
2626 mOutputSink.clear();
2627 mPipeSink.clear();
2628 mNormalSink.clear();
2629 return output;
2630}
2631
2632// this method must always be called either with ThreadBase mLock held or inside the thread loop
2633audio_stream_t* AudioFlinger::PlaybackThread::stream() const
2634{
2635 if (mOutput == NULL) {
2636 return NULL;
2637 }
2638 return &mOutput->stream->common;
2639}
2640
2641uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2642{
2643 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2644}
2645
2646status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2647{
2648 if (!isValidSyncEvent(event)) {
2649 return BAD_VALUE;
2650 }
2651
2652 Mutex::Autolock _l(mLock);
2653
2654 for (size_t i = 0; i < mTracks.size(); ++i) {
2655 sp<Track> track = mTracks[i];
2656 if (event->triggerSession() == track->sessionId()) {
2657 (void) track->setSyncEvent(event);
2658 return NO_ERROR;
2659 }
2660 }
2661
2662 return NAME_NOT_FOUND;
2663}
2664
2665bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2666{
2667 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2668}
2669
2670void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2671 const Vector< sp<Track> >& tracksToRemove)
2672{
2673 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002674 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002675 for (size_t i = 0 ; i < count ; i++) {
2676 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002677 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002678 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002679 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002680#ifdef ADD_BATTERY_DATA
2681 // to track the speaker usage
2682 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2683#endif
2684 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002685 AudioSystem::releaseOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002686 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002687 }
Eric Laurent81784c32012-11-19 14:55:58 -08002688 }
2689 }
2690 }
Eric Laurent81784c32012-11-19 14:55:58 -08002691}
2692
2693void AudioFlinger::PlaybackThread::checkSilentMode_l()
2694{
2695 if (!mMasterMute) {
2696 char value[PROPERTY_VALUE_MAX];
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07002697 if (mOutDevice == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) {
2698 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
2699 return;
2700 }
Eric Laurent81784c32012-11-19 14:55:58 -08002701 if (property_get("ro.audio.silent", value, "0") > 0) {
2702 char *endptr;
2703 unsigned long ul = strtoul(value, &endptr, 0);
2704 if (*endptr == '\0' && ul != 0) {
2705 ALOGD("Silence is golden");
2706 // The setprop command will not allow a property to be changed after
2707 // the first time it is set, so we don't have to worry about un-muting.
2708 setMasterMute_l(true);
2709 }
2710 }
2711 }
2712}
2713
2714// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002715ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002716{
Eric Laurent81784c32012-11-19 14:55:58 -08002717 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002718 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002719 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002720
2721 // If an NBAIO sink is present, use it to write the normal mixer's submix
2722 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002723
Andy Hung010a1a12014-03-13 13:57:33 -07002724 const size_t count = mBytesRemaining / mFrameSize;
2725
Simon Wilson2d590962012-11-29 15:18:50 -08002726 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002727 // update the setpoint when AudioFlinger::mScreenState changes
2728 uint32_t screenState = AudioFlinger::mScreenState;
2729 if (screenState != mScreenState) {
2730 mScreenState = screenState;
2731 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2732 if (pipe != NULL) {
2733 pipe->setAvgFrames((mScreenState & 1) ?
2734 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2735 }
2736 }
Andy Hung010a1a12014-03-13 13:57:33 -07002737 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002738 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002739 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002740 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002741 } else {
2742 bytesWritten = framesWritten;
2743 }
2744 // otherwise use the HAL / AudioStreamOut directly
2745 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002746 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002747
Eric Laurentbfb1b832013-01-07 09:53:42 -08002748 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002749 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2750 mWriteAckSequence += 2;
2751 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002752 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002753 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002754 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002755 // FIXME We should have an implementation of timestamps for direct output threads.
2756 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002757 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurent51716182016-02-29 18:00:56 -08002758
Eric Laurentbfb1b832013-01-07 09:53:42 -08002759 if (mUseAsyncWrite &&
2760 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2761 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002762 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002763 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002764 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002765 }
Eric Laurent81784c32012-11-19 14:55:58 -08002766 }
2767
Eric Laurent81784c32012-11-19 14:55:58 -08002768 mNumWrites++;
2769 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002770 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002771 return bytesWritten;
2772}
2773
2774void AudioFlinger::PlaybackThread::threadLoop_drain()
2775{
2776 if (mOutput->stream->drain) {
2777 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2778 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002779 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2780 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002781 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002782 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002783 }
2784 mOutput->stream->drain(mOutput->stream,
2785 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2786 : AUDIO_DRAIN_ALL);
2787 }
2788}
2789
2790void AudioFlinger::PlaybackThread::threadLoop_exit()
2791{
Eric Laurent275e8e92014-11-30 15:14:47 -08002792 {
2793 Mutex::Autolock _l(mLock);
2794 for (size_t i = 0; i < mTracks.size(); i++) {
2795 sp<Track> track = mTracks[i];
2796 track->invalidate();
2797 }
2798 }
Eric Laurent81784c32012-11-19 14:55:58 -08002799}
2800
2801/*
2802The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002803 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002804 - mActiveSleepTimeUs from activeSleepTimeUs()
2805 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08002806 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
2807 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08002808 - maxPeriod from frame count and sample rate (MIXER only)
2809
2810The parameters that affect these derived values are:
2811 - frame count
2812 - frame size
2813 - sample rate
2814 - device type: A2DP or not
2815 - device latency
2816 - format: PCM or not
2817 - active sleep time
2818 - idle sleep time
2819*/
2820
2821void AudioFlinger::PlaybackThread::cacheParameters_l()
2822{
Andy Hung25c2dac2014-02-27 14:56:00 -08002823 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002824 mActiveSleepTimeUs = activeSleepTimeUs();
2825 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08002826
2827 // make sure standby delay is not too short when connected to an A2DP sink to avoid
2828 // truncating audio when going to standby.
2829 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
2830 if ((mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != 0) {
2831 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
2832 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
2833 }
2834 }
Eric Laurent81784c32012-11-19 14:55:58 -08002835}
2836
Eric Laurent13084622016-05-17 10:51:49 -07002837bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08002838{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002839 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08002840 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07002841 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002842 size_t size = mTracks.size();
2843 for (size_t i = 0; i < size; i++) {
2844 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07002845 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002846 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07002847 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002848 }
2849 }
Eric Laurent13084622016-05-17 10:51:49 -07002850 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08002851}
2852
Haynes Mathew George05317d22016-05-03 16:34:26 -07002853void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2854{
2855 Mutex::Autolock _l(mLock);
2856 invalidateTracks_l(streamType);
2857}
2858
Eric Laurent81784c32012-11-19 14:55:58 -08002859status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2860{
Glenn Kastend848eb42016-03-08 13:42:11 -08002861 audio_session_t session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002862 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2863 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002864 bool ownsBuffer = false;
2865
2866 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Glenn Kastend848eb42016-03-08 13:42:11 -08002867 if (session > AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002868 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002869 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002870 if (mType != DIRECT) {
2871 size_t numSamples = mNormalFrameCount * mChannelCount;
2872 buffer = new int16_t[numSamples];
2873 memset(buffer, 0, numSamples * sizeof(int16_t));
2874 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2875 ownsBuffer = true;
2876 }
2877
2878 // Attach all tracks with same session ID to this chain.
2879 for (size_t i = 0; i < mTracks.size(); ++i) {
2880 sp<Track> track = mTracks[i];
2881 if (session == track->sessionId()) {
2882 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2883 buffer);
2884 track->setMainBuffer(buffer);
2885 chain->incTrackCnt();
2886 }
2887 }
2888
2889 // indicate all active tracks in the chain
2890 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2891 sp<Track> track = mActiveTracks[i].promote();
2892 if (track == 0) {
2893 continue;
2894 }
2895 if (session == track->sessionId()) {
2896 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2897 chain->incActiveTrackCnt();
2898 }
2899 }
2900 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002901 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08002902 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002903 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2904 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002905 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Glenn Kastend848eb42016-03-08 13:42:11 -08002906 // chains list in order to be processed last as it contains output stage effects.
Eric Laurent81784c32012-11-19 14:55:58 -08002907 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2908 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08002909 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08002910 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08002911 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08002912 // Effect chain for other sessions are inserted at beginning of effect
2913 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08002914 // sessions is not important.
2915 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
2916 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX,
2917 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08002918 size_t size = mEffectChains.size();
2919 size_t i = 0;
2920 for (i = 0; i < size; i++) {
2921 if (mEffectChains[i]->sessionId() < session) {
2922 break;
2923 }
2924 }
2925 mEffectChains.insertAt(chain, i);
2926 checkSuspendOnAddEffectChain_l(chain);
2927
2928 return NO_ERROR;
2929}
2930
2931size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2932{
Glenn Kastend848eb42016-03-08 13:42:11 -08002933 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08002934
2935 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2936
2937 for (size_t i = 0; i < mEffectChains.size(); i++) {
2938 if (chain == mEffectChains[i]) {
2939 mEffectChains.removeAt(i);
2940 // detach all active tracks from the chain
2941 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2942 sp<Track> track = mActiveTracks[i].promote();
2943 if (track == 0) {
2944 continue;
2945 }
2946 if (session == track->sessionId()) {
2947 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2948 chain.get(), session);
2949 chain->decActiveTrackCnt();
2950 }
2951 }
2952
2953 // detach all tracks with same session ID from this chain
2954 for (size_t i = 0; i < mTracks.size(); ++i) {
2955 sp<Track> track = mTracks[i];
2956 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002957 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002958 chain->decTrackCnt();
2959 }
2960 }
2961 break;
2962 }
2963 }
2964 return mEffectChains.size();
2965}
2966
2967status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2968 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2969{
2970 Mutex::Autolock _l(mLock);
2971 return attachAuxEffect_l(track, EffectId);
2972}
2973
2974status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2975 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2976{
2977 status_t status = NO_ERROR;
2978
2979 if (EffectId == 0) {
2980 track->setAuxBuffer(0, NULL);
2981 } else {
2982 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2983 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2984 if (effect != 0) {
2985 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2986 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2987 } else {
2988 status = INVALID_OPERATION;
2989 }
2990 } else {
2991 status = BAD_VALUE;
2992 }
2993 }
2994 return status;
2995}
2996
2997void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2998{
2999 for (size_t i = 0; i < mTracks.size(); ++i) {
3000 sp<Track> track = mTracks[i];
3001 if (track->auxEffectId() == effectId) {
3002 attachAuxEffect_l(track, 0);
3003 }
3004 }
3005}
3006
3007bool AudioFlinger::PlaybackThread::threadLoop()
3008{
3009 Vector< sp<Track> > tracksToRemove;
3010
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003011 mStandbyTimeNs = systemTime();
Andy Hung69488c42016-05-16 18:43:33 -07003012 nsecs_t lastWriteFinished = -1; // time last server write completed
3013 int64_t lastFramesWritten = -1; // track changes in timestamp server frames written
Eric Laurent81784c32012-11-19 14:55:58 -08003014
3015 // MIXER
3016 nsecs_t lastWarning = 0;
3017
3018 // DUPLICATING
3019 // FIXME could this be made local to while loop?
3020 writeFrames = 0;
3021
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003022 int lastGeneration = 0;
3023
Eric Laurent81784c32012-11-19 14:55:58 -08003024 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003025 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003026
3027 if (mType == MIXER) {
3028 sleepTimeShift = 0;
3029 }
3030
3031 CpuStats cpuStats;
3032 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3033
3034 acquireWakeLock();
3035
Glenn Kasten9e58b552013-01-18 15:09:48 -08003036 // mNBLogWriter->log can only be called while thread mutex mLock is held.
3037 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3038 // and then that string will be logged at the next convenient opportunity.
3039 const char *logString = NULL;
3040
Eric Laurent664539d2013-09-23 18:24:31 -07003041 checkSilentMode_l();
3042
Eric Laurent81784c32012-11-19 14:55:58 -08003043 while (!exitPending())
3044 {
3045 cpuStats.sample(myName);
3046
3047 Vector< sp<EffectChain> > effectChains;
3048
Eric Laurent81784c32012-11-19 14:55:58 -08003049 { // scope for mLock
3050
3051 Mutex::Autolock _l(mLock);
3052
Eric Laurent021cf962014-05-13 10:18:14 -07003053 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07003054
Glenn Kasten9e58b552013-01-18 15:09:48 -08003055 if (logString != NULL) {
3056 mNBLogWriter->logTimestamp();
3057 mNBLogWriter->log(logString);
3058 logString = NULL;
3059 }
3060
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003061 // Gather the framesReleased counters for all active tracks,
Andy Hunge10393e2015-06-12 13:59:33 -07003062 // and associate with the sink frames written out. We need
3063 // this to convert the sink timestamp to the track timestamp.
Andy Hung69488c42016-05-16 18:43:33 -07003064 bool kernelLocationUpdate = false;
Andy Hunge10393e2015-06-12 13:59:33 -07003065 if (mNormalSink != 0) {
Andy Hungc54b1ff2016-02-23 14:07:07 -08003066 // Note: The DuplicatingThread may not have a mNormalSink.
Andy Hung818e7a32016-02-16 18:08:07 -08003067 // We always fetch the timestamp here because often the downstream
Andy Hung69488c42016-05-16 18:43:33 -07003068 // sink will block while writing.
Andy Hung818e7a32016-02-16 18:08:07 -08003069 ExtendedTimestamp timestamp; // use private copy to fetch
3070 (void) mNormalSink->getTimestamp(timestamp);
Andy Hung6d7b1192016-05-07 22:59:48 -07003071
3072 // We keep track of the last valid kernel position in case we are in underrun
3073 // and the normal mixer period is the same as the fast mixer period, or there
3074 // is some error from the HAL.
3075 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3076 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3077 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
3078 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3079 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
3080
3081 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3082 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
3083 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3084 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
Andy Hung69488c42016-05-16 18:43:33 -07003085 }
3086
3087 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3088 kernelLocationUpdate = true;
Andy Hung6d7b1192016-05-07 22:59:48 -07003089 } else {
Eric Laurent122f7e72016-06-29 11:53:29 -07003090 ALOGVV("getTimestamp error - no valid kernel position");
Andy Hung6d7b1192016-05-07 22:59:48 -07003091 }
3092
Andy Hung818e7a32016-02-16 18:08:07 -08003093 // copy over kernel info
3094 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
Andy Hung238fa3d2016-07-28 10:53:22 -07003095 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3096 + mSuspendedFrames; // add frames discarded when suspended
Andy Hung818e7a32016-02-16 18:08:07 -08003097 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
3098 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hungc54b1ff2016-02-23 14:07:07 -08003099 }
3100 // mFramesWritten for non-offloaded tracks are contiguous
3101 // even after standby() is called. This is useful for the track frame
3102 // to sink frame mapping.
Andy Hung69488c42016-05-16 18:43:33 -07003103 bool serverLocationUpdate = false;
3104 if (mFramesWritten != lastFramesWritten) {
3105 serverLocationUpdate = true;
3106 lastFramesWritten = mFramesWritten;
3107 }
3108 // Only update timestamps if there is a meaningful change.
3109 // Either the kernel timestamp must be valid or we have written something.
3110 if (kernelLocationUpdate || serverLocationUpdate) {
3111 if (serverLocationUpdate) {
3112 // use the time before we called the HAL write - it is a bit more accurate
3113 // to when the server last read data than the current time here.
3114 //
3115 // If we haven't written anything, mLastWriteTime will be -1
3116 // and we use systemTime().
3117 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
3118 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastWriteTime == -1
3119 ? systemTime() : mLastWriteTime;
3120 }
3121 const size_t size = mActiveTracks.size();
3122 for (size_t i = 0; i < size; ++i) {
3123 sp<Track> t = mActiveTracks[i].promote();
3124 if (t != 0 && !t->isFastTrack()) {
3125 t->updateTrackFrameInfo(
3126 t->mAudioTrackServerProxy->framesReleased(),
3127 mFramesWritten,
3128 mTimestamp);
3129 }
Andy Hunge10393e2015-06-12 13:59:33 -07003130 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07003131 }
3132
Eric Laurent81784c32012-11-19 14:55:58 -08003133 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003134 if (mSignalPending) {
3135 // A signal was raised while we were unlocked
3136 mSignalPending = false;
3137 } else if (waitingAsyncCallback_l()) {
3138 if (exitPending()) {
3139 break;
3140 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003141 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003142 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003143 releaseWakeLock_l();
3144 released = true;
Mikhail Naganove94c27a2016-08-18 17:31:46 -07003145 mWakeLockUids.clear();
3146 mActiveTracksGeneration++;
Marco Nelissen078538c2015-05-12 09:17:57 -07003147 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003148 ALOGV("wait async completion");
3149 mWaitWorkCV.wait(mLock);
3150 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003151 if (released) {
3152 acquireWakeLock_l();
3153 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003154 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3155 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003156
3157 continue;
3158 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003159 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003160 isSuspended()) {
3161 // put audio hardware into standby after short delay
3162 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003163
3164 threadLoop_standby();
3165
3166 mStandby = true;
3167 }
3168
3169 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
3170 // we're about to wait, flush the binder command buffer
3171 IPCThreadState::self()->flushCommands();
3172
3173 clearOutputTracks();
3174
3175 if (exitPending()) {
3176 break;
3177 }
3178
3179 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003180 mWakeLockUids.clear();
3181 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08003182 // wait until we have something to do...
3183 ALOGV("%s going to sleep", myName.string());
3184 mWaitWorkCV.wait(mLock);
3185 ALOGV("%s waking up", myName.string());
3186 acquireWakeLock_l();
3187
3188 mMixerStatus = MIXER_IDLE;
3189 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3190 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003191 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003192 checkSilentMode_l();
3193
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003194 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3195 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003196 if (mType == MIXER) {
3197 sleepTimeShift = 0;
3198 }
3199
3200 continue;
3201 }
3202 }
Eric Laurent81784c32012-11-19 14:55:58 -08003203 // mMixerStatusIgnoringFastTracks is also updated internally
3204 mMixerStatus = prepareTracks_l(&tracksToRemove);
3205
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003206 // compare with previously applied list
3207 if (lastGeneration != mActiveTracksGeneration) {
3208 // update wakelock
3209 updateWakeLockUids_l(mWakeLockUids);
3210 lastGeneration = mActiveTracksGeneration;
3211 }
3212
Eric Laurent81784c32012-11-19 14:55:58 -08003213 // prevent any changes in effect chain list and in each effect chain
3214 // during mixing and effect process as the audio buffers could be deleted
3215 // or modified if an effect is created or deleted
3216 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003217 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003218
Eric Laurentbfb1b832013-01-07 09:53:42 -08003219 if (mBytesRemaining == 0) {
3220 mCurrentWriteLength = 0;
3221 if (mMixerStatus == MIXER_TRACKS_READY) {
3222 // threadLoop_mix() sets mCurrentWriteLength
3223 threadLoop_mix();
3224 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3225 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003226 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003227 // must be written to HAL
3228 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003229 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003230 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003231 }
3232 }
Andy Hung98ef9782014-03-04 14:46:50 -08003233 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003234 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003235 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3236 // or mSinkBuffer (if there are no effects).
3237 //
3238 // This is done pre-effects computation; if effects change to
3239 // support higher precision, this needs to move.
3240 //
3241 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003242 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003243 if (mMixerBufferValid) {
3244 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3245 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3246
Andy Hung2ddee192015-12-18 17:34:44 -08003247 // mono blend occurs for mixer threads only (not direct or offloaded)
3248 // and is handled here if we're going directly to the sink.
3249 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003250 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3251 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003252 }
3253
Andy Hung98ef9782014-03-04 14:46:50 -08003254 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
3255 mNormalFrameCount * mChannelCount);
3256 }
3257
Eric Laurentbfb1b832013-01-07 09:53:42 -08003258 mBytesRemaining = mCurrentWriteLength;
3259 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003260 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3261 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3262 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3263 mBytesWritten += mBytesRemaining;
3264 mFramesWritten += framesRemaining;
3265 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003266 mBytesRemaining = 0;
3267 }
Eric Laurent81784c32012-11-19 14:55:58 -08003268
Eric Laurentbfb1b832013-01-07 09:53:42 -08003269 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003270 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003271 for (size_t i = 0; i < effectChains.size(); i ++) {
3272 effectChains[i]->process_l();
3273 }
Eric Laurent81784c32012-11-19 14:55:58 -08003274 }
3275 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003276 // Process effect chains for offloaded thread even if no audio
3277 // was read from audio track: process only updates effect state
3278 // and thus does have to be synchronized with audio writes but may have
3279 // to be called while waiting for async write callback
3280 if (mType == OFFLOAD) {
3281 for (size_t i = 0; i < effectChains.size(); i ++) {
3282 effectChains[i]->process_l();
3283 }
3284 }
Eric Laurent81784c32012-11-19 14:55:58 -08003285
Andy Hung98ef9782014-03-04 14:46:50 -08003286 // Only if the Effects buffer is enabled and there is data in the
3287 // Effects buffer (buffer valid), we need to
3288 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003289 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003290 if (mEffectBufferValid) {
3291 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003292
3293 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003294 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3295 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003296 }
3297
Andy Hung98ef9782014-03-04 14:46:50 -08003298 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
3299 mNormalFrameCount * mChannelCount);
3300 }
3301
Eric Laurent81784c32012-11-19 14:55:58 -08003302 // enable changes in effect chain
3303 unlockEffectChains(effectChains);
3304
Eric Laurentbfb1b832013-01-07 09:53:42 -08003305 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003306 // mSleepTimeUs == 0 means we must write to audio hardware
3307 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003308 ssize_t ret = 0;
Andy Hung69488c42016-05-16 18:43:33 -07003309 // We save lastWriteFinished here, as previousLastWriteFinished,
3310 // for throttling. On thread start, previousLastWriteFinished will be
3311 // set to -1, which properly results in no throttling after the first write.
3312 nsecs_t previousLastWriteFinished = lastWriteFinished;
3313 nsecs_t delta = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003314 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003315 // FIXME rewrite to reduce number of system calls
3316 mLastWriteTime = systemTime(); // also used for dumpsys
Andy Hung08fb1742015-05-31 23:22:10 -07003317 ret = threadLoop_write();
Andy Hung69488c42016-05-16 18:43:33 -07003318 lastWriteFinished = systemTime();
3319 delta = lastWriteFinished - mLastWriteTime;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003320 if (ret < 0) {
3321 mBytesRemaining = 0;
3322 } else {
3323 mBytesWritten += ret;
3324 mBytesRemaining -= ret;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003325 mFramesWritten += ret / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003326 }
3327 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3328 (mMixerStatus == MIXER_DRAIN_ALL)) {
3329 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003330 }
Andy Hung08fb1742015-05-31 23:22:10 -07003331 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003332 // write blocked detection
Andy Hung08fb1742015-05-31 23:22:10 -07003333 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003334 mNumDelayedWrites++;
Andy Hung69488c42016-05-16 18:43:33 -07003335 if ((lastWriteFinished - lastWarning) > kWarningThrottleNs) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003336 ATRACE_NAME("underrun");
3337 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003338 (unsigned long long) ns2ms(delta), mNumDelayedWrites, this);
Andy Hung69488c42016-05-16 18:43:33 -07003339 lastWarning = lastWriteFinished;
Glenn Kasten4944acb2013-08-19 08:39:20 -07003340 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003341 }
Andy Hung08fb1742015-05-31 23:22:10 -07003342
3343 if (mThreadThrottle
3344 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
3345 && ret > 0) { // we wrote something
3346 // Limit MixerThread data processing to no more than twice the
3347 // expected processing rate.
3348 //
3349 // This helps prevent underruns with NuPlayer and other applications
3350 // which may set up buffers that are close to the minimum size, or use
3351 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3352 //
3353 // The throttle smooths out sudden large data drains from the device,
3354 // e.g. when it comes out of standby, which often causes problems with
3355 // (1) mixer threads without a fast mixer (which has its own warm-up)
3356 // (2) minimum buffer sized tracks (even if the track is full,
3357 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07003358 //
3359 // Total time spent in last processing cycle equals time spent in
3360 // 1. threadLoop_write, as well as time spent in
3361 // 2. threadLoop_mix (significant for heavy mixing, especially
3362 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07003363
Andy Hung69488c42016-05-16 18:43:33 -07003364 // it's OK if deltaMs is an overestimate.
3365 const int32_t deltaMs =
3366 (lastWriteFinished - previousLastWriteFinished) / 1000000;
Andy Hung08fb1742015-05-31 23:22:10 -07003367 const int32_t throttleMs = mHalfBufferMs - deltaMs;
3368 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3369 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003370 // notify of throttle start on verbose log
3371 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3372 "mixer(%p) throttle begin:"
3373 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003374 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003375 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07003376 // Throttle must be attributed to the previous mixer loop's write time
3377 // to allow back-to-back throttling.
3378 lastWriteFinished += throttleMs * 1000000;
Andy Hung40eb1a12015-06-18 13:42:02 -07003379 } else {
3380 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3381 if (diff > 0) {
3382 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07003383 // but prevent spamming for bluetooth
3384 ALOGD_IF(!audio_is_a2dp_out_device(outDevice()),
3385 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07003386 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3387 }
Andy Hung08fb1742015-05-31 23:22:10 -07003388 }
3389 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003390 }
Eric Laurent81784c32012-11-19 14:55:58 -08003391
Eric Laurentbfb1b832013-01-07 09:53:42 -08003392 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003393 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07003394 Mutex::Autolock _l(mLock);
3395 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
3396 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08003397 }
Glenn Kastene7754022014-10-31 12:11:26 -07003398 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003399 }
Eric Laurent81784c32012-11-19 14:55:58 -08003400 }
3401
3402 // Finally let go of removed track(s), without the lock held
3403 // since we can't guarantee the destructors won't acquire that
3404 // same lock. This will also mutate and push a new fast mixer state.
3405 threadLoop_removeTracks(tracksToRemove);
3406 tracksToRemove.clear();
3407
3408 // FIXME I don't understand the need for this here;
3409 // it was in the original code but maybe the
3410 // assignment in saveOutputTracks() makes this unnecessary?
3411 clearOutputTracks();
3412
3413 // Effect chains will be actually deleted here if they were removed from
3414 // mEffectChains list during mixing or effects processing
3415 effectChains.clear();
3416
3417 // FIXME Note that the above .clear() is no longer necessary since effectChains
3418 // is now local to this block, but will keep it for now (at least until merge done).
3419 }
3420
Eric Laurentbfb1b832013-01-07 09:53:42 -08003421 threadLoop_exit();
3422
Eric Laurentcf817a22014-08-04 20:36:31 -07003423 if (!mStandby) {
3424 threadLoop_standby();
3425 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003426 }
3427
3428 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003429 mWakeLockUids.clear();
3430 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08003431
3432 ALOGV("Thread %p type %d exiting", this, mType);
3433 return false;
3434}
3435
Eric Laurentbfb1b832013-01-07 09:53:42 -08003436// removeTracks_l() must be called with ThreadBase::mLock held
3437void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3438{
3439 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003440 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003441 for (size_t i=0 ; i<count ; i++) {
3442 const sp<Track>& track = tracksToRemove.itemAt(i);
3443 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003444 mWakeLockUids.remove(track->uid());
3445 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003446 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3447 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3448 if (chain != 0) {
3449 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3450 track->sessionId());
3451 chain->decActiveTrackCnt();
3452 }
3453 if (track->isTerminated()) {
3454 removeTrack_l(track);
Andy Hung1f82f952016-11-28 19:01:02 -08003455 } else { // inactive but not terminated
3456 char buffer[256];
3457 track->dump(buffer, ARRAY_SIZE(buffer), false /* active */);
3458 mLocalLog.log("removeTracks_l(%p) %s", track.get(), buffer + 4);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003459 }
3460 }
3461 }
3462
3463}
Eric Laurent81784c32012-11-19 14:55:58 -08003464
Eric Laurentaccc1472013-09-20 09:36:34 -07003465status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3466{
3467 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08003468 ExtendedTimestamp ets;
3469 status_t status = mNormalSink->getTimestamp(ets);
3470 if (status == NO_ERROR) {
3471 status = ets.getBestTimestamp(&timestamp);
3472 }
3473 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07003474 }
Andy Hung9a1c8892014-12-03 11:37:42 -08003475 if ((mType == OFFLOAD || mType == DIRECT)
3476 && mOutput != NULL && mOutput->stream->get_presentation_position) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003477 uint64_t position64;
Phil Burk062e67a2015-02-11 13:40:50 -08003478 int ret = mOutput->getPresentationPosition(&position64, &timestamp.mTime);
Eric Laurentaccc1472013-09-20 09:36:34 -07003479 if (ret == 0) {
3480 timestamp.mPosition = (uint32_t)position64;
3481 return NO_ERROR;
3482 }
3483 }
3484 return INVALID_OPERATION;
3485}
Eric Laurent1c333e22014-05-20 10:48:17 -07003486
Eric Laurent054d9d32015-04-24 08:48:48 -07003487status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3488 audio_patch_handle_t *handle)
3489{
Andy Hungf60abce2016-08-26 11:37:54 -07003490 status_t status;
3491 if (property_get_bool("af.patch_park", false /* default_value */)) {
3492 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3493 // or if HAL does not properly lock against access.
3494 AutoPark<FastMixer> park(mFastMixer);
3495 status = PlaybackThread::createAudioPatch_l(patch, handle);
3496 } else {
3497 status = PlaybackThread::createAudioPatch_l(patch, handle);
3498 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003499 return status;
3500}
3501
Eric Laurent1c333e22014-05-20 10:48:17 -07003502status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3503 audio_patch_handle_t *handle)
3504{
3505 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003506
3507 // store new device and send to effects
3508 audio_devices_t type = AUDIO_DEVICE_NONE;
3509 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3510 type |= patch->sinks[i].ext.device.type;
3511 }
3512
3513#ifdef ADD_BATTERY_DATA
3514 // when changing the audio output device, call addBatteryData to notify
3515 // the change
3516 if (mOutDevice != type) {
3517 uint32_t params = 0;
3518 // check whether speaker is on
3519 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3520 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003521 }
3522
Eric Laurent054d9d32015-04-24 08:48:48 -07003523 audio_devices_t deviceWithoutSpeaker
3524 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3525 // check if any other device (except speaker) is on
3526 if (type & deviceWithoutSpeaker) {
3527 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3528 }
3529
3530 if (params != 0) {
3531 addBatteryData(params);
3532 }
3533 }
3534#endif
3535
3536 for (size_t i = 0; i < mEffectChains.size(); i++) {
3537 mEffectChains[i]->setDevice_l(type);
3538 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003539
3540 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3541 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3542 bool configChanged = mPrevOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003543 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003544 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003545
3546 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003547 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3548 status = hwDevice->create_audio_patch(hwDevice,
3549 patch->num_sources,
3550 patch->sources,
3551 patch->num_sinks,
3552 patch->sinks,
3553 handle);
3554 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003555 char *address;
3556 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3557 //FIXME: we only support address on first sink with HAL version < 3.0
3558 address = audio_device_address_to_parameter(
3559 patch->sinks[0].ext.device.type,
3560 patch->sinks[0].ext.device.address);
3561 } else {
3562 address = (char *)calloc(1, 1);
3563 }
3564 AudioParameter param = AudioParameter(String8(address));
3565 free(address);
3566 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), (int)type);
3567 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3568 param.toString().string());
3569 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003570 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003571 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003572 mPrevOutDevice = type;
Eric Laurente8726fe2015-06-26 09:39:24 -07003573 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3574 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003575 return status;
3576}
3577
Eric Laurent054d9d32015-04-24 08:48:48 -07003578status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3579{
Andy Hungf60abce2016-08-26 11:37:54 -07003580 status_t status;
3581 if (property_get_bool("af.patch_park", false /* default_value */)) {
3582 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3583 // or if HAL does not properly lock against access.
3584 AutoPark<FastMixer> park(mFastMixer);
3585 status = PlaybackThread::releaseAudioPatch_l(handle);
3586 } else {
3587 status = PlaybackThread::releaseAudioPatch_l(handle);
3588 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003589 return status;
3590}
3591
Eric Laurent1c333e22014-05-20 10:48:17 -07003592status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3593{
3594 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003595
3596 mOutDevice = AUDIO_DEVICE_NONE;
3597
Eric Laurent1c333e22014-05-20 10:48:17 -07003598 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
3599 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3600 status = hwDevice->release_audio_patch(hwDevice, handle);
3601 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003602 AudioParameter param;
3603 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
3604 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3605 param.toString().string());
Eric Laurent1c333e22014-05-20 10:48:17 -07003606 }
3607 return status;
3608}
3609
Eric Laurent83b88082014-06-20 18:31:16 -07003610void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3611{
3612 Mutex::Autolock _l(mLock);
3613 mTracks.add(track);
3614}
3615
3616void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3617{
3618 Mutex::Autolock _l(mLock);
3619 destroyTrack_l(track);
3620}
3621
3622void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3623{
3624 ThreadBase::getAudioPortConfig(config);
3625 config->role = AUDIO_PORT_ROLE_SOURCE;
3626 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3627 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3628}
3629
Eric Laurent81784c32012-11-19 14:55:58 -08003630// ----------------------------------------------------------------------------
3631
3632AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003633 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3634 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003635 // mAudioMixer below
3636 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08003637 mFastMixerFutex(0),
3638 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08003639 // mOutputSink below
3640 // mPipeSink below
3641 // mNormalSink below
3642{
3643 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003644 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%zu, "
3645 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003646 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3647 mNormalFrameCount);
3648 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3649
Andy Hungfbfc3952015-01-15 13:33:51 -08003650 if (type == DUPLICATING) {
3651 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3652 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3653 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3654 return;
3655 }
Eric Laurent81784c32012-11-19 14:55:58 -08003656 // create an NBAIO sink for the HAL output stream, and negotiate
3657 mOutputSink = new AudioStreamOutSink(output->stream);
3658 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003659 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003660#if !LOG_NDEBUG
3661 ssize_t index =
3662#else
3663 (void)
3664#endif
3665 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003666 ALOG_ASSERT(index == 0);
3667
3668 // initialize fast mixer depending on configuration
3669 bool initFastMixer;
3670 switch (kUseFastMixer) {
3671 case FastMixer_Never:
3672 initFastMixer = false;
3673 break;
3674 case FastMixer_Always:
3675 initFastMixer = true;
3676 break;
3677 case FastMixer_Static:
3678 case FastMixer_Dynamic:
3679 initFastMixer = mFrameCount < mNormalFrameCount;
3680 break;
3681 }
3682 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003683 audio_format_t fastMixerFormat;
3684 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3685 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3686 } else {
3687 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3688 }
3689 if (mFormat != fastMixerFormat) {
3690 // change our Sink format to accept our intermediate precision
3691 mFormat = fastMixerFormat;
3692 free(mSinkBuffer);
3693 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3694 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3695 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3696 }
Eric Laurent81784c32012-11-19 14:55:58 -08003697
3698 // create a MonoPipe to connect our submix to FastMixer
3699 NBAIO_Format format = mOutputSink->format();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003700#ifdef TEE_SINK
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003701 NBAIO_Format origformat = format;
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003702#endif
Andy Hung1258c1a2014-05-23 21:22:17 -07003703 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07003704 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003705 format.mFormat = fastMixerFormat;
3706 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3707
Eric Laurent81784c32012-11-19 14:55:58 -08003708 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3709 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3710 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3711 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3712 const NBAIO_Format offers[1] = {format};
3713 size_t numCounterOffers = 0;
Glenn Kastenfc302fd2016-04-11 14:11:26 -07003714#if !LOG_NDEBUG || defined(TEE_SINK)
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003715 ssize_t index =
3716#else
3717 (void)
3718#endif
3719 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003720 ALOG_ASSERT(index == 0);
3721 monoPipe->setAvgFrames((mScreenState & 1) ?
3722 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3723 mPipeSink = monoPipe;
3724
Glenn Kasten46909e72013-02-26 09:20:22 -08003725#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003726 if (mTeeSinkOutputEnabled) {
3727 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003728 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3729 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003730 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003731 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003732 ALOG_ASSERT(index == 0);
3733 mTeeSink = teeSink;
3734 PipeReader *teeSource = new PipeReader(*teeSink);
3735 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003736 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003737 ALOG_ASSERT(index == 0);
3738 mTeeSource = teeSource;
3739 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003740#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003741
3742 // create fast mixer and configure it initially with just one fast track for our submix
3743 mFastMixer = new FastMixer();
3744 FastMixerStateQueue *sq = mFastMixer->sq();
3745#ifdef STATE_QUEUE_DUMP
3746 sq->setObserverDump(&mStateQueueObserverDump);
3747 sq->setMutatorDump(&mStateQueueMutatorDump);
3748#endif
3749 FastMixerState *state = sq->begin();
3750 FastTrack *fastTrack = &state->mFastTracks[0];
3751 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3752 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3753 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003754 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3755 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003756 fastTrack->mGeneration++;
3757 state->mFastTracksGen++;
3758 state->mTrackMask = 1;
3759 // fast mixer will use the HAL output sink
3760 state->mOutputSink = mOutputSink.get();
3761 state->mOutputSinkGen++;
3762 state->mFrameCount = mFrameCount;
3763 state->mCommand = FastMixerState::COLD_IDLE;
3764 // already done in constructor initialization list
3765 //mFastMixerFutex = 0;
3766 state->mColdFutexAddr = &mFastMixerFutex;
3767 state->mColdGen++;
3768 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003769#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003770 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003771#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003772 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3773 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003774 sq->end();
3775 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3776
3777 // start the fast mixer
3778 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3779 pid_t tid = mFastMixer->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003780 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003781
3782#ifdef AUDIO_WATCHDOG
3783 // create and start the watchdog
3784 mAudioWatchdog = new AudioWatchdog();
3785 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3786 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3787 tid = mAudioWatchdog->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003788 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003789#endif
3790
Eric Laurent81784c32012-11-19 14:55:58 -08003791 }
3792
3793 switch (kUseFastMixer) {
3794 case FastMixer_Never:
3795 case FastMixer_Dynamic:
3796 mNormalSink = mOutputSink;
3797 break;
3798 case FastMixer_Always:
3799 mNormalSink = mPipeSink;
3800 break;
3801 case FastMixer_Static:
3802 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3803 break;
3804 }
3805}
3806
3807AudioFlinger::MixerThread::~MixerThread()
3808{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003809 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003810 FastMixerStateQueue *sq = mFastMixer->sq();
3811 FastMixerState *state = sq->begin();
3812 if (state->mCommand == FastMixerState::COLD_IDLE) {
3813 int32_t old = android_atomic_inc(&mFastMixerFutex);
3814 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003815 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003816 }
3817 }
3818 state->mCommand = FastMixerState::EXIT;
3819 sq->end();
3820 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3821 mFastMixer->join();
3822 // Though the fast mixer thread has exited, it's state queue is still valid.
3823 // We'll use that extract the final state which contains one remaining fast track
3824 // corresponding to our sub-mix.
3825 state = sq->begin();
3826 ALOG_ASSERT(state->mTrackMask == 1);
3827 FastTrack *fastTrack = &state->mFastTracks[0];
3828 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3829 delete fastTrack->mBufferProvider;
3830 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003831 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003832#ifdef AUDIO_WATCHDOG
3833 if (mAudioWatchdog != 0) {
3834 mAudioWatchdog->requestExit();
3835 mAudioWatchdog->requestExitAndWait();
3836 mAudioWatchdog.clear();
3837 }
3838#endif
3839 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003840 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003841 delete mAudioMixer;
3842}
3843
3844
3845uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3846{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003847 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003848 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3849 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3850 }
3851 return latency;
3852}
3853
3854
3855void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3856{
3857 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3858}
3859
Eric Laurentbfb1b832013-01-07 09:53:42 -08003860ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003861{
3862 // FIXME we should only do one push per cycle; confirm this is true
3863 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003864 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003865 FastMixerStateQueue *sq = mFastMixer->sq();
3866 FastMixerState *state = sq->begin();
3867 if (state->mCommand != FastMixerState::MIX_WRITE &&
3868 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3869 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07003870
3871 // FIXME workaround for first HAL write being CPU bound on some devices
3872 ATRACE_BEGIN("write");
3873 mOutput->write((char *)mSinkBuffer, 0);
3874 ATRACE_END();
3875
Eric Laurent81784c32012-11-19 14:55:58 -08003876 int32_t old = android_atomic_inc(&mFastMixerFutex);
3877 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003878 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003879 }
3880#ifdef AUDIO_WATCHDOG
3881 if (mAudioWatchdog != 0) {
3882 mAudioWatchdog->resume();
3883 }
3884#endif
3885 }
3886 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003887#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003888 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003889 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003890#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003891 sq->end();
3892 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3893 if (kUseFastMixer == FastMixer_Dynamic) {
3894 mNormalSink = mPipeSink;
3895 }
3896 } else {
3897 sq->end(false /*didModify*/);
3898 }
3899 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003900 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003901}
3902
3903void AudioFlinger::MixerThread::threadLoop_standby()
3904{
3905 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003906 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003907 FastMixerStateQueue *sq = mFastMixer->sq();
3908 FastMixerState *state = sq->begin();
3909 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung1f82f952016-11-28 19:01:02 -08003910 // Report any frames trapped in the Monopipe
3911 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
3912 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
3913 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
3914 "monoPipeWritten:%lld monoPipeLeft:%lld",
3915 (long long)mFramesWritten, (long long)mSuspendedFrames,
3916 (long long)mPipeSink->framesWritten(), pipeFrames);
3917 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
3918
Eric Laurent81784c32012-11-19 14:55:58 -08003919 state->mCommand = FastMixerState::COLD_IDLE;
3920 state->mColdFutexAddr = &mFastMixerFutex;
3921 state->mColdGen++;
3922 mFastMixerFutex = 0;
3923 sq->end();
3924 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3925 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3926 if (kUseFastMixer == FastMixer_Dynamic) {
3927 mNormalSink = mOutputSink;
3928 }
3929#ifdef AUDIO_WATCHDOG
3930 if (mAudioWatchdog != 0) {
3931 mAudioWatchdog->pause();
3932 }
3933#endif
3934 } else {
3935 sq->end(false /*didModify*/);
3936 }
3937 }
3938 PlaybackThread::threadLoop_standby();
3939}
3940
Eric Laurentbfb1b832013-01-07 09:53:42 -08003941bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3942{
3943 return false;
3944}
3945
3946bool AudioFlinger::PlaybackThread::shouldStandby_l()
3947{
3948 return !mStandby;
3949}
3950
3951bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3952{
3953 Mutex::Autolock _l(mLock);
3954 return waitingAsyncCallback_l();
3955}
3956
Eric Laurent81784c32012-11-19 14:55:58 -08003957// shared by MIXER and DIRECT, overridden by DUPLICATING
3958void AudioFlinger::PlaybackThread::threadLoop_standby()
3959{
3960 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08003961 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003962 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003963 // discard any pending drain or write ack by incrementing sequence
3964 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3965 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003966 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003967 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3968 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003969 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003970 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003971}
3972
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003973void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3974{
3975 ALOGV("signal playback thread");
3976 broadcast_l();
3977}
3978
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003979void AudioFlinger::PlaybackThread::onAsyncError()
3980{
3981 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
3982 invalidateTracks((audio_stream_type_t)i);
3983 }
3984}
3985
Eric Laurent81784c32012-11-19 14:55:58 -08003986void AudioFlinger::MixerThread::threadLoop_mix()
3987{
Eric Laurent81784c32012-11-19 14:55:58 -08003988 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08003989 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08003990 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003991 // increase sleep time progressively when application underrun condition clears.
3992 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3993 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3994 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003995 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003996 sleepTimeShift--;
3997 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003998 mSleepTimeUs = 0;
3999 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004000 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07004001
Eric Laurent81784c32012-11-19 14:55:58 -08004002}
4003
4004void AudioFlinger::MixerThread::threadLoop_sleepTime()
4005{
4006 // If no tracks are ready, sleep once for the duration of an output
4007 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004008 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004009 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004010 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
4011 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
4012 mSleepTimeUs = kMinThreadSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004013 }
4014 // reduce sleep time in case of consecutive application underruns to avoid
4015 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
4016 // duration we would end up writing less data than needed by the audio HAL if
4017 // the condition persists.
4018 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
4019 sleepTimeShift++;
4020 }
4021 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004022 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004023 }
4024 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004025 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
4026 // before effects processing or output.
4027 if (mMixerBufferValid) {
4028 memset(mMixerBuffer, 0, mMixerBufferSize);
4029 } else {
4030 memset(mSinkBuffer, 0, mSinkBufferSize);
4031 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004032 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004033 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
4034 "anticipated start");
4035 }
4036 // TODO add standby time extension fct of effect tail
4037}
4038
4039// prepareTracks_l() must be called with ThreadBase::mLock held
4040AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
4041 Vector< sp<Track> > *tracksToRemove)
4042{
4043
4044 mixer_state mixerStatus = MIXER_IDLE;
4045 // find out which tracks need to be processed
4046 size_t count = mActiveTracks.size();
4047 size_t mixedTracks = 0;
4048 size_t tracksWithEffect = 0;
4049 // counts only _active_ fast tracks
4050 size_t fastTracks = 0;
4051 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
4052
4053 float masterVolume = mMasterVolume;
4054 bool masterMute = mMasterMute;
4055
4056 if (masterMute) {
4057 masterVolume = 0;
4058 }
4059 // Delegate master volume control to effect in output mix effect chain if needed
4060 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4061 if (chain != 0) {
4062 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
4063 chain->setVolume_l(&v, &v);
4064 masterVolume = (float)((v + (1 << 23)) >> 24);
4065 chain.clear();
4066 }
4067
4068 // prepare a new state to push
4069 FastMixerStateQueue *sq = NULL;
4070 FastMixerState *state = NULL;
4071 bool didModify = false;
4072 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004073 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004074 sq = mFastMixer->sq();
4075 state = sq->begin();
4076 }
4077
Andy Hung69aed5f2014-02-25 17:24:40 -08004078 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08004079 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08004080
Eric Laurent81784c32012-11-19 14:55:58 -08004081 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07004082 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08004083 if (t == 0) {
4084 continue;
4085 }
4086
4087 // this const just means the local variable doesn't change
4088 Track* const track = t.get();
4089
4090 // process fast tracks
4091 if (track->isFastTrack()) {
4092
4093 // It's theoretically possible (though unlikely) for a fast track to be created
4094 // and then removed within the same normal mix cycle. This is not a problem, as
4095 // the track never becomes active so it's fast mixer slot is never touched.
4096 // The converse, of removing an (active) track and then creating a new track
4097 // at the identical fast mixer slot within the same normal mix cycle,
4098 // is impossible because the slot isn't marked available until the end of each cycle.
4099 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07004100 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08004101 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
4102 FastTrack *fastTrack = &state->mFastTracks[j];
4103
4104 // Determine whether the track is currently in underrun condition,
4105 // and whether it had a recent underrun.
4106 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
4107 FastTrackUnderruns underruns = ftDump->mUnderruns;
4108 uint32_t recentFull = (underruns.mBitFields.mFull -
4109 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
4110 uint32_t recentPartial = (underruns.mBitFields.mPartial -
4111 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
4112 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
4113 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
4114 uint32_t recentUnderruns = recentPartial + recentEmpty;
4115 track->mObservedUnderruns = underruns;
4116 // don't count underruns that occur while stopping or pausing
4117 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07004118 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
4119 recentUnderruns > 0) {
4120 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
4121 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Phil Burk2812d9e2016-01-04 10:34:30 -08004122 } else {
4123 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Eric Laurent81784c32012-11-19 14:55:58 -08004124 }
4125
4126 // This is similar to the state machine for normal tracks,
4127 // with a few modifications for fast tracks.
4128 bool isActive = true;
4129 switch (track->mState) {
4130 case TrackBase::STOPPING_1:
4131 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08004132 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004133 track->mState = TrackBase::STOPPING_2;
4134 }
4135 break;
4136 case TrackBase::PAUSING:
4137 // ramp down is not yet implemented
4138 track->setPaused();
4139 break;
4140 case TrackBase::RESUMING:
4141 // ramp up is not yet implemented
4142 track->mState = TrackBase::ACTIVE;
4143 break;
4144 case TrackBase::ACTIVE:
4145 if (recentFull > 0 || recentPartial > 0) {
4146 // track has provided at least some frames recently: reset retry count
4147 track->mRetryCount = kMaxTrackRetries;
4148 }
4149 if (recentUnderruns == 0) {
4150 // no recent underruns: stay active
4151 break;
4152 }
4153 // there has recently been an underrun of some kind
4154 if (track->sharedBuffer() == 0) {
4155 // were any of the recent underruns "empty" (no frames available)?
4156 if (recentEmpty == 0) {
4157 // no, then ignore the partial underruns as they are allowed indefinitely
4158 break;
4159 }
4160 // there has recently been an "empty" underrun: decrement the retry counter
4161 if (--(track->mRetryCount) > 0) {
4162 break;
4163 }
4164 // indicate to client process that the track was disabled because of underrun;
4165 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004166 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004167 // remove from active list, but state remains ACTIVE [confusing but true]
4168 isActive = false;
4169 break;
4170 }
4171 // fall through
4172 case TrackBase::STOPPING_2:
4173 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08004174 case TrackBase::STOPPED:
4175 case TrackBase::FLUSHED: // flush() while active
4176 // Check for presentation complete if track is inactive
4177 // We have consumed all the buffers of this track.
4178 // This would be incomplete if we auto-paused on underrun
4179 {
4180 size_t audioHALFrames =
4181 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004182 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004183 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
4184 // track stays in active list until presentation is complete
4185 break;
4186 }
4187 }
4188 if (track->isStopping_2()) {
4189 track->mState = TrackBase::STOPPED;
4190 }
4191 if (track->isStopped()) {
4192 // Can't reset directly, as fast mixer is still polling this track
4193 // track->reset();
4194 // So instead mark this track as needing to be reset after push with ack
4195 resetMask |= 1 << i;
4196 }
4197 isActive = false;
4198 break;
4199 case TrackBase::IDLE:
4200 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08004201 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08004202 }
4203
4204 if (isActive) {
4205 // was it previously inactive?
4206 if (!(state->mTrackMask & (1 << j))) {
4207 ExtendedAudioBufferProvider *eabp = track;
4208 VolumeProvider *vp = track;
4209 fastTrack->mBufferProvider = eabp;
4210 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08004211 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07004212 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08004213 fastTrack->mGeneration++;
4214 state->mTrackMask |= 1 << j;
4215 didModify = true;
4216 // no acknowledgement required for newly active tracks
4217 }
4218 // cache the combined master volume and stream type volume for fast mixer; this
4219 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08004220 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08004221 ++fastTracks;
4222 } else {
4223 // was it previously active?
4224 if (state->mTrackMask & (1 << j)) {
4225 fastTrack->mBufferProvider = NULL;
4226 fastTrack->mGeneration++;
4227 state->mTrackMask &= ~(1 << j);
4228 didModify = true;
4229 // If any fast tracks were removed, we must wait for acknowledgement
4230 // because we're about to decrement the last sp<> on those tracks.
4231 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4232 } else {
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08004233 LOG_ALWAYS_FATAL("fast track %d should have been active; "
4234 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
4235 j, track->mState, state->mTrackMask, recentUnderruns,
4236 track->sharedBuffer() != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004237 }
4238 tracksToRemove->add(track);
4239 // Avoids a misleading display in dumpsys
4240 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
4241 }
4242 continue;
4243 }
4244
4245 { // local variable scope to avoid goto warning
4246
4247 audio_track_cblk_t* cblk = track->cblk();
4248
4249 // The first time a track is added we wait
4250 // for all its buffers to be filled before processing it
4251 int name = track->name();
4252 // make sure that we have enough frames to mix one full buffer.
4253 // enforce this condition only once to enable draining the buffer in case the client
4254 // app does not call stop() and relies on underrun to stop:
4255 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
4256 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004257 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07004258 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004259 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004260
4261 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004262 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004263 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
4264 // add frames already consumed but not yet released by the resampler
4265 // because mAudioTrackServerProxy->framesReady() will include these frames
4266 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
4267
Eric Laurent81784c32012-11-19 14:55:58 -08004268 uint32_t minFrames = 1;
4269 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
4270 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004271 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08004272 }
Eric Laurent13e4c962013-12-20 17:36:01 -08004273
4274 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07004275 if (ATRACE_ENABLED()) {
4276 // I wish we had formatted trace names
4277 char traceName[16];
4278 strcpy(traceName, "nRdy");
4279 int name = track->name();
4280 if (AudioMixer::TRACK0 <= name &&
4281 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
4282 name -= AudioMixer::TRACK0;
4283 traceName[4] = (name / 10) + '0';
4284 traceName[5] = (name % 10) + '0';
4285 } else {
4286 traceName[4] = '?';
4287 traceName[5] = '?';
4288 }
4289 traceName[6] = '\0';
4290 ATRACE_INT(traceName, framesReady);
4291 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004292 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08004293 !track->isPaused() && !track->isTerminated())
4294 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004295 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004296
4297 mixedTracks++;
4298
Andy Hung69aed5f2014-02-25 17:24:40 -08004299 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
4300 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08004301 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08004302 if (track->mainBuffer() != mSinkBuffer &&
4303 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004304 if (mEffectBufferEnabled) {
4305 mEffectBufferValid = true; // Later can set directly.
4306 }
Eric Laurent81784c32012-11-19 14:55:58 -08004307 chain = getEffectChain_l(track->sessionId());
4308 // Delegate volume control to effect in track effect chain if needed
4309 if (chain != 0) {
4310 tracksWithEffect++;
4311 } else {
4312 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
4313 "session %d",
4314 name, track->sessionId());
4315 }
4316 }
4317
4318
4319 int param = AudioMixer::VOLUME;
4320 if (track->mFillingUpStatus == Track::FS_FILLED) {
4321 // no ramp for the first volume setting
4322 track->mFillingUpStatus = Track::FS_ACTIVE;
4323 if (track->mState == TrackBase::RESUMING) {
4324 track->mState = TrackBase::ACTIVE;
4325 param = AudioMixer::RAMP_VOLUME;
4326 }
4327 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004328 // FIXME should not make a decision based on mServer
4329 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004330 // If the track is stopped before the first frame was mixed,
4331 // do not apply ramp
4332 param = AudioMixer::RAMP_VOLUME;
4333 }
4334
4335 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07004336 uint32_t vl, vr; // in U8.24 integer format
4337 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08004338 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07004339 vl = vr = 0;
4340 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08004341 if (track->isPausing()) {
4342 track->setPaused();
4343 }
4344 } else {
4345
4346 // read original volumes with volume control
4347 float typeVolume = mStreamTypes[track->streamType()].volume;
4348 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004349 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004350 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07004351 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
4352 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08004353 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07004354 if (vlf > GAIN_FLOAT_UNITY) {
4355 ALOGV("Track left volume out of range: %.3g", vlf);
4356 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004357 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07004358 if (vrf > GAIN_FLOAT_UNITY) {
4359 ALOGV("Track right volume out of range: %.3g", vrf);
4360 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004361 }
4362 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07004363 vlf *= v;
4364 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08004365 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07004366 // then derive vl and vr as U8.24 versions for the effect chain
4367 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
4368 vl = (uint32_t) (scaleto8_24 * vlf);
4369 vr = (uint32_t) (scaleto8_24 * vrf);
4370 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08004371 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08004372 // send level comes from shared memory and so may be corrupt
4373 if (sendLevel > MAX_GAIN_INT) {
4374 ALOGV("Track send level out of range: %04X", sendLevel);
4375 sendLevel = MAX_GAIN_INT;
4376 }
Andy Hung6be49402014-05-30 10:42:03 -07004377 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4378 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08004379 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004380
Eric Laurent81784c32012-11-19 14:55:58 -08004381 // Delegate volume control to effect in track effect chain if needed
4382 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4383 // Do not ramp volume if volume is controlled by effect
4384 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08004385 // Update remaining floating point volume levels
4386 vlf = (float)vl / (1 << 24);
4387 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004388 track->mHasVolumeController = true;
4389 } else {
4390 // force no volume ramp when volume controller was just disabled or removed
4391 // from effect chain to avoid volume spike
4392 if (track->mHasVolumeController) {
4393 param = AudioMixer::VOLUME;
4394 }
4395 track->mHasVolumeController = false;
4396 }
4397
Eric Laurent81784c32012-11-19 14:55:58 -08004398 // XXX: these things DON'T need to be done each time
4399 mAudioMixer->setBufferProvider(name, track);
4400 mAudioMixer->enable(name);
4401
Andy Hung6be49402014-05-30 10:42:03 -07004402 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
4403 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
4404 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004405 mAudioMixer->setParameter(
4406 name,
4407 AudioMixer::TRACK,
4408 AudioMixer::FORMAT, (void *)track->format());
4409 mAudioMixer->setParameter(
4410 name,
4411 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004412 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004413 mAudioMixer->setParameter(
4414 name,
4415 AudioMixer::TRACK,
4416 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004417 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004418 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004419 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004420 if (reqSampleRate == 0) {
4421 reqSampleRate = mSampleRate;
4422 } else if (reqSampleRate > maxSampleRate) {
4423 reqSampleRate = maxSampleRate;
4424 }
Eric Laurent81784c32012-11-19 14:55:58 -08004425 mAudioMixer->setParameter(
4426 name,
4427 AudioMixer::RESAMPLE,
4428 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004429 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004430
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004431 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004432 mAudioMixer->setParameter(
4433 name,
4434 AudioMixer::TIMESTRETCH,
4435 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004436 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004437
Andy Hung69aed5f2014-02-25 17:24:40 -08004438 /*
4439 * Select the appropriate output buffer for the track.
4440 *
Andy Hung98ef9782014-03-04 14:46:50 -08004441 * Tracks with effects go into their own effects chain buffer
4442 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004443 *
4444 * Other tracks can use mMixerBuffer for higher precision
4445 * channel accumulation. If this buffer is enabled
4446 * (mMixerBufferEnabled true), then selected tracks will accumulate
4447 * into it.
4448 *
4449 */
4450 if (mMixerBufferEnabled
4451 && (track->mainBuffer() == mSinkBuffer
4452 || track->mainBuffer() == mMixerBuffer)) {
4453 mAudioMixer->setParameter(
4454 name,
4455 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004456 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004457 mAudioMixer->setParameter(
4458 name,
4459 AudioMixer::TRACK,
4460 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4461 // TODO: override track->mainBuffer()?
4462 mMixerBufferValid = true;
4463 } else {
4464 mAudioMixer->setParameter(
4465 name,
4466 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004467 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004468 mAudioMixer->setParameter(
4469 name,
4470 AudioMixer::TRACK,
4471 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4472 }
Eric Laurent81784c32012-11-19 14:55:58 -08004473 mAudioMixer->setParameter(
4474 name,
4475 AudioMixer::TRACK,
4476 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4477
4478 // reset retry count
4479 track->mRetryCount = kMaxTrackRetries;
4480
4481 // If one track is ready, set the mixer ready if:
4482 // - the mixer was not ready during previous round OR
4483 // - no other track is not ready
4484 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4485 mixerStatus != MIXER_TRACKS_ENABLED) {
4486 mixerStatus = MIXER_TRACKS_READY;
4487 }
4488 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004489 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hung08fb1742015-05-31 23:22:10 -07004490 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)",
4491 track, framesReady, desiredFrames);
Glenn Kasten82aaf942013-07-17 16:05:07 -07004492 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08004493 } else {
4494 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004495 }
Phil Burk2812d9e2016-01-04 10:34:30 -08004496
Eric Laurent81784c32012-11-19 14:55:58 -08004497 // clear effect chain input buffer if an active track underruns to avoid sending
4498 // previous audio buffer again to effects
4499 chain = getEffectChain_l(track->sessionId());
4500 if (chain != 0) {
4501 chain->clearInputBuffer();
4502 }
4503
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004504 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004505 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4506 track->isStopped() || track->isPaused()) {
4507 // We have consumed all the buffers of this track.
4508 // Remove it from the list of active tracks.
4509 // TODO: use actual buffer filling status instead of latency when available from
4510 // audio HAL
4511 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004512 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004513 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4514 if (track->isStopped()) {
4515 track->reset();
4516 }
4517 tracksToRemove->add(track);
4518 }
4519 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004520 // No buffers for this track. Give it a few chances to
4521 // fill a buffer, then remove it from active list.
4522 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004523 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004524 tracksToRemove->add(track);
4525 // indicate to client process that the track was disabled because of underrun;
4526 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004527 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004528 // If one track is not ready, mark the mixer also not ready if:
4529 // - the mixer was ready during previous round OR
4530 // - no other track is ready
4531 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4532 mixerStatus != MIXER_TRACKS_READY) {
4533 mixerStatus = MIXER_TRACKS_ENABLED;
4534 }
4535 }
4536 mAudioMixer->disable(name);
4537 }
4538
4539 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08004540
4541 }
4542
4543 // Push the new FastMixer state if necessary
4544 bool pauseAudioWatchdog = false;
4545 if (didModify) {
4546 state->mFastTracksGen++;
4547 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4548 if (kUseFastMixer == FastMixer_Dynamic &&
4549 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4550 state->mCommand = FastMixerState::COLD_IDLE;
4551 state->mColdFutexAddr = &mFastMixerFutex;
4552 state->mColdGen++;
4553 mFastMixerFutex = 0;
4554 if (kUseFastMixer == FastMixer_Dynamic) {
4555 mNormalSink = mOutputSink;
4556 }
4557 // If we go into cold idle, need to wait for acknowledgement
4558 // so that fast mixer stops doing I/O.
4559 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4560 pauseAudioWatchdog = true;
4561 }
Eric Laurent81784c32012-11-19 14:55:58 -08004562 }
4563 if (sq != NULL) {
4564 sq->end(didModify);
4565 sq->push(block);
4566 }
4567#ifdef AUDIO_WATCHDOG
4568 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4569 mAudioWatchdog->pause();
4570 }
4571#endif
4572
4573 // Now perform the deferred reset on fast tracks that have stopped
4574 while (resetMask != 0) {
4575 size_t i = __builtin_ctz(resetMask);
4576 ALOG_ASSERT(i < count);
4577 resetMask &= ~(1 << i);
4578 sp<Track> t = mActiveTracks[i].promote();
4579 if (t == 0) {
4580 continue;
4581 }
4582 Track* track = t.get();
4583 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4584 track->reset();
4585 }
4586
4587 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004588 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004589
Eric Laurent97d547d2014-09-02 14:45:53 -07004590 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4591 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004592 }
4593
4594 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004595 // as long as there are effects we should clear the effects buffer, to avoid
4596 // passing a non-clean buffer to the effect chain
4597 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004598 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004599 // sink or mix buffer must be cleared if all tracks are connected to an
4600 // effect chain as in this case the mixer will not write to the sink or mix buffer
4601 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004602 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4603 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004604 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004605 if (mMixerBufferValid) {
4606 memset(mMixerBuffer, 0, mMixerBufferSize);
4607 // TODO: In testing, mSinkBuffer below need not be cleared because
4608 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4609 // after mixing.
4610 //
4611 // To enforce this guarantee:
4612 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4613 // (mixedTracks == 0 && fastTracks > 0))
4614 // must imply MIXER_TRACKS_READY.
4615 // Later, we may clear buffers regardless, and skip much of this logic.
4616 }
Andy Hung98ef9782014-03-04 14:46:50 -08004617 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004618 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004619 }
4620
4621 // if any fast tracks, then status is ready
4622 mMixerStatusIgnoringFastTracks = mixerStatus;
4623 if (fastTracks > 0) {
4624 mixerStatus = MIXER_TRACKS_READY;
4625 }
4626 return mixerStatus;
4627}
4628
Eric Laurentad7dd962016-09-22 12:38:37 -07004629// trackCountForUid_l() must be called with ThreadBase::mLock held
4630uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid)
4631{
4632 uint32_t trackCount = 0;
4633 for (size_t i = 0; i < mTracks.size() ; i++) {
4634 if (mTracks[i]->uid() == (int)uid) {
4635 trackCount++;
4636 }
4637 }
4638 return trackCount;
4639}
4640
Eric Laurent81784c32012-11-19 14:55:58 -08004641// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07004642int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
Eric Laurentad7dd962016-09-22 12:38:37 -07004643 audio_format_t format, audio_session_t sessionId, uid_t uid)
Eric Laurent81784c32012-11-19 14:55:58 -08004644{
Eric Laurentad7dd962016-09-22 12:38:37 -07004645 if (trackCountForUid_l(uid) > (PlaybackThread::kMaxTracksPerUid - 1)) {
4646 return -1;
4647 }
Andy Hunge8a1ced2014-05-09 15:02:21 -07004648 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08004649}
4650
4651// deleteTrackName_l() must be called with ThreadBase::mLock held
4652void AudioFlinger::MixerThread::deleteTrackName_l(int name)
4653{
4654 ALOGV("remove track (%d) and delete from mixer", name);
4655 mAudioMixer->deleteTrackName(name);
4656}
4657
Eric Laurent10351942014-05-08 18:49:52 -07004658// checkForNewParameter_l() must be called with ThreadBase::mLock held
4659bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4660 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004661{
Eric Laurent81784c32012-11-19 14:55:58 -08004662 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08004663 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004664
Eric Laurent10351942014-05-08 18:49:52 -07004665 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004666
Glenn Kastenc05b8d72016-03-24 09:48:17 -07004667 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004668
Eric Laurent10351942014-05-08 18:49:52 -07004669 AudioParameter param = AudioParameter(keyValuePair);
4670 int value;
4671 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4672 reconfig = true;
4673 }
4674 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004675 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004676 status = BAD_VALUE;
4677 } else {
4678 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004679 reconfig = true;
4680 }
Eric Laurent10351942014-05-08 18:49:52 -07004681 }
4682 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004683 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004684 status = BAD_VALUE;
4685 } else {
4686 // no need to save value, since it's constant
4687 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004688 }
Eric Laurent10351942014-05-08 18:49:52 -07004689 }
4690 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4691 // do not accept frame count changes if tracks are open as the track buffer
4692 // size depends on frame count and correct behavior would not be guaranteed
4693 // if frame count is changed after track creation
4694 if (!mTracks.isEmpty()) {
4695 status = INVALID_OPERATION;
4696 } else {
4697 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004698 }
Eric Laurent10351942014-05-08 18:49:52 -07004699 }
4700 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004701#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004702 // when changing the audio output device, call addBatteryData to notify
4703 // the change
4704 if (mOutDevice != value) {
4705 uint32_t params = 0;
4706 // check whether speaker is on
4707 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4708 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004709 }
Eric Laurent10351942014-05-08 18:49:52 -07004710
4711 audio_devices_t deviceWithoutSpeaker
4712 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4713 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07004714 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07004715 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4716 }
4717
4718 if (params != 0) {
4719 addBatteryData(params);
4720 }
4721 }
Eric Laurent81784c32012-11-19 14:55:58 -08004722#endif
4723
Eric Laurent10351942014-05-08 18:49:52 -07004724 // forward device change to effects that have requested to be
4725 // aware of attached audio device.
4726 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08004727 a2dpDeviceChanged =
4728 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07004729 mOutDevice = value;
4730 for (size_t i = 0; i < mEffectChains.size(); i++) {
4731 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004732 }
4733 }
Eric Laurent10351942014-05-08 18:49:52 -07004734 }
Eric Laurent81784c32012-11-19 14:55:58 -08004735
Eric Laurent10351942014-05-08 18:49:52 -07004736 if (status == NO_ERROR) {
4737 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4738 keyValuePair.string());
4739 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004740 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004741 mStandby = true;
4742 mBytesWritten = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004743 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Eric Laurent10351942014-05-08 18:49:52 -07004744 keyValuePair.string());
Eric Laurent81784c32012-11-19 14:55:58 -08004745 }
Eric Laurent10351942014-05-08 18:49:52 -07004746 if (status == NO_ERROR && reconfig) {
4747 readOutputParameters_l();
4748 delete mAudioMixer;
4749 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4750 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004751 int name = getTrackName_l(mTracks[i]->mChannelMask,
Eric Laurentad7dd962016-09-22 12:38:37 -07004752 mTracks[i]->mFormat, mTracks[i]->mSessionId, mTracks[i]->uid());
Eric Laurent10351942014-05-08 18:49:52 -07004753 if (name < 0) {
4754 break;
4755 }
4756 mTracks[i]->mName = name;
4757 }
Eric Laurent73e26b62015-04-27 16:55:58 -07004758 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004759 }
Eric Laurent81784c32012-11-19 14:55:58 -08004760 }
4761
Eric Laurent42537be2016-01-08 17:16:42 -08004762 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08004763}
4764
4765
4766void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4767{
Eric Laurent81784c32012-11-19 14:55:58 -08004768 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07004769 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Elliott Hughes87cebad2014-05-22 10:14:43 -07004770 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Andy Hung2ddee192015-12-18 17:34:44 -08004771 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent81784c32012-11-19 14:55:58 -08004772
4773 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten2f90c512015-12-02 11:40:09 -08004774 // while we are dumping it. It may be inconsistent, but it won't mutate!
4775 // This is a large object so we place it on the heap.
4776 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
4777 const FastMixerDumpState *copy = new FastMixerDumpState(mFastMixerDumpState);
4778 copy->dump(fd);
4779 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08004780
4781#ifdef STATE_QUEUE_DUMP
4782 // Similar for state queue
4783 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4784 observerCopy.dump(fd);
4785 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4786 mutatorCopy.dump(fd);
4787#endif
4788
Glenn Kasten46909e72013-02-26 09:20:22 -08004789#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004790 // Write the tee output to a .wav file
4791 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08004792#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004793
4794#ifdef AUDIO_WATCHDOG
4795 if (mAudioWatchdog != 0) {
4796 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4797 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4798 wdCopy.dump(fd);
4799 }
4800#endif
4801}
4802
4803uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4804{
4805 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4806}
4807
4808uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4809{
4810 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4811}
4812
4813void AudioFlinger::MixerThread::cacheParameters_l()
4814{
4815 PlaybackThread::cacheParameters_l();
4816
4817 // FIXME: Relaxed timing because of a certain device that can't meet latency
4818 // Should be reduced to 2x after the vendor fixes the driver issue
4819 // increase threshold again due to low power audio mode. The way this warning
4820 // threshold is calculated and its usefulness should be reconsidered anyway.
4821 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4822}
4823
4824// ----------------------------------------------------------------------------
4825
4826AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07004827 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady)
4828 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08004829 // mLeftVolFloat, mRightVolFloat
4830{
4831}
4832
Eric Laurentbfb1b832013-01-07 09:53:42 -08004833AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4834 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurente93cc032016-05-05 10:15:10 -07004835 ThreadBase::type_t type, bool systemReady)
4836 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004837 // mLeftVolFloat, mRightVolFloat
4838{
4839}
4840
Eric Laurent81784c32012-11-19 14:55:58 -08004841AudioFlinger::DirectOutputThread::~DirectOutputThread()
4842{
4843}
4844
Eric Laurentbfb1b832013-01-07 09:53:42 -08004845void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
4846{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004847 float left, right;
4848
4849 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4850 left = right = 0;
4851 } else {
4852 float typeVolume = mStreamTypes[track->streamType()].volume;
4853 float v = mMasterVolume * typeVolume;
4854 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004855 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4856 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4857 if (left > GAIN_FLOAT_UNITY) {
4858 left = GAIN_FLOAT_UNITY;
4859 }
4860 left *= v;
4861 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4862 if (right > GAIN_FLOAT_UNITY) {
4863 right = GAIN_FLOAT_UNITY;
4864 }
4865 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004866 }
4867
4868 if (lastTrack) {
4869 if (left != mLeftVolFloat || right != mRightVolFloat) {
4870 mLeftVolFloat = left;
4871 mRightVolFloat = right;
4872
4873 // Convert volumes from float to 8.24
4874 uint32_t vl = (uint32_t)(left * (1 << 24));
4875 uint32_t vr = (uint32_t)(right * (1 << 24));
4876
4877 // Delegate volume control to effect in track effect chain if needed
4878 // only one effect chain can be present on DirectOutputThread, so if
4879 // there is one, the track is connected to it
4880 if (!mEffectChains.isEmpty()) {
4881 mEffectChains[0]->setVolume_l(&vl, &vr);
4882 left = (float)vl / (1 << 24);
4883 right = (float)vr / (1 << 24);
4884 }
4885 if (mOutput->stream->set_volume) {
4886 mOutput->stream->set_volume(mOutput->stream, left, right);
4887 }
4888 }
4889 }
4890}
4891
Phil Burk43b4dcc2015-06-09 16:53:44 -07004892void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
4893{
4894 sp<Track> previousTrack = mPreviousTrack.promote();
4895 sp<Track> latestTrack = mLatestActiveTrack.promote();
4896
Eric Laurent0f0631e2015-07-06 18:01:25 -07004897 if (previousTrack != 0 && latestTrack != 0) {
4898 if (mType == DIRECT) {
4899 if (previousTrack.get() != latestTrack.get()) {
4900 mFlushPending = true;
4901 }
4902 } else /* mType == OFFLOAD */ {
4903 if (previousTrack->sessionId() != latestTrack->sessionId()) {
4904 mFlushPending = true;
4905 }
4906 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004907 }
4908 PlaybackThread::onAddNewTrack_l();
4909}
Eric Laurentbfb1b832013-01-07 09:53:42 -08004910
Eric Laurent81784c32012-11-19 14:55:58 -08004911AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4912 Vector< sp<Track> > *tracksToRemove
4913)
4914{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004915 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004916 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004917 bool doHwPause = false;
4918 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004919
4920 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07004921 for (size_t i = 0; i < count; i++) {
4922 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08004923 // The track died recently
4924 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004925 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08004926 }
4927
Phil Burk43b4dcc2015-06-09 16:53:44 -07004928 if (t->isInvalid()) {
4929 ALOGW("An invalidated track shouldn't be in active list");
4930 tracksToRemove->add(t);
4931 continue;
4932 }
4933
Eric Laurent81784c32012-11-19 14:55:58 -08004934 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004935#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08004936 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004937#endif
Eric Laurentfd477972013-10-25 18:10:40 -07004938 // Only consider last track started for volume and mixer state control.
4939 // In theory an older track could underrun and restart after the new one starts
4940 // but as we only care about the transition phase between two tracks on a
4941 // direct output, it is not a problem to ignore the underrun case.
4942 sp<Track> l = mLatestActiveTrack.promote();
4943 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004944
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004945 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004946 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004947 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004948 doHwPause = true;
4949 mHwPaused = true;
4950 }
4951 tracksToRemove->add(track);
4952 } else if (track->isFlushPending()) {
4953 track->flushAck();
4954 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004955 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004956 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004957 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004958 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07004959 if (last) {
4960 mLeftVolFloat = mRightVolFloat = -1.0;
4961 if (mHwPaused) {
4962 doHwResume = true;
4963 mHwPaused = false;
4964 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004965 }
4966 }
4967
Eric Laurent81784c32012-11-19 14:55:58 -08004968 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004969 // for all its buffers to be filled before processing it.
4970 // Allow draining the buffer in case the client
4971 // app does not call stop() and relies on underrun to stop:
4972 // hence the test on (track->mRetryCount > 1).
4973 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07004974 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08004975 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004976 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08004977 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004978 minFrames = mNormalFrameCount;
4979 } else {
4980 minFrames = 1;
4981 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004982
Eric Laurentab5cdba2014-06-09 17:22:27 -07004983 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4984 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004985 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004986 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004987
4988 if (track->mFillingUpStatus == Track::FS_FILLED) {
4989 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07004990 if (last) {
4991 // make sure processVolume_l() will apply new volume even if 0
4992 mLeftVolFloat = mRightVolFloat = -1.0;
4993 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004994 if (!mHwSupportsPause) {
4995 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004996 }
4997 }
4998
4999 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08005000 processVolume_l(track, last);
5001 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005002 sp<Track> previousTrack = mPreviousTrack.promote();
5003 if (previousTrack != 0) {
5004 if (track != previousTrack.get()) {
5005 // Flush any data still being written from last track
5006 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07005007 // Invalidate previous track to force a seek when resuming.
5008 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005009 }
5010 }
5011 mPreviousTrack = track;
5012
Eric Laurentd595b7c2013-04-03 17:27:56 -07005013 // reset retry count
5014 track->mRetryCount = kMaxTrackRetriesDirect;
5015 mActiveTrack = t;
5016 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07005017 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005018 doHwResume = true;
5019 mHwPaused = false;
5020 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005021 }
Eric Laurent81784c32012-11-19 14:55:58 -08005022 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07005023 // clear effect chain input buffer if the last active track started underruns
5024 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07005025 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08005026 mEffectChains[0]->clearInputBuffer();
5027 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005028 if (track->isStopping_1()) {
5029 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07005030 if (last && mHwPaused) {
5031 doHwResume = true;
5032 mHwPaused = false;
5033 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005034 }
5035 if ((track->sharedBuffer() != 0) || track->isStopped() ||
5036 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005037 // We have consumed all the buffers of this track.
5038 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07005039 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08005040 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005041 audioHALFrames = (latency_l() * mSampleRate) / 1000;
5042 } else {
5043 audioHALFrames = 0;
5044 }
5045
Andy Hung818e7a32016-02-16 18:08:07 -08005046 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07005047 if (mStandby || !last ||
5048 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005049 if (track->isStopping_2()) {
5050 track->mState = TrackBase::STOPPED;
5051 }
Eric Laurent81784c32012-11-19 14:55:58 -08005052 if (track->isStopped()) {
5053 track->reset();
5054 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005055 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08005056 }
5057 } else {
5058 // No buffers for this track. Give it a few chances to
5059 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07005060 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08005061 if (--(track->mRetryCount) <= 0) {
5062 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07005063 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005064 // indicate to client process that the track was disabled because of underrun;
5065 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005066 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005067 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07005068 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
5069 "minFrames = %u, mFormat = %#x",
5070 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08005071 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07005072 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005073 doHwPause = true;
5074 mHwPaused = true;
5075 }
Eric Laurent81784c32012-11-19 14:55:58 -08005076 }
5077 }
5078 }
5079 }
5080
Eric Laurentd1f69b02014-12-15 14:33:13 -08005081 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07005082 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005083 for (size_t i = 0; i < mTracks.size(); i++) {
5084 if (mTracks[i]->isFlushPending()) {
5085 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005086 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005087 }
5088 }
5089 }
5090
5091 // make sure the pause/flush/resume sequence is executed in the right order.
5092 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5093 // before flush and then resume HW. This can happen in case of pause/flush/resume
5094 // if resume is received before pause is executed.
5095 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07005096 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005097 mOutput->stream->pause(mOutput->stream);
5098 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005099 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005100 flushHw_l();
5101 }
5102 if (mHwSupportsPause && !mStandby && doHwResume) {
5103 mOutput->stream->resume(mOutput->stream);
5104 }
Eric Laurent81784c32012-11-19 14:55:58 -08005105 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005106 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005107
5108 return mixerStatus;
5109}
5110
5111void AudioFlinger::DirectOutputThread::threadLoop_mix()
5112{
Eric Laurent81784c32012-11-19 14:55:58 -08005113 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08005114 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005115 // output audio to hardware
5116 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07005117 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005118 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08005119 status_t status = mActiveTrack->getNextBuffer(&buffer);
5120 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08005121 // no need to pad with 0 for compressed audio
5122 if (audio_has_proportional_frames(mFormat)) {
5123 memset(curBuf, 0, frameCount * mFrameSize);
5124 }
Eric Laurent81784c32012-11-19 14:55:58 -08005125 break;
5126 }
5127 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
5128 frameCount -= buffer.frameCount;
5129 curBuf += buffer.frameCount * mFrameSize;
5130 mActiveTrack->releaseBuffer(&buffer);
5131 }
Andy Hung2098f272014-02-27 14:00:06 -08005132 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005133 mSleepTimeUs = 0;
5134 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005135 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005136}
5137
5138void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
5139{
Eric Laurentd1f69b02014-12-15 14:33:13 -08005140 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005141 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005142 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005143 return;
5144 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005145 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005146 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurente93cc032016-05-05 10:15:10 -07005147 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005148 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005149 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005150 }
Phil Burkfdb3c072016-02-09 10:47:02 -08005151 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08005152 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005153 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005154 }
5155}
5156
Eric Laurentd1f69b02014-12-15 14:33:13 -08005157void AudioFlinger::DirectOutputThread::threadLoop_exit()
5158{
5159 {
5160 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005161 for (size_t i = 0; i < mTracks.size(); i++) {
5162 if (mTracks[i]->isFlushPending()) {
5163 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005164 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005165 }
5166 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005167 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005168 flushHw_l();
5169 }
5170 }
5171 PlaybackThread::threadLoop_exit();
5172}
5173
5174// must be called with thread mutex locked
5175bool AudioFlinger::DirectOutputThread::shouldStandby_l()
5176{
5177 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07005178 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005179
vivek mehta9cd7ad12016-03-17 00:18:29 -07005180 if ((mType == DIRECT) && audio_is_linear_pcm(mFormat) && !usesHwAvSync()) {
5181 return !mStandby;
5182 }
5183
Eric Laurentd1f69b02014-12-15 14:33:13 -08005184 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
5185 // after a timeout and we will enter standby then.
5186 if (mTracks.size() > 0) {
5187 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07005188 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
5189 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005190 }
5191
Eric Laurent5cff4032015-05-26 13:49:58 -07005192 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08005193}
5194
Eric Laurent81784c32012-11-19 14:55:58 -08005195// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005196int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Eric Laurentad7dd962016-09-22 12:38:37 -07005197 audio_format_t format __unused, audio_session_t sessionId __unused, uid_t uid)
Eric Laurent81784c32012-11-19 14:55:58 -08005198{
Eric Laurentad7dd962016-09-22 12:38:37 -07005199 if (trackCountForUid_l(uid) > (PlaybackThread::kMaxTracksPerUid - 1)) {
5200 return -1;
5201 }
Eric Laurent81784c32012-11-19 14:55:58 -08005202 return 0;
5203}
5204
5205// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005206void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005207{
5208}
5209
Eric Laurent10351942014-05-08 18:49:52 -07005210// checkForNewParameter_l() must be called with ThreadBase::mLock held
5211bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
5212 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005213{
5214 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005215 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005216
Eric Laurent10351942014-05-08 18:49:52 -07005217 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005218
Eric Laurent10351942014-05-08 18:49:52 -07005219 AudioParameter param = AudioParameter(keyValuePair);
5220 int value;
5221 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5222 // forward device change to effects that have requested to be
5223 // aware of attached audio device.
5224 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005225 a2dpDeviceChanged =
5226 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005227 mOutDevice = value;
5228 for (size_t i = 0; i < mEffectChains.size(); i++) {
5229 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07005230 }
5231 }
Eric Laurent81784c32012-11-19 14:55:58 -08005232 }
Eric Laurent10351942014-05-08 18:49:52 -07005233 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5234 // do not accept frame count changes if tracks are open as the track buffer
5235 // size depends on frame count and correct behavior would not be garantied
5236 // if frame count is changed after track creation
5237 if (!mTracks.isEmpty()) {
5238 status = INVALID_OPERATION;
5239 } else {
5240 reconfig = true;
5241 }
5242 }
5243 if (status == NO_ERROR) {
5244 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
5245 keyValuePair.string());
5246 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005247 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005248 mStandby = true;
5249 mBytesWritten = 0;
5250 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
5251 keyValuePair.string());
5252 }
5253 if (status == NO_ERROR && reconfig) {
5254 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07005255 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005256 }
5257 }
5258
Eric Laurent42537be2016-01-08 17:16:42 -08005259 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005260}
5261
5262uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
5263{
5264 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005265 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005266 time = PlaybackThread::activeSleepTimeUs();
5267 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005268 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005269 }
5270 return time;
5271}
5272
5273uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
5274{
5275 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005276 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005277 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
5278 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005279 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005280 }
5281 return time;
5282}
5283
5284uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
5285{
5286 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005287 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005288 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
5289 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005290 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005291 }
5292 return time;
5293}
5294
5295void AudioFlinger::DirectOutputThread::cacheParameters_l()
5296{
5297 PlaybackThread::cacheParameters_l();
5298
5299 // use shorter standby delay as on normal output to release
5300 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07005301 // no delay on outputs with HW A/V sync
5302 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005303 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08005304 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005305 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07005306 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005307 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07005308 }
Eric Laurent81784c32012-11-19 14:55:58 -08005309}
5310
Eric Laurente659ef42014-09-29 13:06:46 -07005311void AudioFlinger::DirectOutputThread::flushHw_l()
5312{
Phil Burk062e67a2015-02-11 13:40:50 -08005313 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08005314 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005315 mFlushPending = false;
Eric Laurente659ef42014-09-29 13:06:46 -07005316}
5317
Eric Laurent81784c32012-11-19 14:55:58 -08005318// ----------------------------------------------------------------------------
5319
Eric Laurentbfb1b832013-01-07 09:53:42 -08005320AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07005321 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005322 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07005323 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07005324 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005325 mDrainSequence(0),
5326 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005327{
5328}
5329
5330AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
5331{
5332}
5333
5334void AudioFlinger::AsyncCallbackThread::onFirstRef()
5335{
5336 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
5337}
5338
5339bool AudioFlinger::AsyncCallbackThread::threadLoop()
5340{
5341 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005342 uint32_t writeAckSequence;
5343 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005344 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005345
5346 {
5347 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005348 while (!((mWriteAckSequence & 1) ||
5349 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005350 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005351 exitPending())) {
5352 mWaitWorkCV.wait(mLock);
5353 }
5354
Eric Laurentbfb1b832013-01-07 09:53:42 -08005355 if (exitPending()) {
5356 break;
5357 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005358 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
5359 mWriteAckSequence, mDrainSequence);
5360 writeAckSequence = mWriteAckSequence;
5361 mWriteAckSequence &= ~1;
5362 drainSequence = mDrainSequence;
5363 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005364 asyncError = mAsyncError;
5365 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005366 }
5367 {
Eric Laurent4de95592013-09-26 15:28:21 -07005368 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
5369 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005370 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005371 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005372 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005373 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005374 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005375 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005376 if (asyncError) {
5377 playbackThread->onAsyncError();
5378 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005379 }
5380 }
5381 }
5382 return false;
5383}
5384
5385void AudioFlinger::AsyncCallbackThread::exit()
5386{
5387 ALOGV("AsyncCallbackThread::exit");
5388 Mutex::Autolock _l(mLock);
5389 requestExit();
5390 mWaitWorkCV.broadcast();
5391}
5392
Eric Laurent3b4529e2013-09-05 18:09:19 -07005393void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005394{
5395 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005396 // bit 0 is cleared
5397 mWriteAckSequence = sequence << 1;
5398}
5399
5400void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5401{
5402 Mutex::Autolock _l(mLock);
5403 // ignore unexpected callbacks
5404 if (mWriteAckSequence & 2) {
5405 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005406 mWaitWorkCV.signal();
5407 }
5408}
5409
Eric Laurent3b4529e2013-09-05 18:09:19 -07005410void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005411{
5412 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005413 // bit 0 is cleared
5414 mDrainSequence = sequence << 1;
5415}
5416
5417void AudioFlinger::AsyncCallbackThread::resetDraining()
5418{
5419 Mutex::Autolock _l(mLock);
5420 // ignore unexpected callbacks
5421 if (mDrainSequence & 2) {
5422 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005423 mWaitWorkCV.signal();
5424 }
5425}
5426
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005427void AudioFlinger::AsyncCallbackThread::setAsyncError()
5428{
5429 Mutex::Autolock _l(mLock);
5430 mAsyncError = true;
5431 mWaitWorkCV.signal();
5432}
5433
Eric Laurentbfb1b832013-01-07 09:53:42 -08005434
5435// ----------------------------------------------------------------------------
5436AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07005437 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
5438 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07005439 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
5440 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005441{
Eric Laurentfd477972013-10-25 18:10:40 -07005442 //FIXME: mStandby should be set to true by ThreadBase constructor
5443 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07005444 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005445}
5446
Eric Laurentbfb1b832013-01-07 09:53:42 -08005447void AudioFlinger::OffloadThread::threadLoop_exit()
5448{
5449 if (mFlushPending || mHwPaused) {
5450 // If a flush is pending or track was paused, just discard buffered data
5451 flushHw_l();
5452 } else {
5453 mMixerStatus = MIXER_DRAIN_ALL;
5454 threadLoop_drain();
5455 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005456 if (mUseAsyncWrite) {
5457 ALOG_ASSERT(mCallbackThread != 0);
5458 mCallbackThread->exit();
5459 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005460 PlaybackThread::threadLoop_exit();
5461}
5462
5463AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5464 Vector< sp<Track> > *tracksToRemove
5465)
5466{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005467 size_t count = mActiveTracks.size();
5468
5469 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005470 bool doHwPause = false;
5471 bool doHwResume = false;
5472
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005473 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07005474
Eric Laurentbfb1b832013-01-07 09:53:42 -08005475 // find out which tracks need to be processed
5476 for (size_t i = 0; i < count; i++) {
5477 sp<Track> t = mActiveTracks[i].promote();
5478 // The track died recently
5479 if (t == 0) {
5480 continue;
5481 }
5482 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005483#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08005484 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005485#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005486 // Only consider last track started for volume and mixer state control.
5487 // In theory an older track could underrun and restart after the new one starts
5488 // but as we only care about the transition phase between two tracks on a
5489 // direct output, it is not a problem to ignore the underrun case.
5490 sp<Track> l = mLatestActiveTrack.promote();
5491 bool last = l.get() == track;
5492
Haynes Mathew George7844f672014-01-15 12:32:55 -08005493 if (track->isInvalid()) {
5494 ALOGW("An invalidated track shouldn't be in active list");
5495 tracksToRemove->add(track);
5496 continue;
5497 }
5498
5499 if (track->mState == TrackBase::IDLE) {
5500 ALOGW("An idle track shouldn't be in active list");
5501 continue;
5502 }
5503
Eric Laurentbfb1b832013-01-07 09:53:42 -08005504 if (track->isPausing()) {
5505 track->setPaused();
5506 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005507 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005508 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005509 mHwPaused = true;
5510 }
5511 // If we were part way through writing the mixbuffer to
5512 // the HAL we must save this until we resume
5513 // BUG - this will be wrong if a different track is made active,
5514 // in that case we want to discard the pending data in the
5515 // mixbuffer and tell the client to present it again when the
5516 // track is resumed
5517 mPausedWriteLength = mCurrentWriteLength;
5518 mPausedBytesRemaining = mBytesRemaining;
5519 mBytesRemaining = 0; // stop writing
5520 }
5521 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005522 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005523 if (track->isStopping_1()) {
5524 track->mRetryCount = kMaxTrackStopRetriesOffload;
5525 } else {
5526 track->mRetryCount = kMaxTrackRetriesOffload;
5527 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08005528 track->flushAck();
5529 if (last) {
5530 mFlushPending = true;
5531 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005532 } else if (track->isResumePending()){
5533 track->resumeAck();
5534 if (last) {
5535 if (mPausedBytesRemaining) {
5536 // Need to continue write that was interrupted
5537 mCurrentWriteLength = mPausedWriteLength;
5538 mBytesRemaining = mPausedBytesRemaining;
5539 mPausedBytesRemaining = 0;
5540 }
5541 if (mHwPaused) {
5542 doHwResume = true;
5543 mHwPaused = false;
5544 // threadLoop_mix() will handle the case that we need to
5545 // resume an interrupted write
5546 }
5547 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005548 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005549
Eric Laurent3df841a2016-07-15 15:15:40 -07005550 mLeftVolFloat = mRightVolFloat = -1.0;
5551
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005552 // Do not handle new data in this iteration even if track->framesReady()
5553 mixerStatus = MIXER_TRACKS_ENABLED;
5554 }
5555 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005556 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005557 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005558 if (track->mFillingUpStatus == Track::FS_FILLED) {
5559 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005560 if (last) {
5561 // make sure processVolume_l() will apply new volume even if 0
5562 mLeftVolFloat = mRightVolFloat = -1.0;
5563 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005564 }
5565
5566 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005567 sp<Track> previousTrack = mPreviousTrack.promote();
5568 if (previousTrack != 0) {
5569 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005570 // Flush any data still being written from last track
5571 mBytesRemaining = 0;
5572 if (mPausedBytesRemaining) {
5573 // Last track was paused so we also need to flush saved
5574 // mixbuffer state and invalidate track so that it will
5575 // re-submit that unwritten data when it is next resumed
5576 mPausedBytesRemaining = 0;
5577 // Invalidate is a bit drastic - would be more efficient
5578 // to have a flag to tell client that some of the
5579 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005580 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005581 }
5582 // flush data already sent to the DSP if changing audio session as audio
5583 // comes from a different source. Also invalidate previous track to force a
5584 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005585 if (previousTrack->sessionId() != track->sessionId()) {
5586 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005587 }
5588 }
5589 }
5590 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005591 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07005592 if (track->isStopping_1()) {
5593 track->mRetryCount = kMaxTrackStopRetriesOffload;
5594 } else {
5595 track->mRetryCount = kMaxTrackRetriesOffload;
5596 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005597 mActiveTrack = t;
5598 mixerStatus = MIXER_TRACKS_READY;
5599 }
5600 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005601 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005602 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005603 if (--(track->mRetryCount) <= 0) {
5604 // Hardware buffer can hold a large amount of audio so we must
5605 // wait for all current track's data to drain before we say
5606 // that the track is stopped.
5607 if (mBytesRemaining == 0) {
5608 // Only start draining when all data in mixbuffer
5609 // has been written
5610 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5611 track->mState = TrackBase::STOPPING_2; // so presentation completes after
5612 // drain do not drain if no data was ever sent to HAL (mStandby == true)
5613 if (last && !mStandby) {
5614 // do not modify drain sequence if we are already draining. This happens
5615 // when resuming from pause after drain.
5616 if ((mDrainSequence & 1) == 0) {
5617 mSleepTimeUs = 0;
5618 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
5619 mixerStatus = MIXER_DRAIN_TRACK;
5620 mDrainSequence += 2;
5621 }
5622 if (mHwPaused) {
5623 // It is possible to move from PAUSED to STOPPING_1 without
5624 // a resume so we must ensure hardware is running
5625 doHwResume = true;
5626 mHwPaused = false;
5627 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005628 }
5629 }
Eric Laurente93cc032016-05-05 10:15:10 -07005630 } else if (last) {
5631 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
5632 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005633 }
5634 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005635 // Drain has completed or we are in standby, signal presentation complete
5636 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005637 track->mState = TrackBase::STOPPED;
5638 size_t audioHALFrames =
5639 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005640 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005641 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005642 track->presentationComplete(framesWritten, audioHALFrames);
5643 track->reset();
5644 tracksToRemove->add(track);
5645 }
5646 } else {
5647 // No buffers for this track. Give it a few chances to
5648 // fill a buffer, then remove it from active list.
5649 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07005650 bool running = false;
5651 if (mOutput->stream->get_presentation_position != nullptr) {
5652 uint64_t position = 0;
5653 struct timespec unused;
5654 // The running check restarts the retry counter at least once.
5655 int ret = mOutput->stream->get_presentation_position(
5656 mOutput->stream, &position, &unused);
5657 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
5658 running = true;
5659 mOffloadUnderrunPosition = position;
5660 }
5661 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
5662 (long long)position, (long long)mOffloadUnderrunPosition);
5663 }
5664 if (running) { // still running, give us more time.
5665 track->mRetryCount = kMaxTrackRetriesOffload;
5666 } else {
5667 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5668 track->name());
5669 tracksToRemove->add(track);
5670 // indicate to client process that the track was disabled because of underrun;
5671 // it will then automatically call start() when data is available
5672 track->disable();
5673 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005674 } else if (last){
5675 mixerStatus = MIXER_TRACKS_ENABLED;
5676 }
5677 }
5678 }
5679 // compute volume for this track
5680 processVolume_l(track, last);
5681 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005682
Eric Laurentea0fade2013-10-04 16:23:48 -07005683 // make sure the pause/flush/resume sequence is executed in the right order.
5684 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5685 // before flush and then resume HW. This can happen in case of pause/flush/resume
5686 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07005687 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07005688 mOutput->stream->pause(mOutput->stream);
5689 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005690 if (mFlushPending) {
5691 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005692 }
Eric Laurentfd477972013-10-25 18:10:40 -07005693 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07005694 mOutput->stream->resume(mOutput->stream);
5695 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005696
Eric Laurentbfb1b832013-01-07 09:53:42 -08005697 // remove all the tracks that need to be...
5698 removeTracks_l(*tracksToRemove);
5699
5700 return mixerStatus;
5701}
5702
Eric Laurentbfb1b832013-01-07 09:53:42 -08005703// must be called with thread mutex locked
5704bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5705{
Eric Laurent3b4529e2013-09-05 18:09:19 -07005706 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5707 mWriteAckSequence, mDrainSequence);
5708 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005709 return true;
5710 }
5711 return false;
5712}
5713
Eric Laurentbfb1b832013-01-07 09:53:42 -08005714bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5715{
5716 Mutex::Autolock _l(mLock);
5717 return waitingAsyncCallback_l();
5718}
5719
5720void AudioFlinger::OffloadThread::flushHw_l()
5721{
Eric Laurente659ef42014-09-29 13:06:46 -07005722 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005723 // Flush anything still waiting in the mixbuffer
5724 mCurrentWriteLength = 0;
5725 mBytesRemaining = 0;
5726 mPausedWriteLength = 0;
5727 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07005728 // reset bytes written count to reflect that DSP buffers are empty after flush.
5729 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07005730 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08005731
Eric Laurentbfb1b832013-01-07 09:53:42 -08005732 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005733 // discard any pending drain or write ack by incrementing sequence
5734 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5735 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005736 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005737 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5738 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005739 }
5740}
5741
Haynes Mathew George05317d22016-05-03 16:34:26 -07005742void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
5743{
5744 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07005745 if (PlaybackThread::invalidateTracks_l(streamType)) {
5746 mFlushPending = true;
5747 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07005748}
5749
Eric Laurentbfb1b832013-01-07 09:53:42 -08005750// ----------------------------------------------------------------------------
5751
Eric Laurent81784c32012-11-19 14:55:58 -08005752AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005753 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005754 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07005755 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08005756 mWaitTimeMs(UINT_MAX)
5757{
5758 addOutputTrack(mainThread);
5759}
5760
5761AudioFlinger::DuplicatingThread::~DuplicatingThread()
5762{
5763 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5764 mOutputTracks[i]->destroy();
5765 }
5766}
5767
5768void AudioFlinger::DuplicatingThread::threadLoop_mix()
5769{
5770 // mix buffers...
5771 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08005772 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08005773 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005774 if (mMixerBufferValid) {
5775 memset(mMixerBuffer, 0, mMixerBufferSize);
5776 } else {
5777 memset(mSinkBuffer, 0, mSinkBufferSize);
5778 }
Eric Laurent81784c32012-11-19 14:55:58 -08005779 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005780 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005781 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005782 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005783 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005784}
5785
5786void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5787{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005788 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005789 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005790 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005791 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005792 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005793 }
5794 } else if (mBytesWritten != 0) {
5795 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5796 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005797 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005798 } else {
5799 // flush remaining overflow buffers in output tracks
5800 writeFrames = 0;
5801 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005802 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005803 }
5804}
5805
Eric Laurentbfb1b832013-01-07 09:53:42 -08005806ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005807{
5808 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005809 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005810 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005811 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005812 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005813}
5814
5815void AudioFlinger::DuplicatingThread::threadLoop_standby()
5816{
5817 // DuplicatingThread implements standby by stopping all tracks
5818 for (size_t i = 0; i < outputTracks.size(); i++) {
5819 outputTracks[i]->stop();
5820 }
5821}
5822
5823void AudioFlinger::DuplicatingThread::saveOutputTracks()
5824{
5825 outputTracks = mOutputTracks;
5826}
5827
5828void AudioFlinger::DuplicatingThread::clearOutputTracks()
5829{
5830 outputTracks.clear();
5831}
5832
5833void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5834{
5835 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005836 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5837 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5838 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5839 const size_t frameCount =
5840 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5841 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5842 // from different OutputTracks and their associated MixerThreads (e.g. one may
5843 // nearly empty and the other may be dropping data).
5844
5845 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005846 this,
5847 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005848 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005849 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005850 frameCount,
5851 IPCThreadState::self()->getCallingUid());
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07005852 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
5853 if (status != NO_ERROR) {
5854 ALOGE("addOutputTrack() initCheck failed %d", status);
5855 return;
Eric Laurent81784c32012-11-19 14:55:58 -08005856 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07005857 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
5858 mOutputTracks.add(outputTrack);
5859 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
5860 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005861}
5862
5863void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5864{
5865 Mutex::Autolock _l(mLock);
5866 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5867 if (mOutputTracks[i]->thread() == thread) {
5868 mOutputTracks[i]->destroy();
5869 mOutputTracks.removeAt(i);
5870 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07005871 if (thread->getOutput() == mOutput) {
5872 mOutput = NULL;
5873 }
Eric Laurent81784c32012-11-19 14:55:58 -08005874 return;
5875 }
5876 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07005877 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005878}
5879
5880// caller must hold mLock
5881void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5882{
5883 mWaitTimeMs = UINT_MAX;
5884 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5885 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5886 if (strong != 0) {
5887 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5888 if (waitTimeMs < mWaitTimeMs) {
5889 mWaitTimeMs = waitTimeMs;
5890 }
5891 }
5892 }
5893}
5894
5895
5896bool AudioFlinger::DuplicatingThread::outputsReady(
5897 const SortedVector< sp<OutputTrack> > &outputTracks)
5898{
5899 for (size_t i = 0; i < outputTracks.size(); i++) {
5900 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5901 if (thread == 0) {
5902 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5903 outputTracks[i].get());
5904 return false;
5905 }
5906 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5907 // see note at standby() declaration
5908 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5909 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5910 thread.get());
5911 return false;
5912 }
5913 }
5914 return true;
5915}
5916
5917uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5918{
5919 return (mWaitTimeMs * 1000) / 2;
5920}
5921
5922void AudioFlinger::DuplicatingThread::cacheParameters_l()
5923{
5924 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5925 updateWaitTime_l();
5926
5927 MixerThread::cacheParameters_l();
5928}
5929
5930// ----------------------------------------------------------------------------
5931// Record
5932// ----------------------------------------------------------------------------
5933
5934AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5935 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005936 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005937 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07005938 audio_devices_t inDevice,
5939 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08005940#ifdef TEE_SINK
5941 , const sp<NBAIO_Sink>& teeSink
5942#endif
5943 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07005944 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005945 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005946 // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005947 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005948#ifdef TEE_SINK
5949 , mTeeSink(teeSink)
5950#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005951 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5952 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005953 // mFastCapture below
5954 , mFastCaptureFutex(0)
5955 // mInputSource
5956 // mPipeSink
5957 // mPipeSource
5958 , mPipeFramesP2(0)
5959 // mPipeMemory
5960 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005961 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005962{
Glenn Kastend7dca052015-03-05 16:05:54 -08005963 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5964 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08005965
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005966 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005967
5968 // create an NBAIO source for the HAL input stream, and negotiate
5969 mInputSource = new AudioStreamInSource(input->stream);
5970 size_t numCounterOffers = 0;
5971 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005972#if !LOG_NDEBUG
5973 ssize_t index =
5974#else
5975 (void)
5976#endif
5977 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005978 ALOG_ASSERT(index == 0);
5979
5980 // initialize fast capture depending on configuration
5981 bool initFastCapture;
5982 switch (kUseFastCapture) {
5983 case FastCapture_Never:
5984 initFastCapture = false;
5985 break;
5986 case FastCapture_Always:
5987 initFastCapture = true;
5988 break;
5989 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07005990 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005991 break;
5992 // case FastCapture_Dynamic:
5993 }
5994
5995 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07005996 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005997 NBAIO_Format format = mInputSource->format();
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005998 size_t pipeFramesP2 = roundup(mSampleRate / 25); // double-buffering of 20 ms each
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005999 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
6000 void *pipeBuffer;
6001 const sp<MemoryDealer> roHeap(readOnlyHeap());
6002 sp<IMemory> pipeMemory;
6003 if ((roHeap == 0) ||
6004 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
6005 (pipeBuffer = pipeMemory->pointer()) == NULL) {
6006 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
6007 goto failed;
6008 }
6009 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
6010 memset(pipeBuffer, 0, pipeSize);
6011 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
6012 const NBAIO_Format offers[1] = {format};
6013 size_t numCounterOffers = 0;
6014 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
6015 ALOG_ASSERT(index == 0);
6016 mPipeSink = pipe;
6017 PipeReader *pipeReader = new PipeReader(*pipe);
6018 numCounterOffers = 0;
6019 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
6020 ALOG_ASSERT(index == 0);
6021 mPipeSource = pipeReader;
6022 mPipeFramesP2 = pipeFramesP2;
6023 mPipeMemory = pipeMemory;
6024
6025 // create fast capture
6026 mFastCapture = new FastCapture();
6027 FastCaptureStateQueue *sq = mFastCapture->sq();
6028#ifdef STATE_QUEUE_DUMP
6029 // FIXME
6030#endif
6031 FastCaptureState *state = sq->begin();
6032 state->mCblk = NULL;
6033 state->mInputSource = mInputSource.get();
6034 state->mInputSourceGen++;
6035 state->mPipeSink = pipe;
6036 state->mPipeSinkGen++;
6037 state->mFrameCount = mFrameCount;
6038 state->mCommand = FastCaptureState::COLD_IDLE;
6039 // already done in constructor initialization list
6040 //mFastCaptureFutex = 0;
6041 state->mColdFutexAddr = &mFastCaptureFutex;
6042 state->mColdGen++;
6043 state->mDumpState = &mFastCaptureDumpState;
6044#ifdef TEE_SINK
6045 // FIXME
6046#endif
6047 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
6048 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
6049 sq->end();
6050 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6051
6052 // start the fast capture
6053 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
6054 pid_t tid = mFastCapture->getTid();
Glenn Kasten8379b722016-03-18 14:54:17 -07006055 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006056#ifdef AUDIO_WATCHDOG
6057 // FIXME
6058#endif
6059
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006060 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006061 }
6062failed: ;
6063
6064 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08006065}
6066
Eric Laurent81784c32012-11-19 14:55:58 -08006067AudioFlinger::RecordThread::~RecordThread()
6068{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006069 if (mFastCapture != 0) {
6070 FastCaptureStateQueue *sq = mFastCapture->sq();
6071 FastCaptureState *state = sq->begin();
6072 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6073 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6074 if (old == -1) {
6075 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6076 }
6077 }
6078 state->mCommand = FastCaptureState::EXIT;
6079 sq->end();
6080 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6081 mFastCapture->join();
6082 mFastCapture.clear();
6083 }
6084 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07006085 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07006086 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08006087}
6088
6089void AudioFlinger::RecordThread::onFirstRef()
6090{
Glenn Kastend7dca052015-03-05 16:05:54 -08006091 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08006092}
6093
Eric Laurent81784c32012-11-19 14:55:58 -08006094bool AudioFlinger::RecordThread::threadLoop()
6095{
Eric Laurent81784c32012-11-19 14:55:58 -08006096 nsecs_t lastWarning = 0;
6097
6098 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006099
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006100reacquire_wakelock:
6101 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08006102 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006103 {
6104 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006105 size_t size = mActiveTracks.size();
6106 activeTracksGen = mActiveTracksGen;
6107 if (size > 0) {
6108 // FIXME an arbitrary choice
6109 activeTrack = mActiveTracks[0];
6110 acquireWakeLock_l(activeTrack->uid());
6111 if (size > 1) {
6112 SortedVector<int> tmp;
6113 for (size_t i = 0; i < size; i++) {
6114 tmp.add(mActiveTracks[i]->uid());
6115 }
6116 updateWakeLockUids_l(tmp);
6117 }
6118 } else {
6119 acquireWakeLock_l(-1);
6120 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006121 }
6122
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006123 // used to request a deferred sleep, to be executed later while mutex is unlocked
6124 uint32_t sleepUs = 0;
6125
6126 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006127 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006128 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07006129
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006130 // activeTracks accumulates a copy of a subset of mActiveTracks
6131 Vector< sp<RecordTrack> > activeTracks;
6132
Glenn Kasten735f45f2014-08-18 15:51:59 -07006133 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006134 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07006135
Glenn Kasten735f45f2014-08-18 15:51:59 -07006136 // reference to a fast track which is about to be removed
6137 sp<RecordTrack> fastTrackToRemove;
6138
Eric Laurent81784c32012-11-19 14:55:58 -08006139 { // scope for mLock
6140 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08006141
Eric Laurent021cf962014-05-13 10:18:14 -07006142 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006143
Eric Laurent000a4192014-01-29 15:17:32 -08006144 // check exitPending here because checkForNewParameters_l() and
6145 // checkForNewParameters_l() can temporarily release mLock
6146 if (exitPending()) {
6147 break;
6148 }
6149
Eric Laurent5c25d562016-07-13 17:17:45 -07006150 // sleep with mutex unlocked
6151 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07006152 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07006153 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
6154 ATRACE_END();
6155 sleepUs = 0;
6156 continue;
6157 }
6158
Glenn Kasten2b806402013-11-20 16:37:38 -08006159 // if no active track(s), then standby and release wakelock
6160 size_t size = mActiveTracks.size();
6161 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07006162 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006163 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08006164 releaseWakeLock_l();
6165 ALOGV("RecordThread: loop stopping");
6166 // go to sleep
6167 mWaitWorkCV.wait(mLock);
6168 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006169 goto reacquire_wakelock;
6170 }
6171
Glenn Kasten2b806402013-11-20 16:37:38 -08006172 if (mActiveTracksGen != activeTracksGen) {
6173 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006174 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08006175 for (size_t i = 0; i < size; i++) {
6176 tmp.add(mActiveTracks[i]->uid());
6177 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006178 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08006179 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006180
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006181 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07006182 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006183 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07006184
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006185 activeTrack = mActiveTracks[i];
6186 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07006187 if (activeTrack->isFastTrack()) {
6188 ALOG_ASSERT(fastTrackToRemove == 0);
6189 fastTrackToRemove = activeTrack;
6190 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006191 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08006192 mActiveTracks.remove(activeTrack);
6193 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006194 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07006195 continue;
6196 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006197
6198 TrackBase::track_state activeTrackState = activeTrack->mState;
6199 switch (activeTrackState) {
6200
6201 case TrackBase::PAUSING:
6202 mActiveTracks.remove(activeTrack);
6203 mActiveTracksGen++;
6204 doBroadcast = true;
6205 size--;
6206 continue;
6207
6208 case TrackBase::STARTING_1:
6209 sleepUs = 10000;
6210 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07006211 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006212 continue;
6213
6214 case TrackBase::STARTING_2:
6215 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006216 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07006217 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07006218 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006219 break;
6220
6221 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07006222 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006223 break;
6224
6225 case TrackBase::IDLE:
6226 i++;
6227 continue;
6228
6229 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08006230 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07006231 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006232
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006233 activeTracks.add(activeTrack);
6234 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07006235
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006236 if (activeTrack->isFastTrack()) {
6237 ALOG_ASSERT(!mFastTrackAvail);
6238 ALOG_ASSERT(fastTrack == 0);
6239 fastTrack = activeTrack;
6240 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006241 }
Eric Laurent5c25d562016-07-13 17:17:45 -07006242
6243 if (allStopped) {
6244 standbyIfNotAlreadyInStandby();
6245 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006246 if (doBroadcast) {
6247 mStartStopCond.broadcast();
6248 }
6249
6250 // sleep if there are no active tracks to process
6251 if (activeTracks.size() == 0) {
6252 if (sleepUs == 0) {
6253 sleepUs = kRecordThreadSleepUs;
6254 }
6255 continue;
6256 }
6257 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07006258
Eric Laurent81784c32012-11-19 14:55:58 -08006259 lockEffectChains_l(effectChains);
6260 }
6261
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006262 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07006263
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006264 size_t size = effectChains.size();
6265 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006266 // thread mutex is not locked, but effect chain is locked
6267 effectChains[i]->process_l();
6268 }
6269
Glenn Kasten735f45f2014-08-18 15:51:59 -07006270 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006271 if (mFastCapture != 0) {
6272 FastCaptureStateQueue *sq = mFastCapture->sq();
6273 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07006274 bool didModify = false;
6275 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006276 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
6277 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
6278 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6279 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6280 if (old == -1) {
6281 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6282 }
6283 }
6284 state->mCommand = FastCaptureState::READ_WRITE;
6285#if 0 // FIXME
6286 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08006287 FastThreadDumpState::kSamplingNforLowRamDevice :
6288 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006289#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07006290 didModify = true;
6291 }
6292 audio_track_cblk_t *cblkOld = state->mCblk;
6293 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
6294 if (cblkNew != cblkOld) {
6295 state->mCblk = cblkNew;
6296 // block until acked if removing a fast track
6297 if (cblkOld != NULL) {
6298 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
6299 }
6300 didModify = true;
6301 }
6302 sq->end(didModify);
6303 if (didModify) {
6304 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006305#if 0
6306 if (kUseFastCapture == FastCapture_Dynamic) {
6307 mNormalSource = mPipeSource;
6308 }
6309#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006310 }
6311 }
6312
Glenn Kasten735f45f2014-08-18 15:51:59 -07006313 // now run the fast track destructor with thread mutex unlocked
6314 fastTrackToRemove.clear();
6315
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006316 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
6317 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
6318 // slow, then this RecordThread will overrun by not calling HAL read often enough.
6319 // If destination is non-contiguous, first read past the nominal end of buffer, then
6320 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006321
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006322 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006323 ssize_t framesRead;
6324
6325 // If an NBAIO source is present, use it to read the normal capture's data
6326 if (mPipeSource != 0) {
6327 size_t framesToRead = mBufferSize / mFrameSize;
Andy Hung57446612015-04-19 23:56:46 -07006328 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
Glenn Kastend79072e2016-01-06 08:41:20 -08006329 framesToRead);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006330 if (framesRead == 0) {
6331 // since pipe is non-blocking, simulate blocking input
6332 sleepUs = (framesToRead * 1000000LL) / mSampleRate;
6333 }
6334 // otherwise use the HAL / AudioStreamIn directly
6335 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07006336 ATRACE_BEGIN("read");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006337 ssize_t bytesRead = mInput->stream->read(mInput->stream,
Andy Hung57446612015-04-19 23:56:46 -07006338 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize);
Glenn Kastenec6a7032016-03-14 07:40:23 -07006339 ATRACE_END();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006340 if (bytesRead < 0) {
6341 framesRead = bytesRead;
6342 } else {
6343 framesRead = bytesRead / mFrameSize;
6344 }
6345 }
6346
Andy Hung3f0c9022016-01-15 17:49:46 -08006347 // Update server timestamp with server stats
6348 // systemTime() is optional if the hardware supports timestamps.
6349 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
6350 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6351
6352 // Update server timestamp with kernel stats
Andy Hung69ce44d2016-07-18 12:14:25 -07006353 if (mInput->stream->get_capture_position != nullptr
6354 && mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08006355 int64_t position, time;
6356 int ret = mInput->stream->get_capture_position(mInput->stream, &position, &time);
6357 if (ret == NO_ERROR) {
6358 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
6359 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
6360 // Note: In general record buffers should tend to be empty in
6361 // a properly running pipeline.
6362 //
6363 // Also, it is not advantageous to call get_presentation_position during the read
6364 // as the read obtains a lock, preventing the timestamp call from executing.
6365 }
6366 }
6367 // Use this to track timestamp information
6368 // ALOGD("%s", mTimestamp.toString().c_str());
6369
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006370 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006371 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006372 // Force input into standby so that it tries to recover at next read attempt
6373 inputStandBy();
6374 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006375 }
6376 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006377 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006378 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006379 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006380
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006381 if (mTeeSink != 0) {
Andy Hung57446612015-04-19 23:56:46 -07006382 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006383 }
6384 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006385 {
6386 size_t part1 = mRsmpInFramesP2 - rear;
6387 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07006388 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006389 (framesRead - part1) * mFrameSize);
6390 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006391 }
6392 rear = mRsmpInRear += framesRead;
6393
6394 size = activeTracks.size();
6395 // loop over each active track
6396 for (size_t i = 0; i < size; i++) {
6397 activeTrack = activeTracks[i];
6398
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006399 // skip fast tracks, as those are handled directly by FastCapture
6400 if (activeTrack->isFastTrack()) {
6401 continue;
6402 }
6403
Andy Hung73c02e42015-03-29 01:13:58 -07006404 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07006405 // TODO: Update the activeTrack buffer converter in case of reconfigure.
6406
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006407 enum {
6408 OVERRUN_UNKNOWN,
6409 OVERRUN_TRUE,
6410 OVERRUN_FALSE
6411 } overrun = OVERRUN_UNKNOWN;
6412
6413 // loop over getNextBuffer to handle circular sink
6414 for (;;) {
6415
6416 activeTrack->mSink.frameCount = ~0;
6417 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
6418 size_t framesOut = activeTrack->mSink.frameCount;
6419 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
6420
Andy Hung73c02e42015-03-29 01:13:58 -07006421 // check available frames and handle overrun conditions
6422 // if the record track isn't draining fast enough.
6423 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006424 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07006425 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
6426 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006427 overrun = OVERRUN_TRUE;
6428 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006429 if (framesOut == 0 || framesIn == 0) {
6430 break;
6431 }
6432
Andy Hung6770c6f2015-04-07 13:43:36 -07006433 // Don't allow framesOut to be larger than what is possible with resampling
6434 // from framesIn.
6435 // This isn't strictly necessary but helps limit buffer resizing in
6436 // RecordBufferConverter. TODO: remove when no longer needed.
6437 framesOut = min(framesOut,
6438 destinationFramesPossible(
6439 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07006440 // process frames from the RecordThread buffer provider to the RecordTrack buffer
6441 framesOut = activeTrack->mRecordBufferConverter->convert(
6442 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006443
6444 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
6445 overrun = OVERRUN_FALSE;
6446 }
6447
6448 if (activeTrack->mFramesToDrop == 0) {
6449 if (framesOut > 0) {
6450 activeTrack->mSink.frameCount = framesOut;
6451 activeTrack->releaseBuffer(&activeTrack->mSink);
6452 }
6453 } else {
6454 // FIXME could do a partial drop of framesOut
6455 if (activeTrack->mFramesToDrop > 0) {
6456 activeTrack->mFramesToDrop -= framesOut;
6457 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006458 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006459 }
6460 } else {
6461 activeTrack->mFramesToDrop += framesOut;
6462 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
6463 activeTrack->mSyncStartEvent->isCancelled()) {
6464 ALOGW("Synced record %s, session %d, trigger session %d",
6465 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
6466 activeTrack->sessionId(),
6467 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08006468 activeTrack->mSyncStartEvent->triggerSession() :
6469 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006470 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006471 }
6472 }
6473 }
6474
6475 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006476 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006477 }
6478 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006479
6480 switch (overrun) {
6481 case OVERRUN_TRUE:
6482 // client isn't retrieving buffers fast enough
6483 if (!activeTrack->setOverflow()) {
6484 nsecs_t now = systemTime();
6485 // FIXME should lastWarning per track?
6486 if ((now - lastWarning) > kWarningThrottleNs) {
6487 ALOGW("RecordThread: buffer overflow");
6488 lastWarning = now;
6489 }
6490 }
6491 break;
6492 case OVERRUN_FALSE:
6493 activeTrack->clearOverflow();
6494 break;
6495 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006496 break;
6497 }
6498
Andy Hung3f0c9022016-01-15 17:49:46 -08006499 // update frame information and push timestamp out
6500 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08006501 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08006502 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
6503 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006504 }
6505
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006506unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08006507 // enable changes in effect chain
6508 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006509 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08006510 }
6511
Glenn Kasten93e471f2013-08-19 08:40:07 -07006512 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08006513
6514 {
6515 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07006516 for (size_t i = 0; i < mTracks.size(); i++) {
6517 sp<RecordTrack> track = mTracks[i];
6518 track->invalidate();
6519 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006520 mActiveTracks.clear();
6521 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08006522 mStartStopCond.broadcast();
6523 }
6524
6525 releaseWakeLock();
6526
6527 ALOGV("RecordThread %p exiting", this);
6528 return false;
6529}
6530
Glenn Kasten93e471f2013-08-19 08:40:07 -07006531void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08006532{
6533 if (!mStandby) {
6534 inputStandBy();
6535 mStandby = true;
6536 }
6537}
6538
6539void AudioFlinger::RecordThread::inputStandBy()
6540{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006541 // Idle the fast capture if it's currently running
6542 if (mFastCapture != 0) {
6543 FastCaptureStateQueue *sq = mFastCapture->sq();
6544 FastCaptureState *state = sq->begin();
6545 if (!(state->mCommand & FastCaptureState::IDLE)) {
6546 state->mCommand = FastCaptureState::COLD_IDLE;
6547 state->mColdFutexAddr = &mFastCaptureFutex;
6548 state->mColdGen++;
6549 mFastCaptureFutex = 0;
6550 sq->end();
6551 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
6552 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
6553#if 0
6554 if (kUseFastCapture == FastCapture_Dynamic) {
6555 // FIXME
6556 }
6557#endif
6558#ifdef AUDIO_WATCHDOG
6559 // FIXME
6560#endif
6561 } else {
6562 sq->end(false /*didModify*/);
6563 }
6564 }
Eric Laurent81784c32012-11-19 14:55:58 -08006565 mInput->stream->common.standby(&mInput->stream->common);
6566}
6567
Glenn Kasten05997e22014-03-13 15:08:33 -07006568// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07006569sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08006570 const sp<AudioFlinger::Client>& client,
6571 uint32_t sampleRate,
6572 audio_format_t format,
6573 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08006574 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08006575 audio_session_t sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07006576 size_t *notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006577 int uid,
Eric Laurent05067782016-06-01 18:27:28 -07006578 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08006579 pid_t tid,
6580 status_t *status)
6581{
Glenn Kasten74935e42013-12-19 08:56:45 -08006582 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08006583 sp<RecordTrack> track;
6584 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07006585 audio_input_flags_t inputFlags = mInput->flags;
6586
6587 // special case for FAST flag considered OK if fast capture is present
6588 if (hasFastCapture()) {
6589 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
6590 }
6591
6592 // Check if requested flags are compatible with output stream flags
6593 if ((*flags & inputFlags) != *flags) {
6594 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
6595 " input flags (%08x)",
6596 *flags, inputFlags);
6597 *flags = (audio_input_flags_t)(*flags & inputFlags);
6598 }
Eric Laurent81784c32012-11-19 14:55:58 -08006599
Glenn Kasten90e58b12013-07-31 16:16:02 -07006600 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07006601 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006602 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07006603 // we formerly checked for a callback handler (non-0 tid),
6604 // but that is no longer required for TRANSFER_OBTAIN mode
6605 //
Glenn Kasten74105912014-07-03 12:28:53 -07006606 // frame count is not specified, or is exactly the pipe depth
6607 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006608 // PCM data
6609 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006610 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006611 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006612 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006613 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006614 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07006615 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006616 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006617 hasFastCapture() &&
6618 // there are sufficient fast track slots available
6619 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07006620 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07006621 // check compatibility with audio effects.
6622 Mutex::Autolock _l(mLock);
6623 // Do not accept FAST flag if the session has software effects
6624 sp<EffectChain> chain = getEffectChain_l(sessionId);
6625 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07006626 audio_input_flags_t old = *flags;
6627 chain->checkInputFlagCompatibility(flags);
6628 if (old != *flags) {
6629 ALOGV("AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
6630 (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07006631 }
6632 }
Eric Laurent122f7e72016-06-29 11:53:29 -07006633 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07006634 "AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
6635 frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006636 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006637 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
Glenn Kasten74105912014-07-03 12:28:53 -07006638 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006639 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07006640 frameCount, mFrameCount, mPipeFramesP2,
6641 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
6642 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07006643 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07006644 }
6645 }
6646
6647 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07006648 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07006649 // fast track: frame count is exactly the pipe depth
6650 frameCount = mPipeFramesP2;
6651 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
6652 *notificationFrames = mFrameCount;
6653 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006654 // not fast track: max notification period is resampled equivalent of one HAL buffer time
6655 // or 20 ms if there is a fast capture
6656 // TODO This could be a roundupRatio inline, and const
6657 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
6658 * sampleRate + mSampleRate - 1) / mSampleRate;
6659 // minimum number of notification periods is at least kMinNotifications,
6660 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
6661 static const size_t kMinNotifications = 3;
6662 static const uint32_t kMinMs = 30;
6663 // TODO This could be a roundupRatio inline
6664 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
6665 // TODO This could be a roundupRatio inline
6666 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
6667 maxNotificationFrames;
6668 const size_t minFrameCount = maxNotificationFrames *
6669 max(kMinNotifications, minNotificationsByMs);
6670 frameCount = max(frameCount, minFrameCount);
6671 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
6672 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07006673 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07006674 }
Glenn Kasten74935e42013-12-19 08:56:45 -08006675 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07006676
Glenn Kasten15e57982013-09-24 11:52:37 -07006677 lStatus = initCheck();
6678 if (lStatus != NO_ERROR) {
6679 ALOGE("createRecordTrack_l() audio driver not initialized");
6680 goto Exit;
6681 }
Eric Laurent81784c32012-11-19 14:55:58 -08006682
6683 { // scope for mLock
6684 Mutex::Autolock _l(mLock);
6685
6686 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07006687 format, channelMask, frameCount, NULL, sessionId, uid,
6688 *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08006689
Glenn Kasten03003332013-08-06 15:40:54 -07006690 lStatus = track->initCheck();
6691 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07006692 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08006693 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08006694 goto Exit;
6695 }
6696 mTracks.add(track);
6697
6698 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6699 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6700 mAudioFlinger->btNrecIsOff();
6701 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6702 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006703
Eric Laurent05067782016-06-01 18:27:28 -07006704 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006705 pid_t callingPid = IPCThreadState::self()->getCallingPid();
6706 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
6707 // so ask activity manager to do this on our behalf
6708 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
6709 }
Eric Laurent81784c32012-11-19 14:55:58 -08006710 }
Glenn Kasten05997e22014-03-13 15:08:33 -07006711
Eric Laurent81784c32012-11-19 14:55:58 -08006712 lStatus = NO_ERROR;
6713
6714Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07006715 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08006716 return track;
6717}
6718
6719status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6720 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08006721 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08006722{
6723 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6724 sp<ThreadBase> strongMe = this;
6725 status_t status = NO_ERROR;
6726
6727 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006728 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006729 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006730 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08006731 triggerSession,
6732 recordTrack->sessionId(),
6733 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006734 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08006735 // Sync event can be cancelled by the trigger session if the track is not in a
6736 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006737 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006738 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006739 } else {
6740 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006741 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006742 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08006743 }
6744 }
6745
6746 {
Glenn Kasten47c20702013-08-13 15:37:35 -07006747 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08006748 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006749 if (mActiveTracks.indexOf(recordTrack) >= 0) {
6750 if (recordTrack->mState == TrackBase::PAUSING) {
6751 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006752 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006753 } else {
6754 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08006755 }
6756 return status;
6757 }
6758
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006759 // TODO consider other ways of handling this, such as changing the state to :STARTING and
6760 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6761 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006762 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08006763 mActiveTracks.add(recordTrack);
6764 mActiveTracksGen++;
Eric Laurent83b88082014-06-20 18:31:16 -07006765 status_t status = NO_ERROR;
6766 if (recordTrack->isExternalTrack()) {
6767 mLock.unlock();
Glenn Kastend848eb42016-03-08 13:42:11 -08006768 status = AudioSystem::startInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006769 mLock.lock();
6770 // FIXME should verify that recordTrack is still in mActiveTracks
6771 if (status != NO_ERROR) {
6772 mActiveTracks.remove(recordTrack);
6773 mActiveTracksGen++;
6774 recordTrack->clearSyncStartEvent();
6775 ALOGV("RecordThread::start error %d", status);
6776 return status;
6777 }
Eric Laurent81784c32012-11-19 14:55:58 -08006778 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006779 // Catch up with current buffer indices if thread is already running.
6780 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
6781 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6782 // see previously buffered data before it called start(), but with greater risk of overrun.
6783
Andy Hung73c02e42015-03-29 01:13:58 -07006784 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07006785 // clear any converter state as new data will be discontinuous
6786 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006787 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08006788 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08006789 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08006790 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006791 ALOGV("Record failed to start");
6792 status = BAD_VALUE;
6793 goto startError;
6794 }
Eric Laurent81784c32012-11-19 14:55:58 -08006795 return status;
6796 }
Glenn Kasten7c027242012-12-26 14:43:16 -08006797
Eric Laurent81784c32012-11-19 14:55:58 -08006798startError:
Eric Laurent83b88082014-06-20 18:31:16 -07006799 if (recordTrack->isExternalTrack()) {
Glenn Kastend848eb42016-03-08 13:42:11 -08006800 AudioSystem::stopInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006801 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006802 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006803 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08006804 return status;
6805}
6806
Eric Laurent81784c32012-11-19 14:55:58 -08006807void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6808{
6809 sp<SyncEvent> strongEvent = event.promote();
6810
6811 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08006812 sp<RefBase> ptr = strongEvent->cookie().promote();
6813 if (ptr != 0) {
6814 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6815 recordTrack->handleSyncStartEvent(strongEvent);
6816 }
Eric Laurent81784c32012-11-19 14:55:58 -08006817 }
6818}
6819
Glenn Kastena8356f62013-07-25 14:37:52 -07006820bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08006821 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07006822 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006823 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08006824 return false;
6825 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006826 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006827 recordTrack->mState = TrackBase::PAUSING;
Eric Laurent5c25d562016-07-13 17:17:45 -07006828 // signal thread to stop
6829 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08006830 // do not wait for mStartStopCond if exiting
6831 if (exitPending()) {
6832 return true;
6833 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006834 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08006835 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006836 // if we have been restarted, recordTrack is in mActiveTracks here
6837 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006838 ALOGV("Record stopped OK");
6839 return true;
6840 }
6841 return false;
6842}
6843
Glenn Kasten0f11b512014-01-31 16:18:54 -08006844bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08006845{
6846 return false;
6847}
6848
Glenn Kasten0f11b512014-01-31 16:18:54 -08006849status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006850{
6851#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6852 if (!isValidSyncEvent(event)) {
6853 return BAD_VALUE;
6854 }
6855
Glenn Kastend848eb42016-03-08 13:42:11 -08006856 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08006857 status_t ret = NAME_NOT_FOUND;
6858
6859 Mutex::Autolock _l(mLock);
6860
6861 for (size_t i = 0; i < mTracks.size(); i++) {
6862 sp<RecordTrack> track = mTracks[i];
6863 if (eventSession == track->sessionId()) {
6864 (void) track->setSyncEvent(event);
6865 ret = NO_ERROR;
6866 }
6867 }
6868 return ret;
6869#else
6870 return BAD_VALUE;
6871#endif
6872}
6873
6874// destroyTrack_l() must be called with ThreadBase::mLock held
6875void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6876{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006877 track->terminate();
6878 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006879 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006880 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006881 removeTrack_l(track);
6882 }
6883}
6884
6885void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6886{
6887 mTracks.remove(track);
6888 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006889 if (track->isFastTrack()) {
6890 ALOG_ASSERT(!mFastTrackAvail);
6891 mFastTrackAvail = true;
6892 }
Eric Laurent81784c32012-11-19 14:55:58 -08006893}
6894
6895void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6896{
6897 dumpInternals(fd, args);
6898 dumpTracks(fd, args);
6899 dumpEffectChains(fd, args);
6900}
6901
6902void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6903{
Elliott Hughes87cebad2014-05-22 10:14:43 -07006904 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08006905
Glenn Kasten44182c22015-03-05 17:12:23 -08006906 dumpBase(fd, args);
6907
6908 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006909 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006910 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006911 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006912 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08006913
Glenn Kasten2f90c512015-12-02 11:40:09 -08006914 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
6915 // while we are dumping it. It may be inconsistent, but it won't mutate!
6916 // This is a large object so we place it on the heap.
6917 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
6918 const FastCaptureDumpState *copy = new FastCaptureDumpState(mFastCaptureDumpState);
6919 copy->dump(fd);
6920 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08006921}
6922
Glenn Kasten0f11b512014-01-31 16:18:54 -08006923void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006924{
6925 const size_t SIZE = 256;
6926 char buffer[SIZE];
6927 String8 result;
6928
Marco Nelissenb2208842014-02-07 14:00:50 -08006929 size_t numtracks = mTracks.size();
6930 size_t numactive = mActiveTracks.size();
6931 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006932 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006933 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006934 dprintf(fd, " of which %zu are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006935 RecordTrack::appendDumpHeader(result);
6936 for (size_t i = 0; i < numtracks ; ++i) {
6937 sp<RecordTrack> track = mTracks[i];
6938 if (track != 0) {
6939 bool active = mActiveTracks.indexOf(track) >= 0;
6940 if (active) {
6941 numactiveseen++;
6942 }
6943 track->dump(buffer, SIZE, active);
6944 result.append(buffer);
6945 }
Eric Laurent81784c32012-11-19 14:55:58 -08006946 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006947 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006948 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006949 }
6950
Marco Nelissenb2208842014-02-07 14:00:50 -08006951 if (numactiveseen != numactive) {
6952 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6953 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006954 result.append(buffer);
6955 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006956 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006957 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006958 if (mTracks.indexOf(track) < 0) {
6959 track->dump(buffer, SIZE, true);
6960 result.append(buffer);
6961 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006962 }
Eric Laurent81784c32012-11-19 14:55:58 -08006963
6964 }
6965 write(fd, result.string(), result.size());
6966}
6967
Andy Hung73c02e42015-03-29 01:13:58 -07006968
6969void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
6970{
6971 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6972 RecordThread *recordThread = (RecordThread *) threadBase.get();
6973 mRsmpInFront = recordThread->mRsmpInRear;
6974 mRsmpInUnrel = 0;
6975}
6976
6977void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
6978 size_t *framesAvailable, bool *hasOverrun)
6979{
6980 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6981 RecordThread *recordThread = (RecordThread *) threadBase.get();
6982 const int32_t rear = recordThread->mRsmpInRear;
6983 const int32_t front = mRsmpInFront;
6984 const ssize_t filled = rear - front;
6985
6986 size_t framesIn;
6987 bool overrun = false;
6988 if (filled < 0) {
6989 // should not happen, but treat like a massive overrun and re-sync
6990 framesIn = 0;
6991 mRsmpInFront = rear;
6992 overrun = true;
6993 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
6994 framesIn = (size_t) filled;
6995 } else {
6996 // client is not keeping up with server, but give it latest data
6997 framesIn = recordThread->mRsmpInFrames;
6998 mRsmpInFront = /* front = */ rear - framesIn;
6999 overrun = true;
7000 }
7001 if (framesAvailable != NULL) {
7002 *framesAvailable = framesIn;
7003 }
7004 if (hasOverrun != NULL) {
7005 *hasOverrun = overrun;
7006 }
7007}
7008
Eric Laurent81784c32012-11-19 14:55:58 -08007009// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007010status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08007011 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08007012{
Andy Hung73c02e42015-03-29 01:13:58 -07007013 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007014 if (threadBase == 0) {
7015 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08007016 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007017 return NOT_ENOUGH_DATA;
7018 }
7019 RecordThread *recordThread = (RecordThread *) threadBase.get();
7020 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07007021 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07007022 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007023 // FIXME should not be P2 (don't want to increase latency)
7024 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08007025 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07007026 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007027 front &= recordThread->mRsmpInFramesP2 - 1;
7028 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07007029 if (part1 > (size_t) filled) {
7030 part1 = filled;
7031 }
7032 size_t ask = buffer->frameCount;
7033 ALOG_ASSERT(ask > 0);
7034 if (part1 > ask) {
7035 part1 = ask;
7036 }
7037 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07007038 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07007039 buffer->raw = NULL;
7040 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07007041 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07007042 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08007043 }
7044
Andy Hung57446612015-04-19 23:56:46 -07007045 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07007046 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07007047 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08007048 return NO_ERROR;
7049}
7050
7051// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007052void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
7053 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08007054{
Glenn Kasten85948432013-08-19 12:09:05 -07007055 size_t stepCount = buffer->frameCount;
7056 if (stepCount == 0) {
7057 return;
7058 }
Andy Hung73c02e42015-03-29 01:13:58 -07007059 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
7060 mRsmpInUnrel -= stepCount;
7061 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07007062 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08007063 buffer->frameCount = 0;
7064}
7065
Andy Hung97a893e2015-03-29 01:03:07 -07007066AudioFlinger::RecordThread::RecordBufferConverter::RecordBufferConverter(
7067 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
7068 uint32_t srcSampleRate,
7069 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
7070 uint32_t dstSampleRate) :
7071 mSrcChannelMask(AUDIO_CHANNEL_INVALID), // updateParameters will set following vars
7072 // mSrcFormat
7073 // mSrcSampleRate
7074 // mDstChannelMask
7075 // mDstFormat
7076 // mDstSampleRate
7077 // mSrcChannelCount
7078 // mDstChannelCount
7079 // mDstFrameSize
7080 mBuf(NULL), mBufFrames(0), mBufFrameSize(0),
Andy Hungd330ee42015-04-20 13:23:41 -07007081 mResampler(NULL),
7082 mIsLegacyDownmix(false),
7083 mIsLegacyUpmix(false),
7084 mRequiresFloat(false),
7085 mInputConverterProvider(NULL)
Andy Hung97a893e2015-03-29 01:03:07 -07007086{
7087 (void)updateParameters(srcChannelMask, srcFormat, srcSampleRate,
7088 dstChannelMask, dstFormat, dstSampleRate);
7089}
7090
7091AudioFlinger::RecordThread::RecordBufferConverter::~RecordBufferConverter() {
7092 free(mBuf);
7093 delete mResampler;
Andy Hungd330ee42015-04-20 13:23:41 -07007094 delete mInputConverterProvider;
Andy Hung97a893e2015-03-29 01:03:07 -07007095}
7096
7097size_t AudioFlinger::RecordThread::RecordBufferConverter::convert(void *dst,
7098 AudioBufferProvider *provider, size_t frames)
7099{
Andy Hungd330ee42015-04-20 13:23:41 -07007100 if (mInputConverterProvider != NULL) {
7101 mInputConverterProvider->setBufferProvider(provider);
7102 provider = mInputConverterProvider;
7103 }
7104
7105 if (mResampler == NULL) {
Andy Hung97a893e2015-03-29 01:03:07 -07007106 ALOGVV("NO RESAMPLING sampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
7107 mSrcSampleRate, mSrcFormat, mDstFormat);
7108
7109 AudioBufferProvider::Buffer buffer;
7110 for (size_t i = frames; i > 0; ) {
7111 buffer.frameCount = i;
Glenn Kastend79072e2016-01-06 08:41:20 -08007112 status_t status = provider->getNextBuffer(&buffer);
Andy Hung97a893e2015-03-29 01:03:07 -07007113 if (status != OK || buffer.frameCount == 0) {
7114 frames -= i; // cannot fill request.
7115 break;
7116 }
Andy Hungd330ee42015-04-20 13:23:41 -07007117 // format convert to destination buffer
7118 convertNoResampler(dst, buffer.raw, buffer.frameCount);
Andy Hung97a893e2015-03-29 01:03:07 -07007119
7120 dst = (int8_t*)dst + buffer.frameCount * mDstFrameSize;
7121 i -= buffer.frameCount;
7122 provider->releaseBuffer(&buffer);
7123 }
7124 } else {
7125 ALOGVV("RESAMPLING mSrcSampleRate:%u mDstSampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
7126 mSrcSampleRate, mDstSampleRate, mSrcFormat, mDstFormat);
7127
Andy Hungd330ee42015-04-20 13:23:41 -07007128 // reallocate buffer if needed
7129 if (mBufFrameSize != 0 && mBufFrames < frames) {
7130 free(mBuf);
7131 mBufFrames = frames;
7132 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
7133 }
Andy Hung97a893e2015-03-29 01:03:07 -07007134 // resampler accumulates, but we only have one source track
Andy Hungd330ee42015-04-20 13:23:41 -07007135 memset(mBuf, 0, frames * mBufFrameSize);
7136 frames = mResampler->resample((int32_t*)mBuf, frames, provider);
7137 // format convert to destination buffer
7138 convertResampler(dst, mBuf, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07007139 }
7140 return frames;
7141}
7142
7143status_t AudioFlinger::RecordThread::RecordBufferConverter::updateParameters(
7144 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
7145 uint32_t srcSampleRate,
7146 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
7147 uint32_t dstSampleRate)
7148{
7149 // quick evaluation if there is any change.
7150 if (mSrcFormat == srcFormat
7151 && mSrcChannelMask == srcChannelMask
7152 && mSrcSampleRate == srcSampleRate
7153 && mDstFormat == dstFormat
7154 && mDstChannelMask == dstChannelMask
7155 && mDstSampleRate == dstSampleRate) {
7156 return NO_ERROR;
7157 }
7158
Andy Hungdb4c0312015-05-06 08:46:52 -07007159 ALOGV("RecordBufferConverter updateParameters srcMask:%#x dstMask:%#x"
7160 " srcFormat:%#x dstFormat:%#x srcRate:%u dstRate:%u",
7161 srcChannelMask, dstChannelMask, srcFormat, dstFormat, srcSampleRate, dstSampleRate);
Andy Hung97a893e2015-03-29 01:03:07 -07007162 const bool valid =
7163 audio_is_input_channel(srcChannelMask)
7164 && audio_is_input_channel(dstChannelMask)
7165 && audio_is_valid_format(srcFormat) && audio_is_linear_pcm(srcFormat)
7166 && audio_is_valid_format(dstFormat) && audio_is_linear_pcm(dstFormat)
7167 && (srcSampleRate <= dstSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX)
7168 ; // no upsampling checks for now
7169 if (!valid) {
7170 return BAD_VALUE;
7171 }
7172
7173 mSrcFormat = srcFormat;
7174 mSrcChannelMask = srcChannelMask;
7175 mSrcSampleRate = srcSampleRate;
7176 mDstFormat = dstFormat;
7177 mDstChannelMask = dstChannelMask;
7178 mDstSampleRate = dstSampleRate;
7179
7180 // compute derived parameters
7181 mSrcChannelCount = audio_channel_count_from_in_mask(srcChannelMask);
7182 mDstChannelCount = audio_channel_count_from_in_mask(dstChannelMask);
7183 mDstFrameSize = mDstChannelCount * audio_bytes_per_sample(mDstFormat);
7184
Andy Hungd330ee42015-04-20 13:23:41 -07007185 // do we need to resample?
7186 delete mResampler;
7187 mResampler = NULL;
7188 if (mSrcSampleRate != mDstSampleRate) {
7189 mResampler = AudioResampler::create(AUDIO_FORMAT_PCM_FLOAT,
7190 mSrcChannelCount, mDstSampleRate);
7191 mResampler->setSampleRate(mSrcSampleRate);
7192 mResampler->setVolume(AudioMixer::UNITY_GAIN_FLOAT, AudioMixer::UNITY_GAIN_FLOAT);
7193 }
7194
7195 // are we running legacy channel conversion modes?
7196 mIsLegacyDownmix = (mSrcChannelMask == AUDIO_CHANNEL_IN_STEREO
7197 || mSrcChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK)
7198 && mDstChannelMask == AUDIO_CHANNEL_IN_MONO;
7199 mIsLegacyUpmix = mSrcChannelMask == AUDIO_CHANNEL_IN_MONO
7200 && (mDstChannelMask == AUDIO_CHANNEL_IN_STEREO
7201 || mDstChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK);
7202
7203 // do we need to process in float?
7204 mRequiresFloat = mResampler != NULL || mIsLegacyDownmix || mIsLegacyUpmix;
7205
7206 // do we need a staging buffer to convert for destination (we can still optimize this)?
7207 // we use mBufFrameSize > 0 to indicate both frame size as well as buffer necessity
7208 if (mResampler != NULL) {
7209 mBufFrameSize = max(mSrcChannelCount, FCC_2)
7210 * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
Andy Hunga97630b2015-07-22 23:27:24 -07007211 } else if (mIsLegacyUpmix || mIsLegacyDownmix) { // legacy modes always float
Andy Hungd330ee42015-04-20 13:23:41 -07007212 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
7213 } else if (mSrcChannelMask != mDstChannelMask && mDstFormat != mSrcFormat) {
Andy Hung97a893e2015-03-29 01:03:07 -07007214 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(mSrcFormat);
7215 } else {
7216 mBufFrameSize = 0;
7217 }
7218 mBufFrames = 0; // force the buffer to be resized.
7219
Andy Hungd330ee42015-04-20 13:23:41 -07007220 // do we need an input converter buffer provider to give us float?
7221 delete mInputConverterProvider;
7222 mInputConverterProvider = NULL;
7223 if (mRequiresFloat && mSrcFormat != AUDIO_FORMAT_PCM_FLOAT) {
7224 mInputConverterProvider = new ReformatBufferProvider(
7225 audio_channel_count_from_in_mask(mSrcChannelMask),
7226 mSrcFormat,
7227 AUDIO_FORMAT_PCM_FLOAT,
7228 256 /* provider buffer frame count */);
7229 }
7230
7231 // do we need a remixer to do channel mask conversion
7232 if (!mIsLegacyDownmix && !mIsLegacyUpmix && mSrcChannelMask != mDstChannelMask) {
7233 (void) memcpy_by_index_array_initialization_from_channel_mask(
7234 mIdxAry, ARRAY_SIZE(mIdxAry), mDstChannelMask, mSrcChannelMask);
Andy Hung97a893e2015-03-29 01:03:07 -07007235 }
7236 return NO_ERROR;
7237}
7238
Andy Hungd330ee42015-04-20 13:23:41 -07007239void AudioFlinger::RecordThread::RecordBufferConverter::convertNoResampler(
7240 void *dst, const void *src, size_t frames)
Andy Hung97a893e2015-03-29 01:03:07 -07007241{
Andy Hungd330ee42015-04-20 13:23:41 -07007242 // src is native type unless there is legacy upmix or downmix, whereupon it is float.
Andy Hung97a893e2015-03-29 01:03:07 -07007243 if (mBufFrameSize != 0 && mBufFrames < frames) {
7244 free(mBuf);
7245 mBufFrames = frames;
7246 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
7247 }
Andy Hungd330ee42015-04-20 13:23:41 -07007248 // do we need to do legacy upmix and downmix?
7249 if (mIsLegacyUpmix || mIsLegacyDownmix) {
Andy Hung97a893e2015-03-29 01:03:07 -07007250 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07007251 if (mIsLegacyUpmix) {
7252 upmix_to_stereo_float_from_mono_float((float *)dstBuf,
7253 (const float *)src, frames);
7254 } else /*mIsLegacyDownmix */ {
7255 downmix_to_mono_float_from_stereo_float((float *)dstBuf,
7256 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07007257 }
Andy Hungd330ee42015-04-20 13:23:41 -07007258 if (mBuf != NULL) {
7259 memcpy_by_audio_format(dst, mDstFormat, mBuf, AUDIO_FORMAT_PCM_FLOAT,
7260 frames * mDstChannelCount);
7261 }
7262 return;
7263 }
7264 // do we need to do channel mask conversion?
7265 if (mSrcChannelMask != mDstChannelMask) {
Andy Hung97a893e2015-03-29 01:03:07 -07007266 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07007267 memcpy_by_index_array(dstBuf, mDstChannelCount,
7268 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mSrcFormat), frames);
7269 if (dstBuf == dst) {
7270 return; // format is the same
7271 }
7272 }
7273 // convert to destination buffer
7274 const void *convertBuf = mBuf != NULL ? mBuf : src;
7275 memcpy_by_audio_format(dst, mDstFormat, convertBuf, mSrcFormat,
7276 frames * mDstChannelCount);
7277}
7278
7279void AudioFlinger::RecordThread::RecordBufferConverter::convertResampler(
7280 void *dst, /*not-a-const*/ void *src, size_t frames)
7281{
7282 // src buffer format is ALWAYS float when entering this routine
7283 if (mIsLegacyUpmix) {
7284 ; // mono to stereo already handled by resampler
7285 } else if (mIsLegacyDownmix
7286 || (mSrcChannelMask == mDstChannelMask && mSrcChannelCount == 1)) {
7287 // the resampler outputs stereo for mono input channel (a feature?)
7288 // must convert to mono
7289 downmix_to_mono_float_from_stereo_float((float *)src,
7290 (const float *)src, frames);
7291 } else if (mSrcChannelMask != mDstChannelMask) {
7292 // convert to mono channel again for channel mask conversion (could be skipped
7293 // with further optimization).
Andy Hung97a893e2015-03-29 01:03:07 -07007294 if (mSrcChannelCount == 1) {
Andy Hungd330ee42015-04-20 13:23:41 -07007295 downmix_to_mono_float_from_stereo_float((float *)src,
7296 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07007297 }
Andy Hungd330ee42015-04-20 13:23:41 -07007298 // convert to destination format (in place, OK as float is larger than other types)
7299 if (mDstFormat != AUDIO_FORMAT_PCM_FLOAT) {
7300 memcpy_by_audio_format(src, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
7301 frames * mSrcChannelCount);
7302 }
7303 // channel convert and save to dst
7304 memcpy_by_index_array(dst, mDstChannelCount,
7305 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mDstFormat), frames);
7306 return;
Andy Hung97a893e2015-03-29 01:03:07 -07007307 }
Andy Hungd330ee42015-04-20 13:23:41 -07007308 // convert to destination format and save to dst
7309 memcpy_by_audio_format(dst, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
7310 frames * mDstChannelCount);
Andy Hung97a893e2015-03-29 01:03:07 -07007311}
7312
Eric Laurent10351942014-05-08 18:49:52 -07007313bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
7314 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007315{
7316 bool reconfig = false;
7317
Eric Laurent10351942014-05-08 18:49:52 -07007318 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007319
Eric Laurent10351942014-05-08 18:49:52 -07007320 audio_format_t reqFormat = mFormat;
7321 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07007322 // 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 -07007323 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
7324
7325 AudioParameter param = AudioParameter(keyValuePair);
7326 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07007327
7328 // scope for AutoPark extends to end of method
7329 AutoPark<FastCapture> park(mFastCapture);
7330
Eric Laurent10351942014-05-08 18:49:52 -07007331 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
7332 // channel count change can be requested. Do we mandate the first client defines the
7333 // HAL sampling rate and channel count or do we allow changes on the fly?
7334 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
7335 samplingRate = value;
7336 reconfig = true;
7337 }
7338 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07007339 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07007340 status = BAD_VALUE;
7341 } else {
7342 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08007343 reconfig = true;
7344 }
Eric Laurent10351942014-05-08 18:49:52 -07007345 }
7346 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
7347 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07007348 if (!audio_is_input_channel(mask) ||
7349 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007350 status = BAD_VALUE;
7351 } else {
7352 channelMask = mask;
7353 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007354 }
Eric Laurent10351942014-05-08 18:49:52 -07007355 }
7356 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7357 // do not accept frame count changes if tracks are open as the track buffer
7358 // size depends on frame count and correct behavior would not be guaranteed
7359 // if frame count is changed after track creation
7360 if (mActiveTracks.size() > 0) {
7361 status = INVALID_OPERATION;
7362 } else {
7363 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007364 }
Eric Laurent10351942014-05-08 18:49:52 -07007365 }
7366 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7367 // forward device change to effects that have requested to be
7368 // aware of attached audio device.
7369 for (size_t i = 0; i < mEffectChains.size(); i++) {
7370 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08007371 }
Eric Laurent81784c32012-11-19 14:55:58 -08007372
Eric Laurent10351942014-05-08 18:49:52 -07007373 // store input device and output device but do not forward output device to audio HAL.
7374 // Note that status is ignored by the caller for output device
7375 // (see AudioFlinger::setParameters()
7376 if (audio_is_output_devices(value)) {
7377 mOutDevice = value;
7378 status = BAD_VALUE;
7379 } else {
7380 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07007381 if (value != AUDIO_DEVICE_NONE) {
7382 mPrevInDevice = value;
7383 }
Eric Laurent10351942014-05-08 18:49:52 -07007384 // disable AEC and NS if the device is a BT SCO headset supporting those
7385 // pre processings
7386 if (mTracks.size() > 0) {
7387 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7388 mAudioFlinger->btNrecIsOff();
7389 for (size_t i = 0; i < mTracks.size(); i++) {
7390 sp<RecordTrack> track = mTracks[i];
7391 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7392 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08007393 }
7394 }
7395 }
Eric Laurent10351942014-05-08 18:49:52 -07007396 }
7397 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
7398 mAudioSource != (audio_source_t)value) {
7399 // forward device change to effects that have requested to be
7400 // aware of attached audio device.
7401 for (size_t i = 0; i < mEffectChains.size(); i++) {
7402 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08007403 }
Eric Laurent10351942014-05-08 18:49:52 -07007404 mAudioSource = (audio_source_t)value;
7405 }
Glenn Kastene198c362013-08-13 09:13:36 -07007406
Eric Laurent10351942014-05-08 18:49:52 -07007407 if (status == NO_ERROR) {
7408 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7409 keyValuePair.string());
7410 if (status == INVALID_OPERATION) {
7411 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08007412 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7413 keyValuePair.string());
Eric Laurent10351942014-05-08 18:49:52 -07007414 }
7415 if (reconfig) {
7416 if (status == BAD_VALUE &&
Andy Hung97a893e2015-03-29 01:03:07 -07007417 audio_is_linear_pcm(mInput->stream->common.get_format(&mInput->stream->common)) &&
7418 audio_is_linear_pcm(reqFormat) &&
Eric Laurent10351942014-05-08 18:49:52 -07007419 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
Andy Hung97a893e2015-03-29 01:03:07 -07007420 <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate)) &&
Andy Hunge5412692014-05-16 11:25:07 -07007421 audio_channel_count_from_in_mask(
Andy Hungd1abb8f2015-05-05 23:42:34 -07007422 mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007423 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007424 }
Eric Laurent10351942014-05-08 18:49:52 -07007425 if (status == NO_ERROR) {
7426 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007427 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08007428 }
7429 }
Eric Laurent81784c32012-11-19 14:55:58 -08007430 }
Eric Laurent10351942014-05-08 18:49:52 -07007431
Eric Laurent81784c32012-11-19 14:55:58 -08007432 return reconfig;
7433}
7434
7435String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
7436{
Eric Laurent81784c32012-11-19 14:55:58 -08007437 Mutex::Autolock _l(mLock);
7438 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07007439 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08007440 }
7441
Glenn Kastend8ea6992013-07-16 14:17:15 -07007442 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
7443 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08007444 free(s);
7445 return out_s8;
7446}
7447
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007448void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007449 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7450
7451 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08007452
7453 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007454 case AUDIO_INPUT_OPENED:
7455 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07007456 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07007457 desc->mChannelMask = mChannelMask;
7458 desc->mSamplingRate = mSampleRate;
7459 desc->mFormat = mFormat;
7460 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07007461 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07007462 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007463 break;
7464
Eric Laurent73e26b62015-04-27 16:55:58 -07007465 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08007466 default:
7467 break;
7468 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007469 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08007470}
7471
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007472void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007473{
Eric Laurent81784c32012-11-19 14:55:58 -08007474 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
7475 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Andy Hunge5412692014-05-16 11:25:07 -07007476 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Andy Hungd330ee42015-04-20 13:23:41 -07007477 if (mChannelCount > FCC_8) {
7478 ALOGE("HAL channel count %d > %d", mChannelCount, FCC_8);
7479 }
Andy Hung463be252014-07-10 16:56:07 -07007480 mHALFormat = mInput->stream->common.get_format(&mInput->stream->common);
7481 mFormat = mHALFormat;
Andy Hungd330ee42015-04-20 13:23:41 -07007482 if (!audio_is_linear_pcm(mFormat)) {
7483 ALOGE("HAL format %#x is not linear pcm", mFormat);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07007484 }
Eric Laurent665470b2014-07-03 16:37:08 -07007485 mFrameSize = audio_stream_in_frame_size(mInput->stream);
Glenn Kasten548efc92012-11-29 08:48:51 -08007486 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
7487 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007488 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08007489 // 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 -07007490 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08007491 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007492 // A larger value should allow more old data to be read after a track calls start(),
7493 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07007494 //
7495 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08007496 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07007497 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07007498 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07007499 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007500
7501 // TODO optimize audio capture buffer sizes ...
7502 // Here we calculate the size of the sliding buffer used as a source
7503 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
7504 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
7505 // be better to have it derived from the pipe depth in the long term.
7506 // The current value is higher than necessary. However it should not add to latency.
7507
Glenn Kasten85948432013-08-19 12:09:05 -07007508 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Andy Hung0a01c2f2015-09-21 12:44:54 -07007509 size_t bufferSize = (mRsmpInFramesP2 + mFrameCount - 1) * mFrameSize;
7510 (void)posix_memalign(&mRsmpInBuffer, 32, bufferSize);
7511 memset(mRsmpInBuffer, 0, bufferSize); // if posix_memalign fails, will segv here.
Eric Laurent81784c32012-11-19 14:55:58 -08007512
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007513 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
7514 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08007515}
7516
Glenn Kasten5f972c02014-01-13 09:59:31 -08007517uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08007518{
7519 Mutex::Autolock _l(mLock);
7520 if (initCheck() != NO_ERROR) {
7521 return 0;
7522 }
7523
7524 return mInput->stream->get_input_frames_lost(mInput->stream);
7525}
7526
Eric Laurent4c415062016-06-17 16:14:16 -07007527// hasAudioSession_l() must be called with ThreadBase::mLock held
7528uint32_t AudioFlinger::RecordThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08007529{
Eric Laurent81784c32012-11-19 14:55:58 -08007530 uint32_t result = 0;
7531 if (getEffectChain_l(sessionId) != 0) {
7532 result = EFFECT_SESSION;
7533 }
7534
7535 for (size_t i = 0; i < mTracks.size(); ++i) {
7536 if (sessionId == mTracks[i]->sessionId()) {
7537 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07007538 if (mTracks[i]->isFastTrack()) {
7539 result |= FAST_SESSION;
7540 }
Eric Laurent81784c32012-11-19 14:55:58 -08007541 break;
7542 }
7543 }
7544
7545 return result;
7546}
7547
Glenn Kastend848eb42016-03-08 13:42:11 -08007548KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08007549{
Glenn Kastend848eb42016-03-08 13:42:11 -08007550 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08007551 Mutex::Autolock _l(mLock);
7552 for (size_t j = 0; j < mTracks.size(); ++j) {
7553 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08007554 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08007555 if (ids.indexOfKey(sessionId) < 0) {
7556 ids.add(sessionId, true);
7557 }
7558 }
7559 return ids;
7560}
7561
7562AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7563{
7564 Mutex::Autolock _l(mLock);
7565 AudioStreamIn *input = mInput;
7566 mInput = NULL;
7567 return input;
7568}
7569
7570// this method must always be called either with ThreadBase mLock held or inside the thread loop
7571audio_stream_t* AudioFlinger::RecordThread::stream() const
7572{
7573 if (mInput == NULL) {
7574 return NULL;
7575 }
7576 return &mInput->stream->common;
7577}
7578
7579status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7580{
7581 // only one chain per input thread
7582 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07007583 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08007584 return INVALID_OPERATION;
7585 }
7586 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07007587 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08007588 chain->setInBuffer(NULL);
7589 chain->setOutBuffer(NULL);
7590
7591 checkSuspendOnAddEffectChain_l(chain);
7592
Eric Laurent1b928682014-10-02 19:41:47 -07007593 // make sure enabled pre processing effects state is communicated to the HAL as we
7594 // just moved them to a new input stream.
7595 chain->syncHalEffectsState();
7596
Eric Laurent81784c32012-11-19 14:55:58 -08007597 mEffectChains.add(chain);
7598
7599 return NO_ERROR;
7600}
7601
7602size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7603{
7604 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7605 ALOGW_IF(mEffectChains.size() != 1,
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007606 "removeEffectChain_l() %p invalid chain size %zu on thread %p",
Eric Laurent81784c32012-11-19 14:55:58 -08007607 chain.get(), mEffectChains.size(), this);
7608 if (mEffectChains.size() == 1) {
7609 mEffectChains.removeAt(0);
7610 }
7611 return 0;
7612}
7613
Eric Laurent1c333e22014-05-20 10:48:17 -07007614status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7615 audio_patch_handle_t *handle)
7616{
7617 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007618
7619 // store new device and send to effects
7620 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07007621 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07007622 for (size_t i = 0; i < mEffectChains.size(); i++) {
7623 mEffectChains[i]->setDevice_l(mInDevice);
7624 }
7625
7626 // disable AEC and NS if the device is a BT SCO headset supporting those
7627 // pre processings
7628 if (mTracks.size() > 0) {
7629 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7630 mAudioFlinger->btNrecIsOff();
7631 for (size_t i = 0; i < mTracks.size(); i++) {
7632 sp<RecordTrack> track = mTracks[i];
7633 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7634 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
7635 }
7636 }
7637
7638 // store new source and send to effects
7639 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7640 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07007641 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07007642 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07007643 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007644 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007645
Eric Laurent054d9d32015-04-24 08:48:48 -07007646 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007647 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
7648 status = hwDevice->create_audio_patch(hwDevice,
7649 patch->num_sources,
7650 patch->sources,
7651 patch->num_sinks,
7652 patch->sinks,
7653 handle);
7654 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007655 char *address;
7656 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7657 address = audio_device_address_to_parameter(
7658 patch->sources[0].ext.device.type,
7659 patch->sources[0].ext.device.address);
7660 } else {
7661 address = (char *)calloc(1, 1);
7662 }
7663 AudioParameter param = AudioParameter(String8(address));
7664 free(address);
7665 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING),
7666 (int)patch->sources[0].ext.device.type);
7667 param.addInt(String8(AUDIO_PARAMETER_STREAM_INPUT_SOURCE),
7668 (int)patch->sinks[0].ext.mix.usecase.source);
7669 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7670 param.toString().string());
7671 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07007672 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007673
Eric Laurente8726fe2015-06-26 09:39:24 -07007674 if (mInDevice != mPrevInDevice) {
7675 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7676 mPrevInDevice = mInDevice;
7677 }
Eric Laurent296fb132015-05-01 11:38:42 -07007678
Eric Laurent1c333e22014-05-20 10:48:17 -07007679 return status;
7680}
7681
7682status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7683{
7684 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007685
7686 mInDevice = AUDIO_DEVICE_NONE;
7687
Eric Laurent1c333e22014-05-20 10:48:17 -07007688 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
7689 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
7690 status = hwDevice->release_audio_patch(hwDevice, handle);
7691 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007692 AudioParameter param;
7693 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
7694 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7695 param.toString().string());
Eric Laurent1c333e22014-05-20 10:48:17 -07007696 }
7697 return status;
7698}
7699
Eric Laurent83b88082014-06-20 18:31:16 -07007700void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
7701{
7702 Mutex::Autolock _l(mLock);
7703 mTracks.add(record);
7704}
7705
7706void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
7707{
7708 Mutex::Autolock _l(mLock);
7709 destroyTrack_l(record);
7710}
7711
7712void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
7713{
7714 ThreadBase::getAudioPortConfig(config);
7715 config->role = AUDIO_PORT_ROLE_SINK;
7716 config->ext.mix.hw_module = mInput->audioHwDev->handle();
7717 config->ext.mix.usecase.source = mAudioSource;
7718}
Eric Laurent1c333e22014-05-20 10:48:17 -07007719
Glenn Kasten63238ef2015-03-02 15:50:29 -08007720} // namespace android