blob: e00070c299074be6c7850d5f90d4b5475d467065 [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 }
1275 audio_input_flags_t flags = mInput->flags;
1276 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1277 if (flags & AUDIO_INPUT_FLAG_RAW) {
1278 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1279 desc->name, mThreadName);
1280 return BAD_VALUE;
1281 }
1282 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1283 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1284 desc->name, mThreadName);
1285 return BAD_VALUE;
1286 }
1287 }
1288 return NO_ERROR;
1289}
1290
1291// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1292status_t AudioFlinger::PlaybackThread::checkEffectCompatibility_l(
1293 const effect_descriptor_t *desc, audio_session_t sessionId)
1294{
1295 // no preprocessing on playback threads
1296 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
1297 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback"
1298 " thread %s", desc->name, mThreadName);
1299 return BAD_VALUE;
1300 }
1301
1302 switch (mType) {
1303 case MIXER: {
1304 // Reject any effect on mixer multichannel sinks.
1305 // TODO: fix both format and multichannel issues with effects.
1306 if (mChannelCount != FCC_2) {
1307 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d) on MIXER"
1308 " thread %s", desc->name, mChannelCount, mThreadName);
1309 return BAD_VALUE;
1310 }
1311 audio_output_flags_t flags = mOutput->flags;
1312 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1313 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1314 // global effects are applied only to non fast tracks if they are SW
1315 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1316 break;
1317 }
1318 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1319 // only post processing on output stage session
1320 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1321 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1322 " on output stage session", desc->name);
1323 return BAD_VALUE;
1324 }
1325 } else {
1326 // no restriction on effects applied on non fast tracks
1327 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1328 break;
1329 }
1330 }
1331 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
1332 ALOGW("checkEffectCompatibility_l(): effect %s on playback thread in raw mode",
1333 desc->name);
1334 return BAD_VALUE;
1335 }
1336 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1337 ALOGW("checkEffectCompatibility_l(): non HW effect %s on playback thread"
1338 " in fast mode", desc->name);
1339 return BAD_VALUE;
1340 }
1341 }
1342 } break;
1343 case OFFLOAD:
1344 // only offloadable effects on offload thread
1345 if ((desc->flags & EFFECT_FLAG_OFFLOAD_MASK) != EFFECT_FLAG_OFFLOAD_SUPPORTED) {
1346 ALOGW("checkEffectCompatibility_l(): non offloadable effect %s created on"
1347 " OFFLOAD thread %s", desc->name, mThreadName);
1348 return BAD_VALUE;
1349 }
1350 break;
1351 case DIRECT:
1352 // Reject any effect on Direct output threads for now, since the format of
1353 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1354 ALOGW("checkEffectCompatibility_l(): effect %s on DIRECT output thread %s",
1355 desc->name, mThreadName);
1356 return BAD_VALUE;
1357 case DUPLICATING:
1358 // Reject any effect on mixer multichannel sinks.
1359 // TODO: fix both format and multichannel issues with effects.
1360 if (mChannelCount != FCC_2) {
1361 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d)"
1362 " on DUPLICATING thread %s", desc->name, mChannelCount, mThreadName);
1363 return BAD_VALUE;
1364 }
1365 if ((sessionId == AUDIO_SESSION_OUTPUT_STAGE) || (sessionId == AUDIO_SESSION_OUTPUT_MIX)) {
1366 ALOGW("checkEffectCompatibility_l(): global effect %s on DUPLICATING"
1367 " thread %s", desc->name, mThreadName);
1368 return BAD_VALUE;
1369 }
1370 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
1371 ALOGW("checkEffectCompatibility_l(): post processing effect %s on"
1372 " DUPLICATING thread %s", desc->name, mThreadName);
1373 return BAD_VALUE;
1374 }
1375 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1376 ALOGW("checkEffectCompatibility_l(): HW tunneled effect %s on"
1377 " DUPLICATING thread %s", desc->name, mThreadName);
1378 return BAD_VALUE;
1379 }
1380 break;
1381 default:
1382 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1383 }
1384
1385 return NO_ERROR;
1386}
1387
Eric Laurent81784c32012-11-19 14:55:58 -08001388// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1389sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1390 const sp<AudioFlinger::Client>& client,
1391 const sp<IEffectClient>& effectClient,
1392 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001393 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001394 effect_descriptor_t *desc,
1395 int *enabled,
Glenn Kasten9156ef32013-08-06 15:39:08 -07001396 status_t *status)
Eric Laurent81784c32012-11-19 14:55:58 -08001397{
1398 sp<EffectModule> effect;
1399 sp<EffectHandle> handle;
1400 status_t lStatus;
1401 sp<EffectChain> chain;
1402 bool chainCreated = false;
1403 bool effectCreated = false;
1404 bool effectRegistered = false;
1405
1406 lStatus = initCheck();
1407 if (lStatus != NO_ERROR) {
1408 ALOGW("createEffect_l() Audio driver not initialized.");
1409 goto Exit;
1410 }
1411
Eric Laurent81784c32012-11-19 14:55:58 -08001412 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1413
1414 { // scope for mLock
1415 Mutex::Autolock _l(mLock);
1416
Eric Laurent4c415062016-06-17 16:14:16 -07001417 lStatus = checkEffectCompatibility_l(desc, sessionId);
1418 if (lStatus != NO_ERROR) {
1419 goto Exit;
1420 }
1421
Eric Laurent81784c32012-11-19 14:55:58 -08001422 // check for existing effect chain with the requested audio session
1423 chain = getEffectChain_l(sessionId);
1424 if (chain == 0) {
1425 // create a new chain for this session
1426 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1427 chain = new EffectChain(this, sessionId);
1428 addEffectChain_l(chain);
1429 chain->setStrategy(getStrategyForSession_l(sessionId));
1430 chainCreated = true;
1431 } else {
1432 effect = chain->getEffectFromDesc_l(desc);
1433 }
1434
1435 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1436
1437 if (effect == 0) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08001438 audio_unique_id_t id = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001439 // Check CPU and memory usage
1440 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
1441 if (lStatus != NO_ERROR) {
1442 goto Exit;
1443 }
1444 effectRegistered = true;
1445 // create a new effect module if none present in the chain
1446 effect = new EffectModule(this, chain, desc, id, sessionId);
1447 lStatus = effect->status();
1448 if (lStatus != NO_ERROR) {
1449 goto Exit;
1450 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001451 effect->setOffloaded(mType == OFFLOAD, mId);
1452
Eric Laurent81784c32012-11-19 14:55:58 -08001453 lStatus = chain->addEffect_l(effect);
1454 if (lStatus != NO_ERROR) {
1455 goto Exit;
1456 }
1457 effectCreated = true;
1458
1459 effect->setDevice(mOutDevice);
1460 effect->setDevice(mInDevice);
1461 effect->setMode(mAudioFlinger->getMode());
1462 effect->setAudioSource(mAudioSource);
1463 }
1464 // create effect handle and connect it to effect module
1465 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001466 lStatus = handle->initCheck();
1467 if (lStatus == OK) {
1468 lStatus = effect->addHandle(handle.get());
1469 }
Eric Laurent81784c32012-11-19 14:55:58 -08001470 if (enabled != NULL) {
1471 *enabled = (int)effect->isEnabled();
1472 }
1473 }
1474
1475Exit:
1476 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1477 Mutex::Autolock _l(mLock);
1478 if (effectCreated) {
1479 chain->removeEffect_l(effect);
1480 }
1481 if (effectRegistered) {
1482 AudioSystem::unregisterEffect(effect->id());
1483 }
1484 if (chainCreated) {
1485 removeEffectChain_l(chain);
1486 }
1487 handle.clear();
1488 }
1489
Glenn Kasten9156ef32013-08-06 15:39:08 -07001490 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001491 return handle;
1492}
1493
Glenn Kastend848eb42016-03-08 13:42:11 -08001494sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1495 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001496{
1497 Mutex::Autolock _l(mLock);
1498 return getEffect_l(sessionId, effectId);
1499}
1500
Glenn Kastend848eb42016-03-08 13:42:11 -08001501sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1502 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001503{
1504 sp<EffectChain> chain = getEffectChain_l(sessionId);
1505 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1506}
1507
1508// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1509// PlaybackThread::mLock held
1510status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1511{
1512 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001513 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001514 sp<EffectChain> chain = getEffectChain_l(sessionId);
1515 bool chainCreated = false;
1516
Eric Laurent5baf2af2013-09-12 17:37:00 -07001517 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1518 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1519 this, effect->desc().name, effect->desc().flags);
1520
Eric Laurent81784c32012-11-19 14:55:58 -08001521 if (chain == 0) {
1522 // create a new chain for this session
1523 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1524 chain = new EffectChain(this, sessionId);
1525 addEffectChain_l(chain);
1526 chain->setStrategy(getStrategyForSession_l(sessionId));
1527 chainCreated = true;
1528 }
1529 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1530
1531 if (chain->getEffectFromId_l(effect->id()) != 0) {
1532 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1533 this, effect->desc().name, chain.get());
1534 return BAD_VALUE;
1535 }
1536
Eric Laurent5baf2af2013-09-12 17:37:00 -07001537 effect->setOffloaded(mType == OFFLOAD, mId);
1538
Eric Laurent81784c32012-11-19 14:55:58 -08001539 status_t status = chain->addEffect_l(effect);
1540 if (status != NO_ERROR) {
1541 if (chainCreated) {
1542 removeEffectChain_l(chain);
1543 }
1544 return status;
1545 }
1546
1547 effect->setDevice(mOutDevice);
1548 effect->setDevice(mInDevice);
1549 effect->setMode(mAudioFlinger->getMode());
1550 effect->setAudioSource(mAudioSource);
1551 return NO_ERROR;
1552}
1553
1554void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
1555
1556 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
1557 effect_descriptor_t desc = effect->desc();
1558 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1559 detachAuxEffect_l(effect->id());
1560 }
1561
1562 sp<EffectChain> chain = effect->chain().promote();
1563 if (chain != 0) {
1564 // remove effect chain if removing last effect
1565 if (chain->removeEffect_l(effect) == 0) {
1566 removeEffectChain_l(chain);
1567 }
1568 } else {
1569 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1570 }
1571}
1572
1573void AudioFlinger::ThreadBase::lockEffectChains_l(
1574 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1575{
1576 effectChains = mEffectChains;
1577 for (size_t i = 0; i < mEffectChains.size(); i++) {
1578 mEffectChains[i]->lock();
1579 }
1580}
1581
1582void AudioFlinger::ThreadBase::unlockEffectChains(
1583 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1584{
1585 for (size_t i = 0; i < effectChains.size(); i++) {
1586 effectChains[i]->unlock();
1587 }
1588}
1589
Glenn Kastend848eb42016-03-08 13:42:11 -08001590sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001591{
1592 Mutex::Autolock _l(mLock);
1593 return getEffectChain_l(sessionId);
1594}
1595
Glenn Kastend848eb42016-03-08 13:42:11 -08001596sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1597 const
Eric Laurent81784c32012-11-19 14:55:58 -08001598{
1599 size_t size = mEffectChains.size();
1600 for (size_t i = 0; i < size; i++) {
1601 if (mEffectChains[i]->sessionId() == sessionId) {
1602 return mEffectChains[i];
1603 }
1604 }
1605 return 0;
1606}
1607
1608void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1609{
1610 Mutex::Autolock _l(mLock);
1611 size_t size = mEffectChains.size();
1612 for (size_t i = 0; i < size; i++) {
1613 mEffectChains[i]->setMode_l(mode);
1614 }
1615}
1616
Eric Laurent83b88082014-06-20 18:31:16 -07001617void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1618{
1619 config->type = AUDIO_PORT_TYPE_MIX;
1620 config->ext.mix.handle = mId;
1621 config->sample_rate = mSampleRate;
1622 config->format = mFormat;
1623 config->channel_mask = mChannelMask;
1624 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1625 AUDIO_PORT_CONFIG_FORMAT;
1626}
1627
Eric Laurent72e3f392015-05-20 14:43:50 -07001628void AudioFlinger::ThreadBase::systemReady()
1629{
1630 Mutex::Autolock _l(mLock);
1631 if (mSystemReady) {
1632 return;
1633 }
1634 mSystemReady = true;
1635
1636 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1637 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1638 }
1639 mPendingConfigEvents.clear();
1640}
1641
Eric Laurent83b88082014-06-20 18:31:16 -07001642
Eric Laurent81784c32012-11-19 14:55:58 -08001643// ----------------------------------------------------------------------------
1644// Playback
1645// ----------------------------------------------------------------------------
1646
1647AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1648 AudioStreamOut* output,
1649 audio_io_handle_t id,
1650 audio_devices_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07001651 type_t type,
Eric Laurente93cc032016-05-05 10:15:10 -07001652 bool systemReady)
Eric Laurent72e3f392015-05-20 14:43:50 -07001653 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001654 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001655 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001656 mMixerBuffer(NULL),
1657 mMixerBufferSize(0),
1658 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1659 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001660 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001661 mEffectBuffer(NULL),
1662 mEffectBufferSize(0),
1663 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1664 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001665 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001666 mFramesWritten(0),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001667 mActiveTracksGeneration(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001668 // mStreamTypes[] initialized in constructor body
1669 mOutput(output),
Andy Hung69488c42016-05-16 18:43:33 -07001670 mLastWriteTime(-1), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001671 mMixerStatus(MIXER_IDLE),
1672 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001673 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001674 mBytesRemaining(0),
1675 mCurrentWriteLength(0),
1676 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001677 mWriteAckSequence(0),
1678 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001679 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001680 mScreenState(AudioFlinger::mScreenState),
1681 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001682 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Andy Hunge10393e2015-06-12 13:59:33 -07001683 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001684{
Glenn Kastend7dca052015-03-05 16:05:54 -08001685 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1686 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001687
1688 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1689 // it would be safer to explicitly pass initial masterVolume/masterMute as
1690 // parameter.
1691 //
1692 // If the HAL we are using has support for master volume or master mute,
1693 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1694 // and the mute set to false).
1695 mMasterVolume = audioFlinger->masterVolume_l();
1696 mMasterMute = audioFlinger->masterMute_l();
1697 if (mOutput && mOutput->audioHwDev) {
1698 if (mOutput->audioHwDev->canSetMasterVolume()) {
1699 mMasterVolume = 1.0;
1700 }
1701
1702 if (mOutput->audioHwDev->canSetMasterMute()) {
1703 mMasterMute = false;
1704 }
1705 }
1706
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001707 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001708
Eric Laurent223fd5c2014-11-11 13:43:36 -08001709 // ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001710 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001711 stream = (audio_stream_type_t) (stream + 1)) {
1712 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1713 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1714 }
Eric Laurent81784c32012-11-19 14:55:58 -08001715}
1716
1717AudioFlinger::PlaybackThread::~PlaybackThread()
1718{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001719 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001720 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001721 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001722 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001723}
1724
1725void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1726{
1727 dumpInternals(fd, args);
1728 dumpTracks(fd, args);
1729 dumpEffectChains(fd, args);
1730}
1731
Glenn Kasten0f11b512014-01-31 16:18:54 -08001732void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001733{
1734 const size_t SIZE = 256;
1735 char buffer[SIZE];
1736 String8 result;
1737
Marco Nelissenb2208842014-02-07 14:00:50 -08001738 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001739 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1740 const stream_type_t *st = &mStreamTypes[i];
1741 if (i > 0) {
1742 result.appendFormat(", ");
1743 }
1744 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1745 if (st->mute) {
1746 result.append("M");
1747 }
1748 }
1749 result.append("\n");
1750 write(fd, result.string(), result.length());
1751 result.clear();
1752
Eric Laurent81784c32012-11-19 14:55:58 -08001753 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1754 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001755 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001756 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001757
1758 size_t numtracks = mTracks.size();
1759 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001760 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001761 size_t numactiveseen = 0;
1762 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001763 dprintf(fd, " of which %zu are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001764 Track::appendDumpHeader(result);
1765 for (size_t i = 0; i < numtracks; ++i) {
1766 sp<Track> track = mTracks[i];
1767 if (track != 0) {
1768 bool active = mActiveTracks.indexOf(track) >= 0;
1769 if (active) {
1770 numactiveseen++;
1771 }
1772 track->dump(buffer, SIZE, active);
1773 result.append(buffer);
1774 }
1775 }
1776 } else {
1777 result.append("\n");
1778 }
1779 if (numactiveseen != numactive) {
1780 // some tracks in the active list were not in the tracks list
1781 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1782 " not in the track list\n");
1783 result.append(buffer);
1784 Track::appendDumpHeader(result);
1785 for (size_t i = 0; i < numactive; ++i) {
1786 sp<Track> track = mActiveTracks[i].promote();
1787 if (track != 0 && mTracks.indexOf(track) < 0) {
1788 track->dump(buffer, SIZE, true);
1789 result.append(buffer);
1790 }
1791 }
1792 }
1793
1794 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001795}
1796
1797void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1798{
Glenn Kasten97b7b752014-09-28 13:04:24 -07001799 dprintf(fd, "\nOutput thread %p type %d (%s):\n", this, type(), threadTypeToString(type()));
Glenn Kasten44182c22015-03-05 17:12:23 -08001800
1801 dumpBase(fd, args);
1802
Elliott Hughes87cebad2014-05-22 10:14:43 -07001803 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001804 dprintf(fd, " Last write occurred (msecs): %llu\n",
1805 (unsigned long long) ns2ms(systemTime() - mLastWriteTime));
Elliott Hughes87cebad2014-05-22 10:14:43 -07001806 dprintf(fd, " Total writes: %d\n", mNumWrites);
1807 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1808 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1809 dprintf(fd, " Suspend count: %d\n", mSuspended);
1810 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1811 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1812 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1813 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08001814 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001815 AudioStreamOut *output = mOutput;
1816 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
1817 String8 flagsAsString = outputFlagsToString(flags);
1818 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n", output, flags, flagsAsString.string());
Eric Laurent81784c32012-11-19 14:55:58 -08001819}
1820
1821// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001822
1823void AudioFlinger::PlaybackThread::onFirstRef()
1824{
Glenn Kastend7dca052015-03-05 16:05:54 -08001825 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001826}
1827
1828// ThreadBase virtuals
1829void AudioFlinger::PlaybackThread::preExit()
1830{
1831 ALOGV(" preExit()");
1832 // FIXME this is using hard-coded strings but in the future, this functionality will be
1833 // converted to use audio HAL extensions required to support tunneling
1834 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1835}
1836
1837// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1838sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1839 const sp<AudioFlinger::Client>& client,
1840 audio_stream_type_t streamType,
1841 uint32_t sampleRate,
1842 audio_format_t format,
1843 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001844 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001845 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08001846 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07001847 audio_output_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08001848 pid_t tid,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001849 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -08001850 status_t *status)
1851{
Glenn Kasten74935e42013-12-19 08:56:45 -08001852 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001853 sp<Track> track;
1854 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07001855 audio_output_flags_t outputFlags = mOutput->flags;
1856
1857 // special case for FAST flag considered OK if fast mixer is present
1858 if (hasFastMixer()) {
1859 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
1860 }
1861
1862 // Check if requested flags are compatible with output stream flags
1863 if ((*flags & outputFlags) != *flags) {
1864 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
1865 *flags, outputFlags);
1866 *flags = (audio_output_flags_t)(*flags & outputFlags);
1867 }
Eric Laurent81784c32012-11-19 14:55:58 -08001868
Eric Laurent81784c32012-11-19 14:55:58 -08001869 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07001870 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08001871 if (
Eric Laurent81784c32012-11-19 14:55:58 -08001872 // PCM data
1873 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001874 // TODO: extract as a data library function that checks that a computationally
1875 // expensive downmixer is not required: isFastOutputChannelConversion()
Andy Hung9a592762014-07-21 21:56:01 -07001876 (channelMask == mChannelMask ||
Andy Hung1f439e12015-05-19 12:57:41 -07001877 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1878 (channelMask == AUDIO_CHANNEL_OUT_MONO
1879 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001880 // hardware sample rate
1881 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001882 // normal mixer has an associated fast mixer
1883 hasFastMixer() &&
1884 // there are sufficient fast track slots available
1885 (mFastTrackAvailMask != 0)
1886 // FIXME test that MixerThread for this fast track has a capable output HAL
1887 // FIXME add a permission test also?
1888 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07001889 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
1890 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001891 // read the fast track multiplier property the first time it is needed
1892 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1893 if (ok != 0) {
1894 ALOGE("%s pthread_once failed: %d", __func__, ok);
1895 }
Andy Hunge0a269a2016-03-23 15:13:42 -07001896 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08001897 }
Eric Laurent4c415062016-06-17 16:14:16 -07001898
1899 // check compatibility with audio effects.
1900 { // scope for mLock
1901 Mutex::Autolock _l(mLock);
1902 // do not accept RAW flag if post processing are present. Note that post processing on
1903 // a fast mixer are necessarily hardware
1904 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE);
1905 if (chain != 0) {
Eric Laurent122f7e72016-06-29 11:53:29 -07001906 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_RAW) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07001907 "AUDIO_OUTPUT_FLAG_RAW denied: post processing effect present");
1908 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_RAW);
1909 }
1910 // Do not accept FAST flag if software global effects are present
1911 chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
1912 if (chain != 0) {
Eric Laurent122f7e72016-06-29 11:53:29 -07001913 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_RAW) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07001914 "AUDIO_OUTPUT_FLAG_RAW denied: global effect present");
1915 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_RAW);
1916 if (chain->hasSoftwareEffect()) {
1917 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: software global effect present");
1918 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
1919 }
1920 }
1921 // Do not accept FAST flag if the session has software effects
1922 chain = getEffectChain_l(sessionId);
1923 if (chain != 0) {
Eric Laurent122f7e72016-06-29 11:53:29 -07001924 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_RAW) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07001925 "AUDIO_OUTPUT_FLAG_RAW denied: effect present on session");
1926 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_RAW);
1927 if (chain->hasSoftwareEffect()) {
1928 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: software effect present on session");
1929 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
1930 }
1931 }
1932 }
Eric Laurent122f7e72016-06-29 11:53:29 -07001933 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07001934 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
1935 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08001936 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001937 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
1938 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07001939 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001940 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08001941 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001942 audio_is_linear_pcm(format),
1943 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07001944 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08001945 }
1946 }
1947 // For normal PCM streaming tracks, update minimum frame count.
1948 // For compatibility with AudioTrack calculation, buffer depth is forced
1949 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1950 // This is probably too conservative, but legacy application code may depend on it.
1951 // If you change this calculation, also review the start threshold which is related.
Eric Laurent05067782016-06-01 18:27:28 -07001952 if (!(*flags & AUDIO_OUTPUT_FLAG_FAST)
Phil Burkfdb3c072016-02-09 10:47:02 -08001953 && audio_has_proportional_frames(format) && sharedBuffer == 0) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001954 // this must match AudioTrack.cpp calculateMinFrameCount().
1955 // TODO: Move to a common library
Eric Laurent81784c32012-11-19 14:55:58 -08001956 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1957 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1958 if (minBufCount < 2) {
1959 minBufCount = 2;
1960 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07001961 // For normal mixing tracks, if speed is > 1.0f (normal), AudioTrack
1962 // or the client should compute and pass in a larger buffer request.
Andy Hung0e48d252015-01-26 11:43:15 -08001963 size_t minFrameCount =
Andy Hung8edb8dc2015-03-26 19:13:55 -07001964 minBufCount * sourceFramesNeededWithTimestretch(
1965 sampleRate, mNormalFrameCount,
1966 mSampleRate, AUDIO_TIMESTRETCH_SPEED_NORMAL /*speed*/);
Andy Hung0e48d252015-01-26 11:43:15 -08001967 if (frameCount < minFrameCount) { // including frameCount == 0
Eric Laurent81784c32012-11-19 14:55:58 -08001968 frameCount = minFrameCount;
1969 }
Eric Laurent81784c32012-11-19 14:55:58 -08001970 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001971 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001972
Glenn Kastenc3df8382014-03-13 15:05:25 -07001973 switch (mType) {
1974
1975 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08001976 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08001977 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001978 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1979 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001980 sampleRate, format, channelMask, mOutput, mFormat);
1981 lStatus = BAD_VALUE;
1982 goto Exit;
1983 }
1984 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001985 break;
1986
1987 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001988 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001989 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1990 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001991 sampleRate, format, channelMask, mOutput, mFormat);
1992 lStatus = BAD_VALUE;
1993 goto Exit;
1994 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001995 break;
1996
1997 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001998 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001999 ALOGE("createTrack_l() Bad parameter: format %#x \""
2000 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002001 format, mOutput, mFormat);
2002 lStatus = BAD_VALUE;
2003 goto Exit;
2004 }
Andy Hungcd044842014-08-07 11:04:34 -07002005 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002006 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2007 lStatus = BAD_VALUE;
2008 goto Exit;
2009 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002010 break;
2011
Eric Laurent81784c32012-11-19 14:55:58 -08002012 }
2013
2014 lStatus = initCheck();
2015 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002016 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002017 goto Exit;
2018 }
2019
2020 { // scope for mLock
2021 Mutex::Autolock _l(mLock);
2022
2023 // all tracks in same audio session must share the same routing strategy otherwise
2024 // conflicts will happen when tracks are moved from one output to another by audio policy
2025 // manager
2026 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
2027 for (size_t i = 0; i < mTracks.size(); ++i) {
2028 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002029 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002030 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
2031 if (sessionId == t->sessionId() && strategy != actual) {
2032 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2033 strategy, actual);
2034 lStatus = BAD_VALUE;
2035 goto Exit;
2036 }
2037 }
2038 }
2039
Glenn Kastend79072e2016-01-06 08:41:20 -08002040 track = new Track(this, client, streamType, sampleRate, format,
2041 channelMask, frameCount, NULL, sharedBuffer,
2042 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT);
Glenn Kasten03003332013-08-06 15:40:54 -07002043
Glenn Kasten03003332013-08-06 15:40:54 -07002044 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2045 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002046 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002047 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002048 goto Exit;
2049 }
2050 mTracks.add(track);
2051
2052 sp<EffectChain> chain = getEffectChain_l(sessionId);
2053 if (chain != 0) {
2054 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2055 track->setMainBuffer(chain->inBuffer());
2056 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
2057 chain->incTrackCnt();
2058 }
2059
Eric Laurent05067782016-06-01 18:27:28 -07002060 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002061 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2062 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2063 // so ask activity manager to do this on our behalf
2064 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
2065 }
2066 }
2067
2068 lStatus = NO_ERROR;
2069
2070Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002071 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002072 return track;
2073}
2074
2075uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2076{
2077 return latency;
2078}
2079
2080uint32_t AudioFlinger::PlaybackThread::latency() const
2081{
2082 Mutex::Autolock _l(mLock);
2083 return latency_l();
2084}
2085uint32_t AudioFlinger::PlaybackThread::latency_l() const
2086{
2087 if (initCheck() == NO_ERROR) {
2088 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
2089 } else {
2090 return 0;
2091 }
2092}
2093
2094void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2095{
2096 Mutex::Autolock _l(mLock);
2097 // Don't apply master volume in SW if our HAL can do it for us.
2098 if (mOutput && mOutput->audioHwDev &&
2099 mOutput->audioHwDev->canSetMasterVolume()) {
2100 mMasterVolume = 1.0;
2101 } else {
2102 mMasterVolume = value;
2103 }
2104}
2105
2106void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2107{
2108 Mutex::Autolock _l(mLock);
2109 // Don't apply master mute in SW if our HAL can do it for us.
2110 if (mOutput && mOutput->audioHwDev &&
2111 mOutput->audioHwDev->canSetMasterMute()) {
2112 mMasterMute = false;
2113 } else {
2114 mMasterMute = muted;
2115 }
2116}
2117
2118void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2119{
2120 Mutex::Autolock _l(mLock);
2121 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002122 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002123}
2124
2125void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2126{
2127 Mutex::Autolock _l(mLock);
2128 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002129 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002130}
2131
2132float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2133{
2134 Mutex::Autolock _l(mLock);
2135 return mStreamTypes[stream].volume;
2136}
2137
2138// addTrack_l() must be called with ThreadBase::mLock held
2139status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2140{
2141 status_t status = ALREADY_EXISTS;
2142
Eric Laurent81784c32012-11-19 14:55:58 -08002143 if (mActiveTracks.indexOf(track) < 0) {
2144 // the track is newly added, make sure it fills up all its
2145 // buffers before playing. This is to ensure the client will
2146 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002147 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002148 TrackBase::track_state state = track->mState;
2149 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002150 status = AudioSystem::startOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002151 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002152 mLock.lock();
2153 // abort track was stopped/paused while we released the lock
2154 if (state != track->mState) {
2155 if (status == NO_ERROR) {
2156 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002157 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002158 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002159 mLock.lock();
2160 }
2161 return INVALID_OPERATION;
2162 }
2163 // abort if start is rejected by audio policy manager
2164 if (status != NO_ERROR) {
2165 return PERMISSION_DENIED;
2166 }
2167#ifdef ADD_BATTERY_DATA
2168 // to track the speaker usage
2169 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2170#endif
2171 }
2172
Eric Laurent51716182016-02-29 18:00:56 -08002173 // set retry count for buffer fill
2174 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002175 if (track->isStopping_1()) {
2176 track->mRetryCount = kMaxTrackStopRetriesOffload;
2177 } else {
2178 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2179 }
2180 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002181 } else {
2182 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002183 track->mFillingUpStatus =
2184 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002185 }
2186
Eric Laurent81784c32012-11-19 14:55:58 -08002187 track->mResetDone = false;
2188 track->mPresentationCompleteFrames = 0;
2189 mActiveTracks.add(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002190 mWakeLockUids.add(track->uid());
2191 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07002192 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07002193 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2194 if (chain != 0) {
2195 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2196 track->sessionId());
2197 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002198 }
2199
2200 status = NO_ERROR;
2201 }
2202
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002203 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002204 return status;
2205}
2206
Eric Laurentbfb1b832013-01-07 09:53:42 -08002207bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002208{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002209 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002210 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002211 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2212 track->mState = TrackBase::STOPPED;
2213 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002214 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002215 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002216 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002217 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002218
2219 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002220}
2221
2222void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2223{
2224 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
2225 mTracks.remove(track);
2226 deleteTrackName_l(track->name());
2227 // redundant as track is about to be destroyed, for dumpsys only
2228 track->mName = -1;
2229 if (track->isFastTrack()) {
2230 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002231 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002232 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2233 mFastTrackAvailMask |= 1 << index;
2234 // redundant as track is about to be destroyed, for dumpsys only
2235 track->mFastIndex = -1;
2236 }
2237 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2238 if (chain != 0) {
2239 chain->decTrackCnt();
2240 }
2241}
2242
Eric Laurentede6c3b2013-09-19 14:37:46 -07002243void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002244{
2245 // Thread could be blocked waiting for async
2246 // so signal it to handle state changes immediately
2247 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
2248 // be lost so we also flag to prevent it blocking on mWaitWorkCV
2249 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002250 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002251}
2252
Eric Laurent81784c32012-11-19 14:55:58 -08002253String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2254{
Eric Laurent81784c32012-11-19 14:55:58 -08002255 Mutex::Autolock _l(mLock);
2256 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07002257 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002258 }
2259
Glenn Kastend8ea6992013-07-16 14:17:15 -07002260 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
2261 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08002262 free(s);
2263 return out_s8;
2264}
2265
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002266void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002267 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2268 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002269
Eric Laurent73e26b62015-04-27 16:55:58 -07002270 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002271
2272 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002273 case AUDIO_OUTPUT_OPENED:
2274 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002275 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002276 desc->mChannelMask = mChannelMask;
2277 desc->mSamplingRate = mSampleRate;
2278 desc->mFormat = mFormat;
2279 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002280 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002281 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002282 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002283 break;
2284
Eric Laurent73e26b62015-04-27 16:55:58 -07002285 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002286 default:
2287 break;
2288 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002289 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002290}
2291
Eric Laurentbfb1b832013-01-07 09:53:42 -08002292void AudioFlinger::PlaybackThread::writeCallback()
2293{
2294 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002295 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002296}
2297
2298void AudioFlinger::PlaybackThread::drainCallback()
2299{
2300 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002301 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002302}
2303
Eric Laurent3b4529e2013-09-05 18:09:19 -07002304void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002305{
2306 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002307 // reject out of sequence requests
2308 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2309 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002310 mWaitWorkCV.signal();
2311 }
2312}
2313
Eric Laurent3b4529e2013-09-05 18:09:19 -07002314void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002315{
2316 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002317 // reject out of sequence requests
2318 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
2319 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002320 mWaitWorkCV.signal();
2321 }
2322}
2323
2324// static
2325int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
Glenn Kasten0f11b512014-01-31 16:18:54 -08002326 void *param __unused,
Eric Laurentbfb1b832013-01-07 09:53:42 -08002327 void *cookie)
2328{
2329 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
2330 ALOGV("asyncCallback() event %d", event);
2331 switch (event) {
2332 case STREAM_CBK_EVENT_WRITE_READY:
2333 me->writeCallback();
2334 break;
2335 case STREAM_CBK_EVENT_DRAIN_READY:
2336 me->drainCallback();
2337 break;
2338 default:
2339 ALOGW("asyncCallback() unknown event %d", event);
2340 break;
2341 }
2342 return 0;
2343}
2344
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002345void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002346{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002347 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002348 mSampleRate = mOutput->getSampleRate();
2349 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002350 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002351 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002352 }
Andy Hung9a592762014-07-21 21:56:01 -07002353 if ((mType == MIXER || mType == DUPLICATING)
2354 && !isValidPcmSinkChannelMask(mChannelMask)) {
2355 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2356 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002357 }
Andy Hunge5412692014-05-16 11:25:07 -07002358 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002359
2360 // Get actual HAL format.
Andy Hung463be252014-07-10 16:56:07 -07002361 mHALFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Phil Burkca5e6142015-07-14 09:42:29 -07002362 // Get format from the shim, which will be different than the HAL format
2363 // if playing compressed audio over HDMI passthrough.
2364 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002365 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002366 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002367 }
Andy Hung6146c082014-03-18 11:56:15 -07002368 if ((mType == MIXER || mType == DUPLICATING)
2369 && !isValidPcmSinkFormat(mFormat)) {
2370 LOG_FATAL("HAL format %#x not supported for mixed output",
2371 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002372 }
Phil Burk062e67a2015-02-11 13:40:50 -08002373 mFrameSize = mOutput->getFrameSize();
Glenn Kasten70949c42013-08-06 07:40:12 -07002374 mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
2375 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002376 if (mFrameCount & 15) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002377 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002378 mFrameCount);
2379 }
2380
Eric Laurentbfb1b832013-01-07 09:53:42 -08002381 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
2382 (mOutput->stream->set_callback != NULL)) {
2383 if (mOutput->stream->set_callback(mOutput->stream,
2384 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
2385 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002386 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002387 }
2388 }
2389
Eric Laurentd1f69b02014-12-15 14:33:13 -08002390 mHwSupportsPause = false;
2391 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
2392 if (mOutput->stream->pause != NULL) {
2393 if (mOutput->stream->resume != NULL) {
2394 mHwSupportsPause = true;
2395 } else {
2396 ALOGW("direct output implements pause but not resume");
2397 }
2398 } else if (mOutput->stream->resume != NULL) {
2399 ALOGW("direct output implements resume but not pause");
2400 }
2401 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002402 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2403 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2404 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002405
Andy Hungfbfc3952015-01-15 13:33:51 -08002406 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2407 // For best precision, we use float instead of the associated output
2408 // device format (typically PCM 16 bit).
2409
2410 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2411 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2412 mBufferSize = mFrameSize * mFrameCount;
2413
2414 // TODO: We currently use the associated output device channel mask and sample rate.
2415 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2416 // (if a valid mask) to avoid premature downmix.
2417 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2418 // instead of the output device sample rate to avoid loss of high frequency information.
2419 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2420 }
2421
Andy Hung09a50072014-02-27 14:30:47 -08002422 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002423 double multiplier = 1.0;
2424 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2425 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002426 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2427 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002428
Eric Laurent81784c32012-11-19 14:55:58 -08002429 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2430 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2431 maxNormalFrameCount = maxNormalFrameCount & ~15;
2432 if (maxNormalFrameCount < minNormalFrameCount) {
2433 maxNormalFrameCount = minNormalFrameCount;
2434 }
2435 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2436 if (multiplier <= 1.0) {
2437 multiplier = 1.0;
2438 } else if (multiplier <= 2.0) {
2439 if (2 * mFrameCount <= maxNormalFrameCount) {
2440 multiplier = 2.0;
2441 } else {
2442 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2443 }
2444 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002445 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002446 }
2447 }
2448 mNormalFrameCount = multiplier * mFrameCount;
2449 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002450 if (mType == MIXER || mType == DUPLICATING) {
2451 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2452 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002453 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002454 mNormalFrameCount);
2455
Andy Hung08fb1742015-05-31 23:22:10 -07002456 // Check if we want to throttle the processing to no more than 2x normal rate
2457 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002458 mThreadThrottleTimeMs = 0;
2459 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002460 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2461
Andy Hung010a1a12014-03-13 13:57:33 -07002462 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2463 // Originally this was int16_t[] array, need to remove legacy implications.
2464 free(mSinkBuffer);
2465 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002466 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2467 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2468 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002469 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002470
Andy Hung69aed5f2014-02-25 17:24:40 -08002471 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2472 // drives the output.
2473 free(mMixerBuffer);
2474 mMixerBuffer = NULL;
2475 if (mMixerBufferEnabled) {
2476 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2477 mMixerBufferSize = mNormalFrameCount * mChannelCount
2478 * audio_bytes_per_sample(mMixerBufferFormat);
2479 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2480 }
Andy Hung98ef9782014-03-04 14:46:50 -08002481 free(mEffectBuffer);
2482 mEffectBuffer = NULL;
2483 if (mEffectBufferEnabled) {
2484 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2485 mEffectBufferSize = mNormalFrameCount * mChannelCount
2486 * audio_bytes_per_sample(mEffectBufferFormat);
2487 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2488 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002489
Eric Laurent81784c32012-11-19 14:55:58 -08002490 // force reconfiguration of effect chains and engines to take new buffer size and audio
2491 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002492 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002493 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2494 // matter.
2495 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2496 Vector< sp<EffectChain> > effectChains = mEffectChains;
2497 for (size_t i = 0; i < effectChains.size(); i ++) {
2498 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2499 }
2500}
2501
2502
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002503status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002504{
2505 if (halFrames == NULL || dspFrames == NULL) {
2506 return BAD_VALUE;
2507 }
2508 Mutex::Autolock _l(mLock);
2509 if (initCheck() != NO_ERROR) {
2510 return INVALID_OPERATION;
2511 }
Andy Hung818e7a32016-02-16 18:08:07 -08002512 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002513 *halFrames = framesWritten;
2514
2515 if (isSuspended()) {
2516 // return an estimation of rendered frames when the output is suspended
2517 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002518 *dspFrames = (uint32_t)
2519 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002520 return NO_ERROR;
2521 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002522 status_t status;
2523 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002524 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002525 *dspFrames = (size_t)frames;
2526 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002527 }
2528}
2529
Eric Laurent4c415062016-06-17 16:14:16 -07002530// hasAudioSession_l() must be called with ThreadBase::mLock held
2531uint32_t AudioFlinger::PlaybackThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08002532{
Eric Laurent81784c32012-11-19 14:55:58 -08002533 uint32_t result = 0;
2534 if (getEffectChain_l(sessionId) != 0) {
2535 result = EFFECT_SESSION;
2536 }
2537
2538 for (size_t i = 0; i < mTracks.size(); ++i) {
2539 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002540 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002541 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07002542 if (track->isFastTrack()) {
2543 result |= FAST_SESSION;
2544 }
Eric Laurent81784c32012-11-19 14:55:58 -08002545 break;
2546 }
2547 }
2548
2549 return result;
2550}
2551
Glenn Kastend848eb42016-03-08 13:42:11 -08002552uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08002553{
2554 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2555 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2556 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2557 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2558 }
2559 for (size_t i = 0; i < mTracks.size(); i++) {
2560 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002561 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002562 return AudioSystem::getStrategyForStream(track->streamType());
2563 }
2564 }
2565 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2566}
2567
2568
Phil Burk062e67a2015-02-11 13:40:50 -08002569AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002570{
2571 Mutex::Autolock _l(mLock);
2572 return mOutput;
2573}
2574
Phil Burk062e67a2015-02-11 13:40:50 -08002575AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002576{
2577 Mutex::Autolock _l(mLock);
2578 AudioStreamOut *output = mOutput;
2579 mOutput = NULL;
2580 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2581 // must push a NULL and wait for ack
2582 mOutputSink.clear();
2583 mPipeSink.clear();
2584 mNormalSink.clear();
2585 return output;
2586}
2587
2588// this method must always be called either with ThreadBase mLock held or inside the thread loop
2589audio_stream_t* AudioFlinger::PlaybackThread::stream() const
2590{
2591 if (mOutput == NULL) {
2592 return NULL;
2593 }
2594 return &mOutput->stream->common;
2595}
2596
2597uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2598{
2599 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2600}
2601
2602status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2603{
2604 if (!isValidSyncEvent(event)) {
2605 return BAD_VALUE;
2606 }
2607
2608 Mutex::Autolock _l(mLock);
2609
2610 for (size_t i = 0; i < mTracks.size(); ++i) {
2611 sp<Track> track = mTracks[i];
2612 if (event->triggerSession() == track->sessionId()) {
2613 (void) track->setSyncEvent(event);
2614 return NO_ERROR;
2615 }
2616 }
2617
2618 return NAME_NOT_FOUND;
2619}
2620
2621bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2622{
2623 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2624}
2625
2626void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2627 const Vector< sp<Track> >& tracksToRemove)
2628{
2629 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002630 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002631 for (size_t i = 0 ; i < count ; i++) {
2632 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002633 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002634 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002635 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002636#ifdef ADD_BATTERY_DATA
2637 // to track the speaker usage
2638 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2639#endif
2640 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002641 AudioSystem::releaseOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002642 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002643 }
Eric Laurent81784c32012-11-19 14:55:58 -08002644 }
2645 }
2646 }
Eric Laurent81784c32012-11-19 14:55:58 -08002647}
2648
2649void AudioFlinger::PlaybackThread::checkSilentMode_l()
2650{
2651 if (!mMasterMute) {
2652 char value[PROPERTY_VALUE_MAX];
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07002653 if (mOutDevice == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) {
2654 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
2655 return;
2656 }
Eric Laurent81784c32012-11-19 14:55:58 -08002657 if (property_get("ro.audio.silent", value, "0") > 0) {
2658 char *endptr;
2659 unsigned long ul = strtoul(value, &endptr, 0);
2660 if (*endptr == '\0' && ul != 0) {
2661 ALOGD("Silence is golden");
2662 // The setprop command will not allow a property to be changed after
2663 // the first time it is set, so we don't have to worry about un-muting.
2664 setMasterMute_l(true);
2665 }
2666 }
2667 }
2668}
2669
2670// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002671ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002672{
Eric Laurent81784c32012-11-19 14:55:58 -08002673 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002674 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002675 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002676
2677 // If an NBAIO sink is present, use it to write the normal mixer's submix
2678 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002679
Andy Hung010a1a12014-03-13 13:57:33 -07002680 const size_t count = mBytesRemaining / mFrameSize;
2681
Simon Wilson2d590962012-11-29 15:18:50 -08002682 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002683 // update the setpoint when AudioFlinger::mScreenState changes
2684 uint32_t screenState = AudioFlinger::mScreenState;
2685 if (screenState != mScreenState) {
2686 mScreenState = screenState;
2687 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2688 if (pipe != NULL) {
2689 pipe->setAvgFrames((mScreenState & 1) ?
2690 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2691 }
2692 }
Andy Hung010a1a12014-03-13 13:57:33 -07002693 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002694 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002695 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002696 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002697 } else {
2698 bytesWritten = framesWritten;
2699 }
2700 // otherwise use the HAL / AudioStreamOut directly
2701 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002702 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002703
Eric Laurentbfb1b832013-01-07 09:53:42 -08002704 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002705 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2706 mWriteAckSequence += 2;
2707 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002708 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002709 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002710 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002711 // FIXME We should have an implementation of timestamps for direct output threads.
2712 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002713 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurent51716182016-02-29 18:00:56 -08002714
Eric Laurentbfb1b832013-01-07 09:53:42 -08002715 if (mUseAsyncWrite &&
2716 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2717 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002718 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002719 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002720 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002721 }
Eric Laurent81784c32012-11-19 14:55:58 -08002722 }
2723
Eric Laurent81784c32012-11-19 14:55:58 -08002724 mNumWrites++;
2725 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002726 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002727 return bytesWritten;
2728}
2729
2730void AudioFlinger::PlaybackThread::threadLoop_drain()
2731{
2732 if (mOutput->stream->drain) {
2733 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2734 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002735 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2736 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002737 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002738 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002739 }
2740 mOutput->stream->drain(mOutput->stream,
2741 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2742 : AUDIO_DRAIN_ALL);
2743 }
2744}
2745
2746void AudioFlinger::PlaybackThread::threadLoop_exit()
2747{
Eric Laurent275e8e92014-11-30 15:14:47 -08002748 {
2749 Mutex::Autolock _l(mLock);
2750 for (size_t i = 0; i < mTracks.size(); i++) {
2751 sp<Track> track = mTracks[i];
2752 track->invalidate();
2753 }
2754 }
Eric Laurent81784c32012-11-19 14:55:58 -08002755}
2756
2757/*
2758The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002759 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002760 - mActiveSleepTimeUs from activeSleepTimeUs()
2761 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08002762 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
2763 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08002764 - maxPeriod from frame count and sample rate (MIXER only)
2765
2766The parameters that affect these derived values are:
2767 - frame count
2768 - frame size
2769 - sample rate
2770 - device type: A2DP or not
2771 - device latency
2772 - format: PCM or not
2773 - active sleep time
2774 - idle sleep time
2775*/
2776
2777void AudioFlinger::PlaybackThread::cacheParameters_l()
2778{
Andy Hung25c2dac2014-02-27 14:56:00 -08002779 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002780 mActiveSleepTimeUs = activeSleepTimeUs();
2781 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08002782
2783 // make sure standby delay is not too short when connected to an A2DP sink to avoid
2784 // truncating audio when going to standby.
2785 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
2786 if ((mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != 0) {
2787 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
2788 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
2789 }
2790 }
Eric Laurent81784c32012-11-19 14:55:58 -08002791}
2792
Eric Laurent13084622016-05-17 10:51:49 -07002793bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08002794{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002795 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08002796 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07002797 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002798 size_t size = mTracks.size();
2799 for (size_t i = 0; i < size; i++) {
2800 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07002801 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002802 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07002803 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002804 }
2805 }
Eric Laurent13084622016-05-17 10:51:49 -07002806 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08002807}
2808
Haynes Mathew George05317d22016-05-03 16:34:26 -07002809void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2810{
2811 Mutex::Autolock _l(mLock);
2812 invalidateTracks_l(streamType);
2813}
2814
Eric Laurent81784c32012-11-19 14:55:58 -08002815status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2816{
Glenn Kastend848eb42016-03-08 13:42:11 -08002817 audio_session_t session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002818 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2819 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002820 bool ownsBuffer = false;
2821
2822 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Glenn Kastend848eb42016-03-08 13:42:11 -08002823 if (session > AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002824 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002825 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002826 if (mType != DIRECT) {
2827 size_t numSamples = mNormalFrameCount * mChannelCount;
2828 buffer = new int16_t[numSamples];
2829 memset(buffer, 0, numSamples * sizeof(int16_t));
2830 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2831 ownsBuffer = true;
2832 }
2833
2834 // Attach all tracks with same session ID to this chain.
2835 for (size_t i = 0; i < mTracks.size(); ++i) {
2836 sp<Track> track = mTracks[i];
2837 if (session == track->sessionId()) {
2838 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2839 buffer);
2840 track->setMainBuffer(buffer);
2841 chain->incTrackCnt();
2842 }
2843 }
2844
2845 // indicate all active tracks in the chain
2846 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2847 sp<Track> track = mActiveTracks[i].promote();
2848 if (track == 0) {
2849 continue;
2850 }
2851 if (session == track->sessionId()) {
2852 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2853 chain->incActiveTrackCnt();
2854 }
2855 }
2856 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002857 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08002858 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002859 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2860 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002861 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Glenn Kastend848eb42016-03-08 13:42:11 -08002862 // chains list in order to be processed last as it contains output stage effects.
Eric Laurent81784c32012-11-19 14:55:58 -08002863 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2864 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08002865 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08002866 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08002867 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08002868 // Effect chain for other sessions are inserted at beginning of effect
2869 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08002870 // sessions is not important.
2871 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
2872 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX,
2873 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08002874 size_t size = mEffectChains.size();
2875 size_t i = 0;
2876 for (i = 0; i < size; i++) {
2877 if (mEffectChains[i]->sessionId() < session) {
2878 break;
2879 }
2880 }
2881 mEffectChains.insertAt(chain, i);
2882 checkSuspendOnAddEffectChain_l(chain);
2883
2884 return NO_ERROR;
2885}
2886
2887size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2888{
Glenn Kastend848eb42016-03-08 13:42:11 -08002889 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08002890
2891 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2892
2893 for (size_t i = 0; i < mEffectChains.size(); i++) {
2894 if (chain == mEffectChains[i]) {
2895 mEffectChains.removeAt(i);
2896 // detach all active tracks from the chain
2897 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2898 sp<Track> track = mActiveTracks[i].promote();
2899 if (track == 0) {
2900 continue;
2901 }
2902 if (session == track->sessionId()) {
2903 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2904 chain.get(), session);
2905 chain->decActiveTrackCnt();
2906 }
2907 }
2908
2909 // detach all tracks with same session ID from this chain
2910 for (size_t i = 0; i < mTracks.size(); ++i) {
2911 sp<Track> track = mTracks[i];
2912 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002913 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002914 chain->decTrackCnt();
2915 }
2916 }
2917 break;
2918 }
2919 }
2920 return mEffectChains.size();
2921}
2922
2923status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2924 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2925{
2926 Mutex::Autolock _l(mLock);
2927 return attachAuxEffect_l(track, EffectId);
2928}
2929
2930status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2931 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2932{
2933 status_t status = NO_ERROR;
2934
2935 if (EffectId == 0) {
2936 track->setAuxBuffer(0, NULL);
2937 } else {
2938 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2939 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2940 if (effect != 0) {
2941 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2942 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2943 } else {
2944 status = INVALID_OPERATION;
2945 }
2946 } else {
2947 status = BAD_VALUE;
2948 }
2949 }
2950 return status;
2951}
2952
2953void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2954{
2955 for (size_t i = 0; i < mTracks.size(); ++i) {
2956 sp<Track> track = mTracks[i];
2957 if (track->auxEffectId() == effectId) {
2958 attachAuxEffect_l(track, 0);
2959 }
2960 }
2961}
2962
2963bool AudioFlinger::PlaybackThread::threadLoop()
2964{
2965 Vector< sp<Track> > tracksToRemove;
2966
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002967 mStandbyTimeNs = systemTime();
Andy Hung69488c42016-05-16 18:43:33 -07002968 nsecs_t lastWriteFinished = -1; // time last server write completed
2969 int64_t lastFramesWritten = -1; // track changes in timestamp server frames written
Eric Laurent81784c32012-11-19 14:55:58 -08002970
2971 // MIXER
2972 nsecs_t lastWarning = 0;
2973
2974 // DUPLICATING
2975 // FIXME could this be made local to while loop?
2976 writeFrames = 0;
2977
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002978 int lastGeneration = 0;
2979
Eric Laurent81784c32012-11-19 14:55:58 -08002980 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002981 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002982
2983 if (mType == MIXER) {
2984 sleepTimeShift = 0;
2985 }
2986
2987 CpuStats cpuStats;
2988 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2989
2990 acquireWakeLock();
2991
Glenn Kasten9e58b552013-01-18 15:09:48 -08002992 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2993 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2994 // and then that string will be logged at the next convenient opportunity.
2995 const char *logString = NULL;
2996
Eric Laurent664539d2013-09-23 18:24:31 -07002997 checkSilentMode_l();
2998
Eric Laurent81784c32012-11-19 14:55:58 -08002999 while (!exitPending())
3000 {
3001 cpuStats.sample(myName);
3002
3003 Vector< sp<EffectChain> > effectChains;
3004
Eric Laurent81784c32012-11-19 14:55:58 -08003005 { // scope for mLock
3006
3007 Mutex::Autolock _l(mLock);
3008
Eric Laurent021cf962014-05-13 10:18:14 -07003009 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07003010
Glenn Kasten9e58b552013-01-18 15:09:48 -08003011 if (logString != NULL) {
3012 mNBLogWriter->logTimestamp();
3013 mNBLogWriter->log(logString);
3014 logString = NULL;
3015 }
3016
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003017 // Gather the framesReleased counters for all active tracks,
Andy Hunge10393e2015-06-12 13:59:33 -07003018 // and associate with the sink frames written out. We need
3019 // this to convert the sink timestamp to the track timestamp.
Andy Hung69488c42016-05-16 18:43:33 -07003020 bool kernelLocationUpdate = false;
Andy Hunge10393e2015-06-12 13:59:33 -07003021 if (mNormalSink != 0) {
Andy Hungc54b1ff2016-02-23 14:07:07 -08003022 // Note: The DuplicatingThread may not have a mNormalSink.
Andy Hung818e7a32016-02-16 18:08:07 -08003023 // We always fetch the timestamp here because often the downstream
Andy Hung69488c42016-05-16 18:43:33 -07003024 // sink will block while writing.
Andy Hung818e7a32016-02-16 18:08:07 -08003025 ExtendedTimestamp timestamp; // use private copy to fetch
3026 (void) mNormalSink->getTimestamp(timestamp);
Andy Hung6d7b1192016-05-07 22:59:48 -07003027
3028 // We keep track of the last valid kernel position in case we are in underrun
3029 // and the normal mixer period is the same as the fast mixer period, or there
3030 // is some error from the HAL.
3031 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3032 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3033 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
3034 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3035 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
3036
3037 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3038 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
3039 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3040 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
Andy Hung69488c42016-05-16 18:43:33 -07003041 }
3042
3043 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3044 kernelLocationUpdate = true;
Andy Hung6d7b1192016-05-07 22:59:48 -07003045 } else {
Eric Laurent122f7e72016-06-29 11:53:29 -07003046 ALOGVV("getTimestamp error - no valid kernel position");
Andy Hung6d7b1192016-05-07 22:59:48 -07003047 }
3048
Andy Hung818e7a32016-02-16 18:08:07 -08003049 // copy over kernel info
3050 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
3051 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
3052 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
3053 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hungc54b1ff2016-02-23 14:07:07 -08003054 }
3055 // mFramesWritten for non-offloaded tracks are contiguous
3056 // even after standby() is called. This is useful for the track frame
3057 // to sink frame mapping.
Andy Hung69488c42016-05-16 18:43:33 -07003058 bool serverLocationUpdate = false;
3059 if (mFramesWritten != lastFramesWritten) {
3060 serverLocationUpdate = true;
3061 lastFramesWritten = mFramesWritten;
3062 }
3063 // Only update timestamps if there is a meaningful change.
3064 // Either the kernel timestamp must be valid or we have written something.
3065 if (kernelLocationUpdate || serverLocationUpdate) {
3066 if (serverLocationUpdate) {
3067 // use the time before we called the HAL write - it is a bit more accurate
3068 // to when the server last read data than the current time here.
3069 //
3070 // If we haven't written anything, mLastWriteTime will be -1
3071 // and we use systemTime().
3072 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
3073 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastWriteTime == -1
3074 ? systemTime() : mLastWriteTime;
3075 }
3076 const size_t size = mActiveTracks.size();
3077 for (size_t i = 0; i < size; ++i) {
3078 sp<Track> t = mActiveTracks[i].promote();
3079 if (t != 0 && !t->isFastTrack()) {
3080 t->updateTrackFrameInfo(
3081 t->mAudioTrackServerProxy->framesReleased(),
3082 mFramesWritten,
3083 mTimestamp);
3084 }
Andy Hunge10393e2015-06-12 13:59:33 -07003085 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07003086 }
3087
Eric Laurent81784c32012-11-19 14:55:58 -08003088 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003089 if (mSignalPending) {
3090 // A signal was raised while we were unlocked
3091 mSignalPending = false;
3092 } else if (waitingAsyncCallback_l()) {
3093 if (exitPending()) {
3094 break;
3095 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003096 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003097 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003098 releaseWakeLock_l();
3099 released = true;
3100 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003101 mWakeLockUids.clear();
3102 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003103 ALOGV("wait async completion");
3104 mWaitWorkCV.wait(mLock);
3105 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003106 if (released) {
3107 acquireWakeLock_l();
3108 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003109 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3110 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003111
3112 continue;
3113 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003114 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003115 isSuspended()) {
3116 // put audio hardware into standby after short delay
3117 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003118
3119 threadLoop_standby();
3120
3121 mStandby = true;
3122 }
3123
3124 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
3125 // we're about to wait, flush the binder command buffer
3126 IPCThreadState::self()->flushCommands();
3127
3128 clearOutputTracks();
3129
3130 if (exitPending()) {
3131 break;
3132 }
3133
3134 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003135 mWakeLockUids.clear();
3136 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08003137 // wait until we have something to do...
3138 ALOGV("%s going to sleep", myName.string());
3139 mWaitWorkCV.wait(mLock);
3140 ALOGV("%s waking up", myName.string());
3141 acquireWakeLock_l();
3142
3143 mMixerStatus = MIXER_IDLE;
3144 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3145 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003146 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003147 checkSilentMode_l();
3148
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003149 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3150 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003151 if (mType == MIXER) {
3152 sleepTimeShift = 0;
3153 }
3154
3155 continue;
3156 }
3157 }
Eric Laurent81784c32012-11-19 14:55:58 -08003158 // mMixerStatusIgnoringFastTracks is also updated internally
3159 mMixerStatus = prepareTracks_l(&tracksToRemove);
3160
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003161 // compare with previously applied list
3162 if (lastGeneration != mActiveTracksGeneration) {
3163 // update wakelock
3164 updateWakeLockUids_l(mWakeLockUids);
3165 lastGeneration = mActiveTracksGeneration;
3166 }
3167
Eric Laurent81784c32012-11-19 14:55:58 -08003168 // prevent any changes in effect chain list and in each effect chain
3169 // during mixing and effect process as the audio buffers could be deleted
3170 // or modified if an effect is created or deleted
3171 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003172 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003173
Eric Laurentbfb1b832013-01-07 09:53:42 -08003174 if (mBytesRemaining == 0) {
3175 mCurrentWriteLength = 0;
3176 if (mMixerStatus == MIXER_TRACKS_READY) {
3177 // threadLoop_mix() sets mCurrentWriteLength
3178 threadLoop_mix();
3179 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3180 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003181 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003182 // must be written to HAL
3183 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003184 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003185 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003186 }
3187 }
Andy Hung98ef9782014-03-04 14:46:50 -08003188 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003189 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003190 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3191 // or mSinkBuffer (if there are no effects).
3192 //
3193 // This is done pre-effects computation; if effects change to
3194 // support higher precision, this needs to move.
3195 //
3196 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003197 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003198 if (mMixerBufferValid) {
3199 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3200 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3201
Andy Hung2ddee192015-12-18 17:34:44 -08003202 // mono blend occurs for mixer threads only (not direct or offloaded)
3203 // and is handled here if we're going directly to the sink.
3204 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003205 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3206 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003207 }
3208
Andy Hung98ef9782014-03-04 14:46:50 -08003209 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
3210 mNormalFrameCount * mChannelCount);
3211 }
3212
Eric Laurentbfb1b832013-01-07 09:53:42 -08003213 mBytesRemaining = mCurrentWriteLength;
3214 if (isSuspended()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003215 mSleepTimeUs = suspendSleepTimeUs();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003216 // simulate write to HAL when suspended
Andy Hung25c2dac2014-02-27 14:56:00 -08003217 mBytesWritten += mSinkBufferSize;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003218 mFramesWritten += mSinkBufferSize / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003219 mBytesRemaining = 0;
3220 }
Eric Laurent81784c32012-11-19 14:55:58 -08003221
Eric Laurentbfb1b832013-01-07 09:53:42 -08003222 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003223 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003224 for (size_t i = 0; i < effectChains.size(); i ++) {
3225 effectChains[i]->process_l();
3226 }
Eric Laurent81784c32012-11-19 14:55:58 -08003227 }
3228 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003229 // Process effect chains for offloaded thread even if no audio
3230 // was read from audio track: process only updates effect state
3231 // and thus does have to be synchronized with audio writes but may have
3232 // to be called while waiting for async write callback
3233 if (mType == OFFLOAD) {
3234 for (size_t i = 0; i < effectChains.size(); i ++) {
3235 effectChains[i]->process_l();
3236 }
3237 }
Eric Laurent81784c32012-11-19 14:55:58 -08003238
Andy Hung98ef9782014-03-04 14:46:50 -08003239 // Only if the Effects buffer is enabled and there is data in the
3240 // Effects buffer (buffer valid), we need to
3241 // copy into the sink buffer.
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 (mEffectBufferValid) {
3244 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003245
3246 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003247 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3248 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003249 }
3250
Andy Hung98ef9782014-03-04 14:46:50 -08003251 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
3252 mNormalFrameCount * mChannelCount);
3253 }
3254
Eric Laurent81784c32012-11-19 14:55:58 -08003255 // enable changes in effect chain
3256 unlockEffectChains(effectChains);
3257
Eric Laurentbfb1b832013-01-07 09:53:42 -08003258 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003259 // mSleepTimeUs == 0 means we must write to audio hardware
3260 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003261 ssize_t ret = 0;
Andy Hung69488c42016-05-16 18:43:33 -07003262 // We save lastWriteFinished here, as previousLastWriteFinished,
3263 // for throttling. On thread start, previousLastWriteFinished will be
3264 // set to -1, which properly results in no throttling after the first write.
3265 nsecs_t previousLastWriteFinished = lastWriteFinished;
3266 nsecs_t delta = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003267 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003268 // FIXME rewrite to reduce number of system calls
3269 mLastWriteTime = systemTime(); // also used for dumpsys
Andy Hung08fb1742015-05-31 23:22:10 -07003270 ret = threadLoop_write();
Andy Hung69488c42016-05-16 18:43:33 -07003271 lastWriteFinished = systemTime();
3272 delta = lastWriteFinished - mLastWriteTime;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003273 if (ret < 0) {
3274 mBytesRemaining = 0;
3275 } else {
3276 mBytesWritten += ret;
3277 mBytesRemaining -= ret;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003278 mFramesWritten += ret / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003279 }
3280 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3281 (mMixerStatus == MIXER_DRAIN_ALL)) {
3282 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003283 }
Andy Hung08fb1742015-05-31 23:22:10 -07003284 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003285 // write blocked detection
Andy Hung08fb1742015-05-31 23:22:10 -07003286 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003287 mNumDelayedWrites++;
Andy Hung69488c42016-05-16 18:43:33 -07003288 if ((lastWriteFinished - lastWarning) > kWarningThrottleNs) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003289 ATRACE_NAME("underrun");
3290 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003291 (unsigned long long) ns2ms(delta), mNumDelayedWrites, this);
Andy Hung69488c42016-05-16 18:43:33 -07003292 lastWarning = lastWriteFinished;
Glenn Kasten4944acb2013-08-19 08:39:20 -07003293 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003294 }
Andy Hung08fb1742015-05-31 23:22:10 -07003295
3296 if (mThreadThrottle
3297 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
3298 && ret > 0) { // we wrote something
3299 // Limit MixerThread data processing to no more than twice the
3300 // expected processing rate.
3301 //
3302 // This helps prevent underruns with NuPlayer and other applications
3303 // which may set up buffers that are close to the minimum size, or use
3304 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3305 //
3306 // The throttle smooths out sudden large data drains from the device,
3307 // e.g. when it comes out of standby, which often causes problems with
3308 // (1) mixer threads without a fast mixer (which has its own warm-up)
3309 // (2) minimum buffer sized tracks (even if the track is full,
3310 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07003311 //
3312 // Total time spent in last processing cycle equals time spent in
3313 // 1. threadLoop_write, as well as time spent in
3314 // 2. threadLoop_mix (significant for heavy mixing, especially
3315 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07003316
Andy Hung69488c42016-05-16 18:43:33 -07003317 // it's OK if deltaMs is an overestimate.
3318 const int32_t deltaMs =
3319 (lastWriteFinished - previousLastWriteFinished) / 1000000;
Andy Hung08fb1742015-05-31 23:22:10 -07003320 const int32_t throttleMs = mHalfBufferMs - deltaMs;
3321 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3322 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003323 // notify of throttle start on verbose log
3324 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3325 "mixer(%p) throttle begin:"
3326 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003327 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003328 mThreadThrottleTimeMs += throttleMs;
3329 } else {
3330 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3331 if (diff > 0) {
3332 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07003333 // but prevent spamming for bluetooth
3334 ALOGD_IF(!audio_is_a2dp_out_device(outDevice()),
3335 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07003336 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3337 }
Andy Hung08fb1742015-05-31 23:22:10 -07003338 }
3339 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003340 }
Eric Laurent81784c32012-11-19 14:55:58 -08003341
Eric Laurentbfb1b832013-01-07 09:53:42 -08003342 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003343 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07003344 Mutex::Autolock _l(mLock);
3345 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
3346 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08003347 }
Glenn Kastene7754022014-10-31 12:11:26 -07003348 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003349 }
Eric Laurent81784c32012-11-19 14:55:58 -08003350 }
3351
3352 // Finally let go of removed track(s), without the lock held
3353 // since we can't guarantee the destructors won't acquire that
3354 // same lock. This will also mutate and push a new fast mixer state.
3355 threadLoop_removeTracks(tracksToRemove);
3356 tracksToRemove.clear();
3357
3358 // FIXME I don't understand the need for this here;
3359 // it was in the original code but maybe the
3360 // assignment in saveOutputTracks() makes this unnecessary?
3361 clearOutputTracks();
3362
3363 // Effect chains will be actually deleted here if they were removed from
3364 // mEffectChains list during mixing or effects processing
3365 effectChains.clear();
3366
3367 // FIXME Note that the above .clear() is no longer necessary since effectChains
3368 // is now local to this block, but will keep it for now (at least until merge done).
3369 }
3370
Eric Laurentbfb1b832013-01-07 09:53:42 -08003371 threadLoop_exit();
3372
Eric Laurentcf817a22014-08-04 20:36:31 -07003373 if (!mStandby) {
3374 threadLoop_standby();
3375 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003376 }
3377
3378 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003379 mWakeLockUids.clear();
3380 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08003381
3382 ALOGV("Thread %p type %d exiting", this, mType);
3383 return false;
3384}
3385
Eric Laurentbfb1b832013-01-07 09:53:42 -08003386// removeTracks_l() must be called with ThreadBase::mLock held
3387void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3388{
3389 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003390 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003391 for (size_t i=0 ; i<count ; i++) {
3392 const sp<Track>& track = tracksToRemove.itemAt(i);
3393 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003394 mWakeLockUids.remove(track->uid());
3395 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003396 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3397 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3398 if (chain != 0) {
3399 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3400 track->sessionId());
3401 chain->decActiveTrackCnt();
3402 }
3403 if (track->isTerminated()) {
3404 removeTrack_l(track);
3405 }
3406 }
3407 }
3408
3409}
Eric Laurent81784c32012-11-19 14:55:58 -08003410
Eric Laurentaccc1472013-09-20 09:36:34 -07003411status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3412{
3413 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08003414 ExtendedTimestamp ets;
3415 status_t status = mNormalSink->getTimestamp(ets);
3416 if (status == NO_ERROR) {
3417 status = ets.getBestTimestamp(&timestamp);
3418 }
3419 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07003420 }
Andy Hung9a1c8892014-12-03 11:37:42 -08003421 if ((mType == OFFLOAD || mType == DIRECT)
3422 && mOutput != NULL && mOutput->stream->get_presentation_position) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003423 uint64_t position64;
Phil Burk062e67a2015-02-11 13:40:50 -08003424 int ret = mOutput->getPresentationPosition(&position64, &timestamp.mTime);
Eric Laurentaccc1472013-09-20 09:36:34 -07003425 if (ret == 0) {
3426 timestamp.mPosition = (uint32_t)position64;
3427 return NO_ERROR;
3428 }
3429 }
3430 return INVALID_OPERATION;
3431}
Eric Laurent1c333e22014-05-20 10:48:17 -07003432
Eric Laurent054d9d32015-04-24 08:48:48 -07003433status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3434 audio_patch_handle_t *handle)
3435{
Glenn Kastenc05b8d72016-03-24 09:48:17 -07003436 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent054d9d32015-04-24 08:48:48 -07003437
Glenn Kastenc05b8d72016-03-24 09:48:17 -07003438 status_t status = PlaybackThread::createAudioPatch_l(patch, handle);
Eric Laurent054d9d32015-04-24 08:48:48 -07003439
3440 return status;
3441}
3442
Eric Laurent1c333e22014-05-20 10:48:17 -07003443status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3444 audio_patch_handle_t *handle)
3445{
3446 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003447
3448 // store new device and send to effects
3449 audio_devices_t type = AUDIO_DEVICE_NONE;
3450 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3451 type |= patch->sinks[i].ext.device.type;
3452 }
3453
3454#ifdef ADD_BATTERY_DATA
3455 // when changing the audio output device, call addBatteryData to notify
3456 // the change
3457 if (mOutDevice != type) {
3458 uint32_t params = 0;
3459 // check whether speaker is on
3460 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3461 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003462 }
3463
Eric Laurent054d9d32015-04-24 08:48:48 -07003464 audio_devices_t deviceWithoutSpeaker
3465 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3466 // check if any other device (except speaker) is on
3467 if (type & deviceWithoutSpeaker) {
3468 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3469 }
3470
3471 if (params != 0) {
3472 addBatteryData(params);
3473 }
3474 }
3475#endif
3476
3477 for (size_t i = 0; i < mEffectChains.size(); i++) {
3478 mEffectChains[i]->setDevice_l(type);
3479 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003480
3481 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3482 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3483 bool configChanged = mPrevOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003484 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003485 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003486
3487 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003488 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3489 status = hwDevice->create_audio_patch(hwDevice,
3490 patch->num_sources,
3491 patch->sources,
3492 patch->num_sinks,
3493 patch->sinks,
3494 handle);
3495 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003496 char *address;
3497 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3498 //FIXME: we only support address on first sink with HAL version < 3.0
3499 address = audio_device_address_to_parameter(
3500 patch->sinks[0].ext.device.type,
3501 patch->sinks[0].ext.device.address);
3502 } else {
3503 address = (char *)calloc(1, 1);
3504 }
3505 AudioParameter param = AudioParameter(String8(address));
3506 free(address);
3507 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), (int)type);
3508 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3509 param.toString().string());
3510 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003511 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003512 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003513 mPrevOutDevice = type;
Eric Laurente8726fe2015-06-26 09:39:24 -07003514 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3515 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003516 return status;
3517}
3518
Eric Laurent054d9d32015-04-24 08:48:48 -07003519status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3520{
Glenn Kastenc05b8d72016-03-24 09:48:17 -07003521 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent054d9d32015-04-24 08:48:48 -07003522
3523 status_t status = PlaybackThread::releaseAudioPatch_l(handle);
3524
Eric Laurent054d9d32015-04-24 08:48:48 -07003525 return status;
3526}
3527
Eric Laurent1c333e22014-05-20 10:48:17 -07003528status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3529{
3530 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003531
3532 mOutDevice = AUDIO_DEVICE_NONE;
3533
Eric Laurent1c333e22014-05-20 10:48:17 -07003534 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
3535 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3536 status = hwDevice->release_audio_patch(hwDevice, handle);
3537 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003538 AudioParameter param;
3539 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
3540 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3541 param.toString().string());
Eric Laurent1c333e22014-05-20 10:48:17 -07003542 }
3543 return status;
3544}
3545
Eric Laurent83b88082014-06-20 18:31:16 -07003546void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3547{
3548 Mutex::Autolock _l(mLock);
3549 mTracks.add(track);
3550}
3551
3552void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3553{
3554 Mutex::Autolock _l(mLock);
3555 destroyTrack_l(track);
3556}
3557
3558void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3559{
3560 ThreadBase::getAudioPortConfig(config);
3561 config->role = AUDIO_PORT_ROLE_SOURCE;
3562 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3563 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3564}
3565
Eric Laurent81784c32012-11-19 14:55:58 -08003566// ----------------------------------------------------------------------------
3567
3568AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003569 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3570 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003571 // mAudioMixer below
3572 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08003573 mFastMixerFutex(0),
3574 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08003575 // mOutputSink below
3576 // mPipeSink below
3577 // mNormalSink below
3578{
3579 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003580 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%zu, "
3581 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003582 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3583 mNormalFrameCount);
3584 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3585
Andy Hungfbfc3952015-01-15 13:33:51 -08003586 if (type == DUPLICATING) {
3587 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3588 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3589 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3590 return;
3591 }
Eric Laurent81784c32012-11-19 14:55:58 -08003592 // create an NBAIO sink for the HAL output stream, and negotiate
3593 mOutputSink = new AudioStreamOutSink(output->stream);
3594 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003595 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003596#if !LOG_NDEBUG
3597 ssize_t index =
3598#else
3599 (void)
3600#endif
3601 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003602 ALOG_ASSERT(index == 0);
3603
3604 // initialize fast mixer depending on configuration
3605 bool initFastMixer;
3606 switch (kUseFastMixer) {
3607 case FastMixer_Never:
3608 initFastMixer = false;
3609 break;
3610 case FastMixer_Always:
3611 initFastMixer = true;
3612 break;
3613 case FastMixer_Static:
3614 case FastMixer_Dynamic:
3615 initFastMixer = mFrameCount < mNormalFrameCount;
3616 break;
3617 }
3618 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003619 audio_format_t fastMixerFormat;
3620 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3621 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3622 } else {
3623 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3624 }
3625 if (mFormat != fastMixerFormat) {
3626 // change our Sink format to accept our intermediate precision
3627 mFormat = fastMixerFormat;
3628 free(mSinkBuffer);
3629 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3630 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3631 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3632 }
Eric Laurent81784c32012-11-19 14:55:58 -08003633
3634 // create a MonoPipe to connect our submix to FastMixer
3635 NBAIO_Format format = mOutputSink->format();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003636#ifdef TEE_SINK
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003637 NBAIO_Format origformat = format;
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003638#endif
Andy Hung1258c1a2014-05-23 21:22:17 -07003639 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07003640 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003641 format.mFormat = fastMixerFormat;
3642 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3643
Eric Laurent81784c32012-11-19 14:55:58 -08003644 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3645 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3646 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3647 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3648 const NBAIO_Format offers[1] = {format};
3649 size_t numCounterOffers = 0;
Glenn Kastenfc302fd2016-04-11 14:11:26 -07003650#if !LOG_NDEBUG || defined(TEE_SINK)
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003651 ssize_t index =
3652#else
3653 (void)
3654#endif
3655 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003656 ALOG_ASSERT(index == 0);
3657 monoPipe->setAvgFrames((mScreenState & 1) ?
3658 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3659 mPipeSink = monoPipe;
3660
Glenn Kasten46909e72013-02-26 09:20:22 -08003661#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003662 if (mTeeSinkOutputEnabled) {
3663 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003664 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3665 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003666 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003667 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003668 ALOG_ASSERT(index == 0);
3669 mTeeSink = teeSink;
3670 PipeReader *teeSource = new PipeReader(*teeSink);
3671 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003672 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003673 ALOG_ASSERT(index == 0);
3674 mTeeSource = teeSource;
3675 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003676#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003677
3678 // create fast mixer and configure it initially with just one fast track for our submix
3679 mFastMixer = new FastMixer();
3680 FastMixerStateQueue *sq = mFastMixer->sq();
3681#ifdef STATE_QUEUE_DUMP
3682 sq->setObserverDump(&mStateQueueObserverDump);
3683 sq->setMutatorDump(&mStateQueueMutatorDump);
3684#endif
3685 FastMixerState *state = sq->begin();
3686 FastTrack *fastTrack = &state->mFastTracks[0];
3687 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3688 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3689 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003690 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3691 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003692 fastTrack->mGeneration++;
3693 state->mFastTracksGen++;
3694 state->mTrackMask = 1;
3695 // fast mixer will use the HAL output sink
3696 state->mOutputSink = mOutputSink.get();
3697 state->mOutputSinkGen++;
3698 state->mFrameCount = mFrameCount;
3699 state->mCommand = FastMixerState::COLD_IDLE;
3700 // already done in constructor initialization list
3701 //mFastMixerFutex = 0;
3702 state->mColdFutexAddr = &mFastMixerFutex;
3703 state->mColdGen++;
3704 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003705#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003706 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003707#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003708 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3709 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003710 sq->end();
3711 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3712
3713 // start the fast mixer
3714 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3715 pid_t tid = mFastMixer->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003716 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003717
3718#ifdef AUDIO_WATCHDOG
3719 // create and start the watchdog
3720 mAudioWatchdog = new AudioWatchdog();
3721 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3722 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3723 tid = mAudioWatchdog->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003724 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003725#endif
3726
Eric Laurent81784c32012-11-19 14:55:58 -08003727 }
3728
3729 switch (kUseFastMixer) {
3730 case FastMixer_Never:
3731 case FastMixer_Dynamic:
3732 mNormalSink = mOutputSink;
3733 break;
3734 case FastMixer_Always:
3735 mNormalSink = mPipeSink;
3736 break;
3737 case FastMixer_Static:
3738 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3739 break;
3740 }
3741}
3742
3743AudioFlinger::MixerThread::~MixerThread()
3744{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003745 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003746 FastMixerStateQueue *sq = mFastMixer->sq();
3747 FastMixerState *state = sq->begin();
3748 if (state->mCommand == FastMixerState::COLD_IDLE) {
3749 int32_t old = android_atomic_inc(&mFastMixerFutex);
3750 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003751 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003752 }
3753 }
3754 state->mCommand = FastMixerState::EXIT;
3755 sq->end();
3756 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3757 mFastMixer->join();
3758 // Though the fast mixer thread has exited, it's state queue is still valid.
3759 // We'll use that extract the final state which contains one remaining fast track
3760 // corresponding to our sub-mix.
3761 state = sq->begin();
3762 ALOG_ASSERT(state->mTrackMask == 1);
3763 FastTrack *fastTrack = &state->mFastTracks[0];
3764 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3765 delete fastTrack->mBufferProvider;
3766 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003767 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003768#ifdef AUDIO_WATCHDOG
3769 if (mAudioWatchdog != 0) {
3770 mAudioWatchdog->requestExit();
3771 mAudioWatchdog->requestExitAndWait();
3772 mAudioWatchdog.clear();
3773 }
3774#endif
3775 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003776 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003777 delete mAudioMixer;
3778}
3779
3780
3781uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3782{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003783 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003784 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3785 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3786 }
3787 return latency;
3788}
3789
3790
3791void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3792{
3793 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3794}
3795
Eric Laurentbfb1b832013-01-07 09:53:42 -08003796ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003797{
3798 // FIXME we should only do one push per cycle; confirm this is true
3799 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003800 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003801 FastMixerStateQueue *sq = mFastMixer->sq();
3802 FastMixerState *state = sq->begin();
3803 if (state->mCommand != FastMixerState::MIX_WRITE &&
3804 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3805 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07003806
3807 // FIXME workaround for first HAL write being CPU bound on some devices
3808 ATRACE_BEGIN("write");
3809 mOutput->write((char *)mSinkBuffer, 0);
3810 ATRACE_END();
3811
Eric Laurent81784c32012-11-19 14:55:58 -08003812 int32_t old = android_atomic_inc(&mFastMixerFutex);
3813 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003814 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003815 }
3816#ifdef AUDIO_WATCHDOG
3817 if (mAudioWatchdog != 0) {
3818 mAudioWatchdog->resume();
3819 }
3820#endif
3821 }
3822 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003823#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003824 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003825 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003826#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003827 sq->end();
3828 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3829 if (kUseFastMixer == FastMixer_Dynamic) {
3830 mNormalSink = mPipeSink;
3831 }
3832 } else {
3833 sq->end(false /*didModify*/);
3834 }
3835 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003836 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003837}
3838
3839void AudioFlinger::MixerThread::threadLoop_standby()
3840{
3841 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003842 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003843 FastMixerStateQueue *sq = mFastMixer->sq();
3844 FastMixerState *state = sq->begin();
3845 if (!(state->mCommand & FastMixerState::IDLE)) {
3846 state->mCommand = FastMixerState::COLD_IDLE;
3847 state->mColdFutexAddr = &mFastMixerFutex;
3848 state->mColdGen++;
3849 mFastMixerFutex = 0;
3850 sq->end();
3851 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3852 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3853 if (kUseFastMixer == FastMixer_Dynamic) {
3854 mNormalSink = mOutputSink;
3855 }
3856#ifdef AUDIO_WATCHDOG
3857 if (mAudioWatchdog != 0) {
3858 mAudioWatchdog->pause();
3859 }
3860#endif
3861 } else {
3862 sq->end(false /*didModify*/);
3863 }
3864 }
3865 PlaybackThread::threadLoop_standby();
3866}
3867
Eric Laurentbfb1b832013-01-07 09:53:42 -08003868bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3869{
3870 return false;
3871}
3872
3873bool AudioFlinger::PlaybackThread::shouldStandby_l()
3874{
3875 return !mStandby;
3876}
3877
3878bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3879{
3880 Mutex::Autolock _l(mLock);
3881 return waitingAsyncCallback_l();
3882}
3883
Eric Laurent81784c32012-11-19 14:55:58 -08003884// shared by MIXER and DIRECT, overridden by DUPLICATING
3885void AudioFlinger::PlaybackThread::threadLoop_standby()
3886{
3887 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08003888 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003889 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003890 // discard any pending drain or write ack by incrementing sequence
3891 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3892 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003893 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003894 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3895 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003896 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003897 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003898}
3899
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003900void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3901{
3902 ALOGV("signal playback thread");
3903 broadcast_l();
3904}
3905
Eric Laurent81784c32012-11-19 14:55:58 -08003906void AudioFlinger::MixerThread::threadLoop_mix()
3907{
Eric Laurent81784c32012-11-19 14:55:58 -08003908 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08003909 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08003910 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003911 // increase sleep time progressively when application underrun condition clears.
3912 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3913 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3914 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003915 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003916 sleepTimeShift--;
3917 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003918 mSleepTimeUs = 0;
3919 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08003920 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003921
Eric Laurent81784c32012-11-19 14:55:58 -08003922}
3923
3924void AudioFlinger::MixerThread::threadLoop_sleepTime()
3925{
3926 // If no tracks are ready, sleep once for the duration of an output
3927 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003928 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003929 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003930 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
3931 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
3932 mSleepTimeUs = kMinThreadSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003933 }
3934 // reduce sleep time in case of consecutive application underruns to avoid
3935 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3936 // duration we would end up writing less data than needed by the audio HAL if
3937 // the condition persists.
3938 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3939 sleepTimeShift++;
3940 }
3941 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003942 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003943 }
3944 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003945 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3946 // before effects processing or output.
3947 if (mMixerBufferValid) {
3948 memset(mMixerBuffer, 0, mMixerBufferSize);
3949 } else {
3950 memset(mSinkBuffer, 0, mSinkBufferSize);
3951 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003952 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003953 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3954 "anticipated start");
3955 }
3956 // TODO add standby time extension fct of effect tail
3957}
3958
3959// prepareTracks_l() must be called with ThreadBase::mLock held
3960AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3961 Vector< sp<Track> > *tracksToRemove)
3962{
3963
3964 mixer_state mixerStatus = MIXER_IDLE;
3965 // find out which tracks need to be processed
3966 size_t count = mActiveTracks.size();
3967 size_t mixedTracks = 0;
3968 size_t tracksWithEffect = 0;
3969 // counts only _active_ fast tracks
3970 size_t fastTracks = 0;
3971 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3972
3973 float masterVolume = mMasterVolume;
3974 bool masterMute = mMasterMute;
3975
3976 if (masterMute) {
3977 masterVolume = 0;
3978 }
3979 // Delegate master volume control to effect in output mix effect chain if needed
3980 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3981 if (chain != 0) {
3982 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3983 chain->setVolume_l(&v, &v);
3984 masterVolume = (float)((v + (1 << 23)) >> 24);
3985 chain.clear();
3986 }
3987
3988 // prepare a new state to push
3989 FastMixerStateQueue *sq = NULL;
3990 FastMixerState *state = NULL;
3991 bool didModify = false;
3992 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003993 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003994 sq = mFastMixer->sq();
3995 state = sq->begin();
3996 }
3997
Andy Hung69aed5f2014-02-25 17:24:40 -08003998 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003999 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08004000
Eric Laurent81784c32012-11-19 14:55:58 -08004001 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07004002 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08004003 if (t == 0) {
4004 continue;
4005 }
4006
4007 // this const just means the local variable doesn't change
4008 Track* const track = t.get();
4009
4010 // process fast tracks
4011 if (track->isFastTrack()) {
4012
4013 // It's theoretically possible (though unlikely) for a fast track to be created
4014 // and then removed within the same normal mix cycle. This is not a problem, as
4015 // the track never becomes active so it's fast mixer slot is never touched.
4016 // The converse, of removing an (active) track and then creating a new track
4017 // at the identical fast mixer slot within the same normal mix cycle,
4018 // is impossible because the slot isn't marked available until the end of each cycle.
4019 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07004020 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08004021 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
4022 FastTrack *fastTrack = &state->mFastTracks[j];
4023
4024 // Determine whether the track is currently in underrun condition,
4025 // and whether it had a recent underrun.
4026 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
4027 FastTrackUnderruns underruns = ftDump->mUnderruns;
4028 uint32_t recentFull = (underruns.mBitFields.mFull -
4029 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
4030 uint32_t recentPartial = (underruns.mBitFields.mPartial -
4031 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
4032 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
4033 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
4034 uint32_t recentUnderruns = recentPartial + recentEmpty;
4035 track->mObservedUnderruns = underruns;
4036 // don't count underruns that occur while stopping or pausing
4037 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07004038 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
4039 recentUnderruns > 0) {
4040 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
4041 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Phil Burk2812d9e2016-01-04 10:34:30 -08004042 } else {
4043 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Eric Laurent81784c32012-11-19 14:55:58 -08004044 }
4045
4046 // This is similar to the state machine for normal tracks,
4047 // with a few modifications for fast tracks.
4048 bool isActive = true;
4049 switch (track->mState) {
4050 case TrackBase::STOPPING_1:
4051 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08004052 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004053 track->mState = TrackBase::STOPPING_2;
4054 }
4055 break;
4056 case TrackBase::PAUSING:
4057 // ramp down is not yet implemented
4058 track->setPaused();
4059 break;
4060 case TrackBase::RESUMING:
4061 // ramp up is not yet implemented
4062 track->mState = TrackBase::ACTIVE;
4063 break;
4064 case TrackBase::ACTIVE:
4065 if (recentFull > 0 || recentPartial > 0) {
4066 // track has provided at least some frames recently: reset retry count
4067 track->mRetryCount = kMaxTrackRetries;
4068 }
4069 if (recentUnderruns == 0) {
4070 // no recent underruns: stay active
4071 break;
4072 }
4073 // there has recently been an underrun of some kind
4074 if (track->sharedBuffer() == 0) {
4075 // were any of the recent underruns "empty" (no frames available)?
4076 if (recentEmpty == 0) {
4077 // no, then ignore the partial underruns as they are allowed indefinitely
4078 break;
4079 }
4080 // there has recently been an "empty" underrun: decrement the retry counter
4081 if (--(track->mRetryCount) > 0) {
4082 break;
4083 }
4084 // indicate to client process that the track was disabled because of underrun;
4085 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004086 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004087 // remove from active list, but state remains ACTIVE [confusing but true]
4088 isActive = false;
4089 break;
4090 }
4091 // fall through
4092 case TrackBase::STOPPING_2:
4093 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08004094 case TrackBase::STOPPED:
4095 case TrackBase::FLUSHED: // flush() while active
4096 // Check for presentation complete if track is inactive
4097 // We have consumed all the buffers of this track.
4098 // This would be incomplete if we auto-paused on underrun
4099 {
4100 size_t audioHALFrames =
4101 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004102 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004103 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
4104 // track stays in active list until presentation is complete
4105 break;
4106 }
4107 }
4108 if (track->isStopping_2()) {
4109 track->mState = TrackBase::STOPPED;
4110 }
4111 if (track->isStopped()) {
4112 // Can't reset directly, as fast mixer is still polling this track
4113 // track->reset();
4114 // So instead mark this track as needing to be reset after push with ack
4115 resetMask |= 1 << i;
4116 }
4117 isActive = false;
4118 break;
4119 case TrackBase::IDLE:
4120 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08004121 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08004122 }
4123
4124 if (isActive) {
4125 // was it previously inactive?
4126 if (!(state->mTrackMask & (1 << j))) {
4127 ExtendedAudioBufferProvider *eabp = track;
4128 VolumeProvider *vp = track;
4129 fastTrack->mBufferProvider = eabp;
4130 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08004131 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07004132 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08004133 fastTrack->mGeneration++;
4134 state->mTrackMask |= 1 << j;
4135 didModify = true;
4136 // no acknowledgement required for newly active tracks
4137 }
4138 // cache the combined master volume and stream type volume for fast mixer; this
4139 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08004140 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08004141 ++fastTracks;
4142 } else {
4143 // was it previously active?
4144 if (state->mTrackMask & (1 << j)) {
4145 fastTrack->mBufferProvider = NULL;
4146 fastTrack->mGeneration++;
4147 state->mTrackMask &= ~(1 << j);
4148 didModify = true;
4149 // If any fast tracks were removed, we must wait for acknowledgement
4150 // because we're about to decrement the last sp<> on those tracks.
4151 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4152 } else {
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08004153 LOG_ALWAYS_FATAL("fast track %d should have been active; "
4154 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
4155 j, track->mState, state->mTrackMask, recentUnderruns,
4156 track->sharedBuffer() != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004157 }
4158 tracksToRemove->add(track);
4159 // Avoids a misleading display in dumpsys
4160 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
4161 }
4162 continue;
4163 }
4164
4165 { // local variable scope to avoid goto warning
4166
4167 audio_track_cblk_t* cblk = track->cblk();
4168
4169 // The first time a track is added we wait
4170 // for all its buffers to be filled before processing it
4171 int name = track->name();
4172 // make sure that we have enough frames to mix one full buffer.
4173 // enforce this condition only once to enable draining the buffer in case the client
4174 // app does not call stop() and relies on underrun to stop:
4175 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
4176 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004177 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07004178 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004179 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004180
4181 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004182 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004183 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
4184 // add frames already consumed but not yet released by the resampler
4185 // because mAudioTrackServerProxy->framesReady() will include these frames
4186 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
4187
Eric Laurent81784c32012-11-19 14:55:58 -08004188 uint32_t minFrames = 1;
4189 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
4190 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004191 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08004192 }
Eric Laurent13e4c962013-12-20 17:36:01 -08004193
4194 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07004195 if (ATRACE_ENABLED()) {
4196 // I wish we had formatted trace names
4197 char traceName[16];
4198 strcpy(traceName, "nRdy");
4199 int name = track->name();
4200 if (AudioMixer::TRACK0 <= name &&
4201 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
4202 name -= AudioMixer::TRACK0;
4203 traceName[4] = (name / 10) + '0';
4204 traceName[5] = (name % 10) + '0';
4205 } else {
4206 traceName[4] = '?';
4207 traceName[5] = '?';
4208 }
4209 traceName[6] = '\0';
4210 ATRACE_INT(traceName, framesReady);
4211 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004212 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08004213 !track->isPaused() && !track->isTerminated())
4214 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004215 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004216
4217 mixedTracks++;
4218
Andy Hung69aed5f2014-02-25 17:24:40 -08004219 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
4220 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08004221 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08004222 if (track->mainBuffer() != mSinkBuffer &&
4223 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004224 if (mEffectBufferEnabled) {
4225 mEffectBufferValid = true; // Later can set directly.
4226 }
Eric Laurent81784c32012-11-19 14:55:58 -08004227 chain = getEffectChain_l(track->sessionId());
4228 // Delegate volume control to effect in track effect chain if needed
4229 if (chain != 0) {
4230 tracksWithEffect++;
4231 } else {
4232 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
4233 "session %d",
4234 name, track->sessionId());
4235 }
4236 }
4237
4238
4239 int param = AudioMixer::VOLUME;
4240 if (track->mFillingUpStatus == Track::FS_FILLED) {
4241 // no ramp for the first volume setting
4242 track->mFillingUpStatus = Track::FS_ACTIVE;
4243 if (track->mState == TrackBase::RESUMING) {
4244 track->mState = TrackBase::ACTIVE;
4245 param = AudioMixer::RAMP_VOLUME;
4246 }
4247 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004248 // FIXME should not make a decision based on mServer
4249 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004250 // If the track is stopped before the first frame was mixed,
4251 // do not apply ramp
4252 param = AudioMixer::RAMP_VOLUME;
4253 }
4254
4255 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07004256 uint32_t vl, vr; // in U8.24 integer format
4257 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08004258 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07004259 vl = vr = 0;
4260 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08004261 if (track->isPausing()) {
4262 track->setPaused();
4263 }
4264 } else {
4265
4266 // read original volumes with volume control
4267 float typeVolume = mStreamTypes[track->streamType()].volume;
4268 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004269 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004270 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07004271 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
4272 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08004273 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07004274 if (vlf > GAIN_FLOAT_UNITY) {
4275 ALOGV("Track left volume out of range: %.3g", vlf);
4276 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004277 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07004278 if (vrf > GAIN_FLOAT_UNITY) {
4279 ALOGV("Track right volume out of range: %.3g", vrf);
4280 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004281 }
4282 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07004283 vlf *= v;
4284 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08004285 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07004286 // then derive vl and vr as U8.24 versions for the effect chain
4287 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
4288 vl = (uint32_t) (scaleto8_24 * vlf);
4289 vr = (uint32_t) (scaleto8_24 * vrf);
4290 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08004291 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08004292 // send level comes from shared memory and so may be corrupt
4293 if (sendLevel > MAX_GAIN_INT) {
4294 ALOGV("Track send level out of range: %04X", sendLevel);
4295 sendLevel = MAX_GAIN_INT;
4296 }
Andy Hung6be49402014-05-30 10:42:03 -07004297 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4298 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08004299 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004300
Eric Laurent81784c32012-11-19 14:55:58 -08004301 // Delegate volume control to effect in track effect chain if needed
4302 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4303 // Do not ramp volume if volume is controlled by effect
4304 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08004305 // Update remaining floating point volume levels
4306 vlf = (float)vl / (1 << 24);
4307 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004308 track->mHasVolumeController = true;
4309 } else {
4310 // force no volume ramp when volume controller was just disabled or removed
4311 // from effect chain to avoid volume spike
4312 if (track->mHasVolumeController) {
4313 param = AudioMixer::VOLUME;
4314 }
4315 track->mHasVolumeController = false;
4316 }
4317
Eric Laurent81784c32012-11-19 14:55:58 -08004318 // XXX: these things DON'T need to be done each time
4319 mAudioMixer->setBufferProvider(name, track);
4320 mAudioMixer->enable(name);
4321
Andy Hung6be49402014-05-30 10:42:03 -07004322 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
4323 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
4324 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004325 mAudioMixer->setParameter(
4326 name,
4327 AudioMixer::TRACK,
4328 AudioMixer::FORMAT, (void *)track->format());
4329 mAudioMixer->setParameter(
4330 name,
4331 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004332 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004333 mAudioMixer->setParameter(
4334 name,
4335 AudioMixer::TRACK,
4336 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004337 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004338 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004339 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004340 if (reqSampleRate == 0) {
4341 reqSampleRate = mSampleRate;
4342 } else if (reqSampleRate > maxSampleRate) {
4343 reqSampleRate = maxSampleRate;
4344 }
Eric Laurent81784c32012-11-19 14:55:58 -08004345 mAudioMixer->setParameter(
4346 name,
4347 AudioMixer::RESAMPLE,
4348 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004349 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004350
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004351 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004352 mAudioMixer->setParameter(
4353 name,
4354 AudioMixer::TIMESTRETCH,
4355 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004356 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004357
Andy Hung69aed5f2014-02-25 17:24:40 -08004358 /*
4359 * Select the appropriate output buffer for the track.
4360 *
Andy Hung98ef9782014-03-04 14:46:50 -08004361 * Tracks with effects go into their own effects chain buffer
4362 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004363 *
4364 * Other tracks can use mMixerBuffer for higher precision
4365 * channel accumulation. If this buffer is enabled
4366 * (mMixerBufferEnabled true), then selected tracks will accumulate
4367 * into it.
4368 *
4369 */
4370 if (mMixerBufferEnabled
4371 && (track->mainBuffer() == mSinkBuffer
4372 || track->mainBuffer() == mMixerBuffer)) {
4373 mAudioMixer->setParameter(
4374 name,
4375 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004376 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004377 mAudioMixer->setParameter(
4378 name,
4379 AudioMixer::TRACK,
4380 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4381 // TODO: override track->mainBuffer()?
4382 mMixerBufferValid = true;
4383 } else {
4384 mAudioMixer->setParameter(
4385 name,
4386 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004387 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004388 mAudioMixer->setParameter(
4389 name,
4390 AudioMixer::TRACK,
4391 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4392 }
Eric Laurent81784c32012-11-19 14:55:58 -08004393 mAudioMixer->setParameter(
4394 name,
4395 AudioMixer::TRACK,
4396 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4397
4398 // reset retry count
4399 track->mRetryCount = kMaxTrackRetries;
4400
4401 // If one track is ready, set the mixer ready if:
4402 // - the mixer was not ready during previous round OR
4403 // - no other track is not ready
4404 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4405 mixerStatus != MIXER_TRACKS_ENABLED) {
4406 mixerStatus = MIXER_TRACKS_READY;
4407 }
4408 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004409 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hung08fb1742015-05-31 23:22:10 -07004410 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)",
4411 track, framesReady, desiredFrames);
Glenn Kasten82aaf942013-07-17 16:05:07 -07004412 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08004413 } else {
4414 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004415 }
Phil Burk2812d9e2016-01-04 10:34:30 -08004416
Eric Laurent81784c32012-11-19 14:55:58 -08004417 // clear effect chain input buffer if an active track underruns to avoid sending
4418 // previous audio buffer again to effects
4419 chain = getEffectChain_l(track->sessionId());
4420 if (chain != 0) {
4421 chain->clearInputBuffer();
4422 }
4423
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004424 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004425 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4426 track->isStopped() || track->isPaused()) {
4427 // We have consumed all the buffers of this track.
4428 // Remove it from the list of active tracks.
4429 // TODO: use actual buffer filling status instead of latency when available from
4430 // audio HAL
4431 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004432 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004433 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4434 if (track->isStopped()) {
4435 track->reset();
4436 }
4437 tracksToRemove->add(track);
4438 }
4439 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004440 // No buffers for this track. Give it a few chances to
4441 // fill a buffer, then remove it from active list.
4442 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004443 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004444 tracksToRemove->add(track);
4445 // indicate to client process that the track was disabled because of underrun;
4446 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004447 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004448 // If one track is not ready, mark the mixer also not ready if:
4449 // - the mixer was ready during previous round OR
4450 // - no other track is ready
4451 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4452 mixerStatus != MIXER_TRACKS_READY) {
4453 mixerStatus = MIXER_TRACKS_ENABLED;
4454 }
4455 }
4456 mAudioMixer->disable(name);
4457 }
4458
4459 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08004460
4461 }
4462
4463 // Push the new FastMixer state if necessary
4464 bool pauseAudioWatchdog = false;
4465 if (didModify) {
4466 state->mFastTracksGen++;
4467 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4468 if (kUseFastMixer == FastMixer_Dynamic &&
4469 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4470 state->mCommand = FastMixerState::COLD_IDLE;
4471 state->mColdFutexAddr = &mFastMixerFutex;
4472 state->mColdGen++;
4473 mFastMixerFutex = 0;
4474 if (kUseFastMixer == FastMixer_Dynamic) {
4475 mNormalSink = mOutputSink;
4476 }
4477 // If we go into cold idle, need to wait for acknowledgement
4478 // so that fast mixer stops doing I/O.
4479 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4480 pauseAudioWatchdog = true;
4481 }
Eric Laurent81784c32012-11-19 14:55:58 -08004482 }
4483 if (sq != NULL) {
4484 sq->end(didModify);
4485 sq->push(block);
4486 }
4487#ifdef AUDIO_WATCHDOG
4488 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4489 mAudioWatchdog->pause();
4490 }
4491#endif
4492
4493 // Now perform the deferred reset on fast tracks that have stopped
4494 while (resetMask != 0) {
4495 size_t i = __builtin_ctz(resetMask);
4496 ALOG_ASSERT(i < count);
4497 resetMask &= ~(1 << i);
4498 sp<Track> t = mActiveTracks[i].promote();
4499 if (t == 0) {
4500 continue;
4501 }
4502 Track* track = t.get();
4503 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4504 track->reset();
4505 }
4506
4507 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004508 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004509
Eric Laurent97d547d2014-09-02 14:45:53 -07004510 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4511 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004512 }
4513
4514 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004515 // as long as there are effects we should clear the effects buffer, to avoid
4516 // passing a non-clean buffer to the effect chain
4517 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004518 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004519 // sink or mix buffer must be cleared if all tracks are connected to an
4520 // effect chain as in this case the mixer will not write to the sink or mix buffer
4521 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004522 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4523 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004524 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004525 if (mMixerBufferValid) {
4526 memset(mMixerBuffer, 0, mMixerBufferSize);
4527 // TODO: In testing, mSinkBuffer below need not be cleared because
4528 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4529 // after mixing.
4530 //
4531 // To enforce this guarantee:
4532 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4533 // (mixedTracks == 0 && fastTracks > 0))
4534 // must imply MIXER_TRACKS_READY.
4535 // Later, we may clear buffers regardless, and skip much of this logic.
4536 }
Andy Hung98ef9782014-03-04 14:46:50 -08004537 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004538 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004539 }
4540
4541 // if any fast tracks, then status is ready
4542 mMixerStatusIgnoringFastTracks = mixerStatus;
4543 if (fastTracks > 0) {
4544 mixerStatus = MIXER_TRACKS_READY;
4545 }
4546 return mixerStatus;
4547}
4548
4549// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07004550int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
Glenn Kastend848eb42016-03-08 13:42:11 -08004551 audio_format_t format, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08004552{
Andy Hunge8a1ced2014-05-09 15:02:21 -07004553 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08004554}
4555
4556// deleteTrackName_l() must be called with ThreadBase::mLock held
4557void AudioFlinger::MixerThread::deleteTrackName_l(int name)
4558{
4559 ALOGV("remove track (%d) and delete from mixer", name);
4560 mAudioMixer->deleteTrackName(name);
4561}
4562
Eric Laurent10351942014-05-08 18:49:52 -07004563// checkForNewParameter_l() must be called with ThreadBase::mLock held
4564bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4565 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004566{
Eric Laurent81784c32012-11-19 14:55:58 -08004567 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08004568 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004569
Eric Laurent10351942014-05-08 18:49:52 -07004570 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004571
Glenn Kastenc05b8d72016-03-24 09:48:17 -07004572 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004573
Eric Laurent10351942014-05-08 18:49:52 -07004574 AudioParameter param = AudioParameter(keyValuePair);
4575 int value;
4576 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4577 reconfig = true;
4578 }
4579 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004580 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004581 status = BAD_VALUE;
4582 } else {
4583 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004584 reconfig = true;
4585 }
Eric Laurent10351942014-05-08 18:49:52 -07004586 }
4587 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004588 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004589 status = BAD_VALUE;
4590 } else {
4591 // no need to save value, since it's constant
4592 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004593 }
Eric Laurent10351942014-05-08 18:49:52 -07004594 }
4595 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4596 // do not accept frame count changes if tracks are open as the track buffer
4597 // size depends on frame count and correct behavior would not be guaranteed
4598 // if frame count is changed after track creation
4599 if (!mTracks.isEmpty()) {
4600 status = INVALID_OPERATION;
4601 } else {
4602 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004603 }
Eric Laurent10351942014-05-08 18:49:52 -07004604 }
4605 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004606#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004607 // when changing the audio output device, call addBatteryData to notify
4608 // the change
4609 if (mOutDevice != value) {
4610 uint32_t params = 0;
4611 // check whether speaker is on
4612 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4613 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004614 }
Eric Laurent10351942014-05-08 18:49:52 -07004615
4616 audio_devices_t deviceWithoutSpeaker
4617 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4618 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07004619 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07004620 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4621 }
4622
4623 if (params != 0) {
4624 addBatteryData(params);
4625 }
4626 }
Eric Laurent81784c32012-11-19 14:55:58 -08004627#endif
4628
Eric Laurent10351942014-05-08 18:49:52 -07004629 // forward device change to effects that have requested to be
4630 // aware of attached audio device.
4631 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08004632 a2dpDeviceChanged =
4633 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07004634 mOutDevice = value;
4635 for (size_t i = 0; i < mEffectChains.size(); i++) {
4636 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004637 }
4638 }
Eric Laurent10351942014-05-08 18:49:52 -07004639 }
Eric Laurent81784c32012-11-19 14:55:58 -08004640
Eric Laurent10351942014-05-08 18:49:52 -07004641 if (status == NO_ERROR) {
4642 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4643 keyValuePair.string());
4644 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004645 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004646 mStandby = true;
4647 mBytesWritten = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004648 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Eric Laurent10351942014-05-08 18:49:52 -07004649 keyValuePair.string());
Eric Laurent81784c32012-11-19 14:55:58 -08004650 }
Eric Laurent10351942014-05-08 18:49:52 -07004651 if (status == NO_ERROR && reconfig) {
4652 readOutputParameters_l();
4653 delete mAudioMixer;
4654 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4655 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004656 int name = getTrackName_l(mTracks[i]->mChannelMask,
4657 mTracks[i]->mFormat, mTracks[i]->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07004658 if (name < 0) {
4659 break;
4660 }
4661 mTracks[i]->mName = name;
4662 }
Eric Laurent73e26b62015-04-27 16:55:58 -07004663 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004664 }
Eric Laurent81784c32012-11-19 14:55:58 -08004665 }
4666
Eric Laurent42537be2016-01-08 17:16:42 -08004667 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08004668}
4669
4670
4671void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4672{
Eric Laurent81784c32012-11-19 14:55:58 -08004673 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07004674 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Elliott Hughes87cebad2014-05-22 10:14:43 -07004675 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Andy Hung2ddee192015-12-18 17:34:44 -08004676 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent81784c32012-11-19 14:55:58 -08004677
4678 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten2f90c512015-12-02 11:40:09 -08004679 // while we are dumping it. It may be inconsistent, but it won't mutate!
4680 // This is a large object so we place it on the heap.
4681 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
4682 const FastMixerDumpState *copy = new FastMixerDumpState(mFastMixerDumpState);
4683 copy->dump(fd);
4684 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08004685
4686#ifdef STATE_QUEUE_DUMP
4687 // Similar for state queue
4688 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4689 observerCopy.dump(fd);
4690 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4691 mutatorCopy.dump(fd);
4692#endif
4693
Glenn Kasten46909e72013-02-26 09:20:22 -08004694#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004695 // Write the tee output to a .wav file
4696 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08004697#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004698
4699#ifdef AUDIO_WATCHDOG
4700 if (mAudioWatchdog != 0) {
4701 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4702 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4703 wdCopy.dump(fd);
4704 }
4705#endif
4706}
4707
4708uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4709{
4710 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4711}
4712
4713uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4714{
4715 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4716}
4717
4718void AudioFlinger::MixerThread::cacheParameters_l()
4719{
4720 PlaybackThread::cacheParameters_l();
4721
4722 // FIXME: Relaxed timing because of a certain device that can't meet latency
4723 // Should be reduced to 2x after the vendor fixes the driver issue
4724 // increase threshold again due to low power audio mode. The way this warning
4725 // threshold is calculated and its usefulness should be reconsidered anyway.
4726 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4727}
4728
4729// ----------------------------------------------------------------------------
4730
4731AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07004732 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady)
4733 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08004734 // mLeftVolFloat, mRightVolFloat
4735{
4736}
4737
Eric Laurentbfb1b832013-01-07 09:53:42 -08004738AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4739 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurente93cc032016-05-05 10:15:10 -07004740 ThreadBase::type_t type, bool systemReady)
4741 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004742 // mLeftVolFloat, mRightVolFloat
4743{
4744}
4745
Eric Laurent81784c32012-11-19 14:55:58 -08004746AudioFlinger::DirectOutputThread::~DirectOutputThread()
4747{
4748}
4749
Eric Laurentbfb1b832013-01-07 09:53:42 -08004750void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
4751{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004752 float left, right;
4753
4754 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4755 left = right = 0;
4756 } else {
4757 float typeVolume = mStreamTypes[track->streamType()].volume;
4758 float v = mMasterVolume * typeVolume;
4759 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004760 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4761 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4762 if (left > GAIN_FLOAT_UNITY) {
4763 left = GAIN_FLOAT_UNITY;
4764 }
4765 left *= v;
4766 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4767 if (right > GAIN_FLOAT_UNITY) {
4768 right = GAIN_FLOAT_UNITY;
4769 }
4770 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004771 }
4772
4773 if (lastTrack) {
4774 if (left != mLeftVolFloat || right != mRightVolFloat) {
4775 mLeftVolFloat = left;
4776 mRightVolFloat = right;
4777
4778 // Convert volumes from float to 8.24
4779 uint32_t vl = (uint32_t)(left * (1 << 24));
4780 uint32_t vr = (uint32_t)(right * (1 << 24));
4781
4782 // Delegate volume control to effect in track effect chain if needed
4783 // only one effect chain can be present on DirectOutputThread, so if
4784 // there is one, the track is connected to it
4785 if (!mEffectChains.isEmpty()) {
4786 mEffectChains[0]->setVolume_l(&vl, &vr);
4787 left = (float)vl / (1 << 24);
4788 right = (float)vr / (1 << 24);
4789 }
4790 if (mOutput->stream->set_volume) {
4791 mOutput->stream->set_volume(mOutput->stream, left, right);
4792 }
4793 }
4794 }
4795}
4796
Phil Burk43b4dcc2015-06-09 16:53:44 -07004797void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
4798{
4799 sp<Track> previousTrack = mPreviousTrack.promote();
4800 sp<Track> latestTrack = mLatestActiveTrack.promote();
4801
Eric Laurent0f0631e2015-07-06 18:01:25 -07004802 if (previousTrack != 0 && latestTrack != 0) {
4803 if (mType == DIRECT) {
4804 if (previousTrack.get() != latestTrack.get()) {
4805 mFlushPending = true;
4806 }
4807 } else /* mType == OFFLOAD */ {
4808 if (previousTrack->sessionId() != latestTrack->sessionId()) {
4809 mFlushPending = true;
4810 }
4811 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004812 }
4813 PlaybackThread::onAddNewTrack_l();
4814}
Eric Laurentbfb1b832013-01-07 09:53:42 -08004815
Eric Laurent81784c32012-11-19 14:55:58 -08004816AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4817 Vector< sp<Track> > *tracksToRemove
4818)
4819{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004820 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004821 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004822 bool doHwPause = false;
4823 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004824
4825 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07004826 for (size_t i = 0; i < count; i++) {
4827 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08004828 // The track died recently
4829 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004830 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08004831 }
4832
Phil Burk43b4dcc2015-06-09 16:53:44 -07004833 if (t->isInvalid()) {
4834 ALOGW("An invalidated track shouldn't be in active list");
4835 tracksToRemove->add(t);
4836 continue;
4837 }
4838
Eric Laurent81784c32012-11-19 14:55:58 -08004839 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004840#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08004841 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004842#endif
Eric Laurentfd477972013-10-25 18:10:40 -07004843 // Only consider last track started for volume and mixer state control.
4844 // In theory an older track could underrun and restart after the new one starts
4845 // but as we only care about the transition phase between two tracks on a
4846 // direct output, it is not a problem to ignore the underrun case.
4847 sp<Track> l = mLatestActiveTrack.promote();
4848 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004849
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004850 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004851 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004852 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004853 doHwPause = true;
4854 mHwPaused = true;
4855 }
4856 tracksToRemove->add(track);
4857 } else if (track->isFlushPending()) {
4858 track->flushAck();
4859 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004860 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004861 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004862 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004863 track->resumeAck();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004864 if (last && mHwPaused) {
4865 doHwResume = true;
4866 mHwPaused = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004867 }
4868 }
4869
Eric Laurent81784c32012-11-19 14:55:58 -08004870 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004871 // for all its buffers to be filled before processing it.
4872 // Allow draining the buffer in case the client
4873 // app does not call stop() and relies on underrun to stop:
4874 // hence the test on (track->mRetryCount > 1).
4875 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07004876 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08004877 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004878 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08004879 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004880 minFrames = mNormalFrameCount;
4881 } else {
4882 minFrames = 1;
4883 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004884
Eric Laurentab5cdba2014-06-09 17:22:27 -07004885 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4886 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004887 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004888 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004889
4890 if (track->mFillingUpStatus == Track::FS_FILLED) {
4891 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004892 // make sure processVolume_l() will apply new volume even if 0
4893 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004894 if (!mHwSupportsPause) {
4895 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004896 }
4897 }
4898
4899 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004900 processVolume_l(track, last);
4901 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004902 sp<Track> previousTrack = mPreviousTrack.promote();
4903 if (previousTrack != 0) {
4904 if (track != previousTrack.get()) {
4905 // Flush any data still being written from last track
4906 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07004907 // Invalidate previous track to force a seek when resuming.
4908 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004909 }
4910 }
4911 mPreviousTrack = track;
4912
Eric Laurentd595b7c2013-04-03 17:27:56 -07004913 // reset retry count
4914 track->mRetryCount = kMaxTrackRetriesDirect;
4915 mActiveTrack = t;
4916 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07004917 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004918 doHwResume = true;
4919 mHwPaused = false;
4920 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004921 }
Eric Laurent81784c32012-11-19 14:55:58 -08004922 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004923 // clear effect chain input buffer if the last active track started underruns
4924 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004925 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004926 mEffectChains[0]->clearInputBuffer();
4927 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004928 if (track->isStopping_1()) {
4929 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07004930 if (last && mHwPaused) {
4931 doHwResume = true;
4932 mHwPaused = false;
4933 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004934 }
4935 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4936 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004937 // We have consumed all the buffers of this track.
4938 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004939 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08004940 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004941 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4942 } else {
4943 audioHALFrames = 0;
4944 }
4945
Andy Hung818e7a32016-02-16 18:08:07 -08004946 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004947 if (mStandby || !last ||
4948 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004949 if (track->isStopping_2()) {
4950 track->mState = TrackBase::STOPPED;
4951 }
Eric Laurent81784c32012-11-19 14:55:58 -08004952 if (track->isStopped()) {
4953 track->reset();
4954 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004955 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004956 }
4957 } else {
4958 // No buffers for this track. Give it a few chances to
4959 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004960 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004961 if (--(track->mRetryCount) <= 0) {
4962 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004963 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004964 // indicate to client process that the track was disabled because of underrun;
4965 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004966 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004967 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07004968 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
4969 "minFrames = %u, mFormat = %#x",
4970 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08004971 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07004972 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004973 doHwPause = true;
4974 mHwPaused = true;
4975 }
Eric Laurent81784c32012-11-19 14:55:58 -08004976 }
4977 }
4978 }
4979 }
4980
Eric Laurentd1f69b02014-12-15 14:33:13 -08004981 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07004982 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004983 for (size_t i = 0; i < mTracks.size(); i++) {
4984 if (mTracks[i]->isFlushPending()) {
4985 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004986 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004987 }
4988 }
4989 }
4990
4991 // make sure the pause/flush/resume sequence is executed in the right order.
4992 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4993 // before flush and then resume HW. This can happen in case of pause/flush/resume
4994 // if resume is received before pause is executed.
4995 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07004996 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004997 mOutput->stream->pause(mOutput->stream);
4998 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004999 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005000 flushHw_l();
5001 }
5002 if (mHwSupportsPause && !mStandby && doHwResume) {
5003 mOutput->stream->resume(mOutput->stream);
5004 }
Eric Laurent81784c32012-11-19 14:55:58 -08005005 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005006 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005007
5008 return mixerStatus;
5009}
5010
5011void AudioFlinger::DirectOutputThread::threadLoop_mix()
5012{
Eric Laurent81784c32012-11-19 14:55:58 -08005013 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08005014 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005015 // output audio to hardware
5016 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07005017 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005018 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08005019 status_t status = mActiveTrack->getNextBuffer(&buffer);
5020 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08005021 // no need to pad with 0 for compressed audio
5022 if (audio_has_proportional_frames(mFormat)) {
5023 memset(curBuf, 0, frameCount * mFrameSize);
5024 }
Eric Laurent81784c32012-11-19 14:55:58 -08005025 break;
5026 }
5027 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
5028 frameCount -= buffer.frameCount;
5029 curBuf += buffer.frameCount * mFrameSize;
5030 mActiveTrack->releaseBuffer(&buffer);
5031 }
Andy Hung2098f272014-02-27 14:00:06 -08005032 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005033 mSleepTimeUs = 0;
5034 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005035 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005036}
5037
5038void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
5039{
Eric Laurentd1f69b02014-12-15 14:33:13 -08005040 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005041 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005042 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005043 return;
5044 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005045 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005046 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurente93cc032016-05-05 10:15:10 -07005047 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005048 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005049 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005050 }
Phil Burkfdb3c072016-02-09 10:47:02 -08005051 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08005052 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005053 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005054 }
5055}
5056
Eric Laurentd1f69b02014-12-15 14:33:13 -08005057void AudioFlinger::DirectOutputThread::threadLoop_exit()
5058{
5059 {
5060 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005061 for (size_t i = 0; i < mTracks.size(); i++) {
5062 if (mTracks[i]->isFlushPending()) {
5063 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005064 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005065 }
5066 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005067 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005068 flushHw_l();
5069 }
5070 }
5071 PlaybackThread::threadLoop_exit();
5072}
5073
5074// must be called with thread mutex locked
5075bool AudioFlinger::DirectOutputThread::shouldStandby_l()
5076{
5077 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07005078 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005079
vivek mehta9cd7ad12016-03-17 00:18:29 -07005080 if ((mType == DIRECT) && audio_is_linear_pcm(mFormat) && !usesHwAvSync()) {
5081 return !mStandby;
5082 }
5083
Eric Laurentd1f69b02014-12-15 14:33:13 -08005084 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
5085 // after a timeout and we will enter standby then.
5086 if (mTracks.size() > 0) {
5087 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07005088 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
5089 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005090 }
5091
Eric Laurent5cff4032015-05-26 13:49:58 -07005092 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08005093}
5094
Eric Laurent81784c32012-11-19 14:55:58 -08005095// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005096int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Glenn Kastend848eb42016-03-08 13:42:11 -08005097 audio_format_t format __unused, audio_session_t sessionId __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005098{
5099 return 0;
5100}
5101
5102// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005103void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005104{
5105}
5106
Eric Laurent10351942014-05-08 18:49:52 -07005107// checkForNewParameter_l() must be called with ThreadBase::mLock held
5108bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
5109 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005110{
5111 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005112 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005113
Eric Laurent10351942014-05-08 18:49:52 -07005114 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005115
Eric Laurent10351942014-05-08 18:49:52 -07005116 AudioParameter param = AudioParameter(keyValuePair);
5117 int value;
5118 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5119 // forward device change to effects that have requested to be
5120 // aware of attached audio device.
5121 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005122 a2dpDeviceChanged =
5123 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005124 mOutDevice = value;
5125 for (size_t i = 0; i < mEffectChains.size(); i++) {
5126 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07005127 }
5128 }
Eric Laurent81784c32012-11-19 14:55:58 -08005129 }
Eric Laurent10351942014-05-08 18:49:52 -07005130 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5131 // do not accept frame count changes if tracks are open as the track buffer
5132 // size depends on frame count and correct behavior would not be garantied
5133 // if frame count is changed after track creation
5134 if (!mTracks.isEmpty()) {
5135 status = INVALID_OPERATION;
5136 } else {
5137 reconfig = true;
5138 }
5139 }
5140 if (status == NO_ERROR) {
5141 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
5142 keyValuePair.string());
5143 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005144 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005145 mStandby = true;
5146 mBytesWritten = 0;
5147 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
5148 keyValuePair.string());
5149 }
5150 if (status == NO_ERROR && reconfig) {
5151 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07005152 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005153 }
5154 }
5155
Eric Laurent42537be2016-01-08 17:16:42 -08005156 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005157}
5158
5159uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
5160{
5161 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005162 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005163 time = PlaybackThread::activeSleepTimeUs();
5164 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005165 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005166 }
5167 return time;
5168}
5169
5170uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
5171{
5172 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005173 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005174 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
5175 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005176 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005177 }
5178 return time;
5179}
5180
5181uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
5182{
5183 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005184 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005185 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
5186 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005187 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005188 }
5189 return time;
5190}
5191
5192void AudioFlinger::DirectOutputThread::cacheParameters_l()
5193{
5194 PlaybackThread::cacheParameters_l();
5195
5196 // use shorter standby delay as on normal output to release
5197 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07005198 // no delay on outputs with HW A/V sync
5199 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005200 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08005201 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005202 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07005203 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005204 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07005205 }
Eric Laurent81784c32012-11-19 14:55:58 -08005206}
5207
Eric Laurente659ef42014-09-29 13:06:46 -07005208void AudioFlinger::DirectOutputThread::flushHw_l()
5209{
Phil Burk062e67a2015-02-11 13:40:50 -08005210 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08005211 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005212 mFlushPending = false;
Eric Laurente659ef42014-09-29 13:06:46 -07005213}
5214
Eric Laurent81784c32012-11-19 14:55:58 -08005215// ----------------------------------------------------------------------------
5216
Eric Laurentbfb1b832013-01-07 09:53:42 -08005217AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07005218 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005219 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07005220 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07005221 mWriteAckSequence(0),
5222 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005223{
5224}
5225
5226AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
5227{
5228}
5229
5230void AudioFlinger::AsyncCallbackThread::onFirstRef()
5231{
5232 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
5233}
5234
5235bool AudioFlinger::AsyncCallbackThread::threadLoop()
5236{
5237 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005238 uint32_t writeAckSequence;
5239 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005240
5241 {
5242 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005243 while (!((mWriteAckSequence & 1) ||
5244 (mDrainSequence & 1) ||
5245 exitPending())) {
5246 mWaitWorkCV.wait(mLock);
5247 }
5248
Eric Laurentbfb1b832013-01-07 09:53:42 -08005249 if (exitPending()) {
5250 break;
5251 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005252 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
5253 mWriteAckSequence, mDrainSequence);
5254 writeAckSequence = mWriteAckSequence;
5255 mWriteAckSequence &= ~1;
5256 drainSequence = mDrainSequence;
5257 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005258 }
5259 {
Eric Laurent4de95592013-09-26 15:28:21 -07005260 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
5261 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005262 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005263 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005264 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005265 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005266 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005267 }
5268 }
5269 }
5270 }
5271 return false;
5272}
5273
5274void AudioFlinger::AsyncCallbackThread::exit()
5275{
5276 ALOGV("AsyncCallbackThread::exit");
5277 Mutex::Autolock _l(mLock);
5278 requestExit();
5279 mWaitWorkCV.broadcast();
5280}
5281
Eric Laurent3b4529e2013-09-05 18:09:19 -07005282void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005283{
5284 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005285 // bit 0 is cleared
5286 mWriteAckSequence = sequence << 1;
5287}
5288
5289void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5290{
5291 Mutex::Autolock _l(mLock);
5292 // ignore unexpected callbacks
5293 if (mWriteAckSequence & 2) {
5294 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005295 mWaitWorkCV.signal();
5296 }
5297}
5298
Eric Laurent3b4529e2013-09-05 18:09:19 -07005299void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005300{
5301 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005302 // bit 0 is cleared
5303 mDrainSequence = sequence << 1;
5304}
5305
5306void AudioFlinger::AsyncCallbackThread::resetDraining()
5307{
5308 Mutex::Autolock _l(mLock);
5309 // ignore unexpected callbacks
5310 if (mDrainSequence & 2) {
5311 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005312 mWaitWorkCV.signal();
5313 }
5314}
5315
5316
5317// ----------------------------------------------------------------------------
5318AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07005319 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
5320 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Eric Laurent64667972016-03-30 18:19:46 -07005321 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005322{
Eric Laurentfd477972013-10-25 18:10:40 -07005323 //FIXME: mStandby should be set to true by ThreadBase constructor
5324 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07005325 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005326}
5327
Eric Laurentbfb1b832013-01-07 09:53:42 -08005328void AudioFlinger::OffloadThread::threadLoop_exit()
5329{
5330 if (mFlushPending || mHwPaused) {
5331 // If a flush is pending or track was paused, just discard buffered data
5332 flushHw_l();
5333 } else {
5334 mMixerStatus = MIXER_DRAIN_ALL;
5335 threadLoop_drain();
5336 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005337 if (mUseAsyncWrite) {
5338 ALOG_ASSERT(mCallbackThread != 0);
5339 mCallbackThread->exit();
5340 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005341 PlaybackThread::threadLoop_exit();
5342}
5343
5344AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5345 Vector< sp<Track> > *tracksToRemove
5346)
5347{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005348 size_t count = mActiveTracks.size();
5349
5350 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005351 bool doHwPause = false;
5352 bool doHwResume = false;
5353
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005354 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07005355
Eric Laurentbfb1b832013-01-07 09:53:42 -08005356 // find out which tracks need to be processed
5357 for (size_t i = 0; i < count; i++) {
5358 sp<Track> t = mActiveTracks[i].promote();
5359 // The track died recently
5360 if (t == 0) {
5361 continue;
5362 }
5363 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005364#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08005365 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005366#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005367 // Only consider last track started for volume and mixer state control.
5368 // In theory an older track could underrun and restart after the new one starts
5369 // but as we only care about the transition phase between two tracks on a
5370 // direct output, it is not a problem to ignore the underrun case.
5371 sp<Track> l = mLatestActiveTrack.promote();
5372 bool last = l.get() == track;
5373
Haynes Mathew George7844f672014-01-15 12:32:55 -08005374 if (track->isInvalid()) {
5375 ALOGW("An invalidated track shouldn't be in active list");
5376 tracksToRemove->add(track);
5377 continue;
5378 }
5379
5380 if (track->mState == TrackBase::IDLE) {
5381 ALOGW("An idle track shouldn't be in active list");
5382 continue;
5383 }
5384
Eric Laurentbfb1b832013-01-07 09:53:42 -08005385 if (track->isPausing()) {
5386 track->setPaused();
5387 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005388 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005389 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005390 mHwPaused = true;
5391 }
5392 // If we were part way through writing the mixbuffer to
5393 // the HAL we must save this until we resume
5394 // BUG - this will be wrong if a different track is made active,
5395 // in that case we want to discard the pending data in the
5396 // mixbuffer and tell the client to present it again when the
5397 // track is resumed
5398 mPausedWriteLength = mCurrentWriteLength;
5399 mPausedBytesRemaining = mBytesRemaining;
5400 mBytesRemaining = 0; // stop writing
5401 }
5402 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005403 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005404 if (track->isStopping_1()) {
5405 track->mRetryCount = kMaxTrackStopRetriesOffload;
5406 } else {
5407 track->mRetryCount = kMaxTrackRetriesOffload;
5408 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08005409 track->flushAck();
5410 if (last) {
5411 mFlushPending = true;
5412 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005413 } else if (track->isResumePending()){
5414 track->resumeAck();
5415 if (last) {
5416 if (mPausedBytesRemaining) {
5417 // Need to continue write that was interrupted
5418 mCurrentWriteLength = mPausedWriteLength;
5419 mBytesRemaining = mPausedBytesRemaining;
5420 mPausedBytesRemaining = 0;
5421 }
5422 if (mHwPaused) {
5423 doHwResume = true;
5424 mHwPaused = false;
5425 // threadLoop_mix() will handle the case that we need to
5426 // resume an interrupted write
5427 }
5428 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005429 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005430
5431 // Do not handle new data in this iteration even if track->framesReady()
5432 mixerStatus = MIXER_TRACKS_ENABLED;
5433 }
5434 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005435 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005436 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005437 if (track->mFillingUpStatus == Track::FS_FILLED) {
5438 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07005439 // make sure processVolume_l() will apply new volume even if 0
5440 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005441 }
5442
5443 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005444 sp<Track> previousTrack = mPreviousTrack.promote();
5445 if (previousTrack != 0) {
5446 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005447 // Flush any data still being written from last track
5448 mBytesRemaining = 0;
5449 if (mPausedBytesRemaining) {
5450 // Last track was paused so we also need to flush saved
5451 // mixbuffer state and invalidate track so that it will
5452 // re-submit that unwritten data when it is next resumed
5453 mPausedBytesRemaining = 0;
5454 // Invalidate is a bit drastic - would be more efficient
5455 // to have a flag to tell client that some of the
5456 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005457 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005458 }
5459 // flush data already sent to the DSP if changing audio session as audio
5460 // comes from a different source. Also invalidate previous track to force a
5461 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005462 if (previousTrack->sessionId() != track->sessionId()) {
5463 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005464 }
5465 }
5466 }
5467 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005468 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07005469 if (track->isStopping_1()) {
5470 track->mRetryCount = kMaxTrackStopRetriesOffload;
5471 } else {
5472 track->mRetryCount = kMaxTrackRetriesOffload;
5473 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005474 mActiveTrack = t;
5475 mixerStatus = MIXER_TRACKS_READY;
5476 }
5477 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005478 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005479 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005480 if (--(track->mRetryCount) <= 0) {
5481 // Hardware buffer can hold a large amount of audio so we must
5482 // wait for all current track's data to drain before we say
5483 // that the track is stopped.
5484 if (mBytesRemaining == 0) {
5485 // Only start draining when all data in mixbuffer
5486 // has been written
5487 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5488 track->mState = TrackBase::STOPPING_2; // so presentation completes after
5489 // drain do not drain if no data was ever sent to HAL (mStandby == true)
5490 if (last && !mStandby) {
5491 // do not modify drain sequence if we are already draining. This happens
5492 // when resuming from pause after drain.
5493 if ((mDrainSequence & 1) == 0) {
5494 mSleepTimeUs = 0;
5495 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
5496 mixerStatus = MIXER_DRAIN_TRACK;
5497 mDrainSequence += 2;
5498 }
5499 if (mHwPaused) {
5500 // It is possible to move from PAUSED to STOPPING_1 without
5501 // a resume so we must ensure hardware is running
5502 doHwResume = true;
5503 mHwPaused = false;
5504 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005505 }
5506 }
Eric Laurente93cc032016-05-05 10:15:10 -07005507 } else if (last) {
5508 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
5509 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005510 }
5511 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005512 // Drain has completed or we are in standby, signal presentation complete
5513 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005514 track->mState = TrackBase::STOPPED;
5515 size_t audioHALFrames =
5516 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005517 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005518 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005519 track->presentationComplete(framesWritten, audioHALFrames);
5520 track->reset();
5521 tracksToRemove->add(track);
5522 }
5523 } else {
5524 // No buffers for this track. Give it a few chances to
5525 // fill a buffer, then remove it from active list.
5526 if (--(track->mRetryCount) <= 0) {
5527 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5528 track->name());
5529 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005530 // indicate to client process that the track was disabled because of underrun;
5531 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005532 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005533 } else if (last){
5534 mixerStatus = MIXER_TRACKS_ENABLED;
5535 }
5536 }
5537 }
5538 // compute volume for this track
5539 processVolume_l(track, last);
5540 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005541
Eric Laurentea0fade2013-10-04 16:23:48 -07005542 // make sure the pause/flush/resume sequence is executed in the right order.
5543 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5544 // before flush and then resume HW. This can happen in case of pause/flush/resume
5545 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07005546 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07005547 mOutput->stream->pause(mOutput->stream);
5548 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005549 if (mFlushPending) {
5550 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005551 }
Eric Laurentfd477972013-10-25 18:10:40 -07005552 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07005553 mOutput->stream->resume(mOutput->stream);
5554 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005555
Eric Laurentbfb1b832013-01-07 09:53:42 -08005556 // remove all the tracks that need to be...
5557 removeTracks_l(*tracksToRemove);
5558
5559 return mixerStatus;
5560}
5561
Eric Laurentbfb1b832013-01-07 09:53:42 -08005562// must be called with thread mutex locked
5563bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5564{
Eric Laurent3b4529e2013-09-05 18:09:19 -07005565 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5566 mWriteAckSequence, mDrainSequence);
5567 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005568 return true;
5569 }
5570 return false;
5571}
5572
Eric Laurentbfb1b832013-01-07 09:53:42 -08005573bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5574{
5575 Mutex::Autolock _l(mLock);
5576 return waitingAsyncCallback_l();
5577}
5578
5579void AudioFlinger::OffloadThread::flushHw_l()
5580{
Eric Laurente659ef42014-09-29 13:06:46 -07005581 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005582 // Flush anything still waiting in the mixbuffer
5583 mCurrentWriteLength = 0;
5584 mBytesRemaining = 0;
5585 mPausedWriteLength = 0;
5586 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07005587 // reset bytes written count to reflect that DSP buffers are empty after flush.
5588 mBytesWritten = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08005589
Eric Laurentbfb1b832013-01-07 09:53:42 -08005590 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005591 // discard any pending drain or write ack by incrementing sequence
5592 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5593 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005594 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005595 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5596 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005597 }
5598}
5599
Haynes Mathew George05317d22016-05-03 16:34:26 -07005600void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
5601{
5602 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07005603 if (PlaybackThread::invalidateTracks_l(streamType)) {
5604 mFlushPending = true;
5605 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07005606}
5607
Eric Laurentbfb1b832013-01-07 09:53:42 -08005608// ----------------------------------------------------------------------------
5609
Eric Laurent81784c32012-11-19 14:55:58 -08005610AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005611 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005612 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07005613 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08005614 mWaitTimeMs(UINT_MAX)
5615{
5616 addOutputTrack(mainThread);
5617}
5618
5619AudioFlinger::DuplicatingThread::~DuplicatingThread()
5620{
5621 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5622 mOutputTracks[i]->destroy();
5623 }
5624}
5625
5626void AudioFlinger::DuplicatingThread::threadLoop_mix()
5627{
5628 // mix buffers...
5629 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08005630 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08005631 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005632 if (mMixerBufferValid) {
5633 memset(mMixerBuffer, 0, mMixerBufferSize);
5634 } else {
5635 memset(mSinkBuffer, 0, mSinkBufferSize);
5636 }
Eric Laurent81784c32012-11-19 14:55:58 -08005637 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005638 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005639 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005640 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005641 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005642}
5643
5644void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5645{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005646 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005647 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005648 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005649 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005650 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005651 }
5652 } else if (mBytesWritten != 0) {
5653 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5654 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005655 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005656 } else {
5657 // flush remaining overflow buffers in output tracks
5658 writeFrames = 0;
5659 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005660 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005661 }
5662}
5663
Eric Laurentbfb1b832013-01-07 09:53:42 -08005664ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005665{
5666 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005667 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005668 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005669 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005670 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005671}
5672
5673void AudioFlinger::DuplicatingThread::threadLoop_standby()
5674{
5675 // DuplicatingThread implements standby by stopping all tracks
5676 for (size_t i = 0; i < outputTracks.size(); i++) {
5677 outputTracks[i]->stop();
5678 }
5679}
5680
5681void AudioFlinger::DuplicatingThread::saveOutputTracks()
5682{
5683 outputTracks = mOutputTracks;
5684}
5685
5686void AudioFlinger::DuplicatingThread::clearOutputTracks()
5687{
5688 outputTracks.clear();
5689}
5690
5691void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5692{
5693 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005694 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5695 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5696 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5697 const size_t frameCount =
5698 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5699 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5700 // from different OutputTracks and their associated MixerThreads (e.g. one may
5701 // nearly empty and the other may be dropping data).
5702
5703 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005704 this,
5705 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005706 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005707 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005708 frameCount,
5709 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08005710 if (outputTrack->cblk() != NULL) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005711 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
Eric Laurent81784c32012-11-19 14:55:58 -08005712 mOutputTracks.add(outputTrack);
Andy Hungc25b84a2015-01-14 19:04:10 -08005713 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005714 updateWaitTime_l();
5715 }
5716}
5717
5718void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5719{
5720 Mutex::Autolock _l(mLock);
5721 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5722 if (mOutputTracks[i]->thread() == thread) {
5723 mOutputTracks[i]->destroy();
5724 mOutputTracks.removeAt(i);
5725 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07005726 if (thread->getOutput() == mOutput) {
5727 mOutput = NULL;
5728 }
Eric Laurent81784c32012-11-19 14:55:58 -08005729 return;
5730 }
5731 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07005732 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005733}
5734
5735// caller must hold mLock
5736void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5737{
5738 mWaitTimeMs = UINT_MAX;
5739 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5740 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5741 if (strong != 0) {
5742 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5743 if (waitTimeMs < mWaitTimeMs) {
5744 mWaitTimeMs = waitTimeMs;
5745 }
5746 }
5747 }
5748}
5749
5750
5751bool AudioFlinger::DuplicatingThread::outputsReady(
5752 const SortedVector< sp<OutputTrack> > &outputTracks)
5753{
5754 for (size_t i = 0; i < outputTracks.size(); i++) {
5755 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5756 if (thread == 0) {
5757 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5758 outputTracks[i].get());
5759 return false;
5760 }
5761 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5762 // see note at standby() declaration
5763 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5764 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5765 thread.get());
5766 return false;
5767 }
5768 }
5769 return true;
5770}
5771
5772uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5773{
5774 return (mWaitTimeMs * 1000) / 2;
5775}
5776
5777void AudioFlinger::DuplicatingThread::cacheParameters_l()
5778{
5779 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5780 updateWaitTime_l();
5781
5782 MixerThread::cacheParameters_l();
5783}
5784
5785// ----------------------------------------------------------------------------
5786// Record
5787// ----------------------------------------------------------------------------
5788
5789AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5790 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005791 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005792 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07005793 audio_devices_t inDevice,
5794 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08005795#ifdef TEE_SINK
5796 , const sp<NBAIO_Sink>& teeSink
5797#endif
5798 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07005799 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005800 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005801 // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005802 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005803#ifdef TEE_SINK
5804 , mTeeSink(teeSink)
5805#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005806 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5807 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005808 // mFastCapture below
5809 , mFastCaptureFutex(0)
5810 // mInputSource
5811 // mPipeSink
5812 // mPipeSource
5813 , mPipeFramesP2(0)
5814 // mPipeMemory
5815 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005816 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005817{
Glenn Kastend7dca052015-03-05 16:05:54 -08005818 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5819 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08005820
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005821 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005822
5823 // create an NBAIO source for the HAL input stream, and negotiate
5824 mInputSource = new AudioStreamInSource(input->stream);
5825 size_t numCounterOffers = 0;
5826 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005827#if !LOG_NDEBUG
5828 ssize_t index =
5829#else
5830 (void)
5831#endif
5832 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005833 ALOG_ASSERT(index == 0);
5834
5835 // initialize fast capture depending on configuration
5836 bool initFastCapture;
5837 switch (kUseFastCapture) {
5838 case FastCapture_Never:
5839 initFastCapture = false;
5840 break;
5841 case FastCapture_Always:
5842 initFastCapture = true;
5843 break;
5844 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07005845 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005846 break;
5847 // case FastCapture_Dynamic:
5848 }
5849
5850 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07005851 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005852 NBAIO_Format format = mInputSource->format();
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005853 size_t pipeFramesP2 = roundup(mSampleRate / 25); // double-buffering of 20 ms each
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005854 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5855 void *pipeBuffer;
5856 const sp<MemoryDealer> roHeap(readOnlyHeap());
5857 sp<IMemory> pipeMemory;
5858 if ((roHeap == 0) ||
5859 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5860 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5861 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5862 goto failed;
5863 }
5864 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5865 memset(pipeBuffer, 0, pipeSize);
5866 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5867 const NBAIO_Format offers[1] = {format};
5868 size_t numCounterOffers = 0;
5869 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5870 ALOG_ASSERT(index == 0);
5871 mPipeSink = pipe;
5872 PipeReader *pipeReader = new PipeReader(*pipe);
5873 numCounterOffers = 0;
5874 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5875 ALOG_ASSERT(index == 0);
5876 mPipeSource = pipeReader;
5877 mPipeFramesP2 = pipeFramesP2;
5878 mPipeMemory = pipeMemory;
5879
5880 // create fast capture
5881 mFastCapture = new FastCapture();
5882 FastCaptureStateQueue *sq = mFastCapture->sq();
5883#ifdef STATE_QUEUE_DUMP
5884 // FIXME
5885#endif
5886 FastCaptureState *state = sq->begin();
5887 state->mCblk = NULL;
5888 state->mInputSource = mInputSource.get();
5889 state->mInputSourceGen++;
5890 state->mPipeSink = pipe;
5891 state->mPipeSinkGen++;
5892 state->mFrameCount = mFrameCount;
5893 state->mCommand = FastCaptureState::COLD_IDLE;
5894 // already done in constructor initialization list
5895 //mFastCaptureFutex = 0;
5896 state->mColdFutexAddr = &mFastCaptureFutex;
5897 state->mColdGen++;
5898 state->mDumpState = &mFastCaptureDumpState;
5899#ifdef TEE_SINK
5900 // FIXME
5901#endif
5902 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
5903 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
5904 sq->end();
5905 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5906
5907 // start the fast capture
5908 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
5909 pid_t tid = mFastCapture->getTid();
Glenn Kasten8379b722016-03-18 14:54:17 -07005910 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005911#ifdef AUDIO_WATCHDOG
5912 // FIXME
5913#endif
5914
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005915 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005916 }
5917failed: ;
5918
5919 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08005920}
5921
Eric Laurent81784c32012-11-19 14:55:58 -08005922AudioFlinger::RecordThread::~RecordThread()
5923{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005924 if (mFastCapture != 0) {
5925 FastCaptureStateQueue *sq = mFastCapture->sq();
5926 FastCaptureState *state = sq->begin();
5927 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5928 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5929 if (old == -1) {
5930 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5931 }
5932 }
5933 state->mCommand = FastCaptureState::EXIT;
5934 sq->end();
5935 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5936 mFastCapture->join();
5937 mFastCapture.clear();
5938 }
5939 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07005940 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07005941 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08005942}
5943
5944void AudioFlinger::RecordThread::onFirstRef()
5945{
Glenn Kastend7dca052015-03-05 16:05:54 -08005946 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08005947}
5948
Eric Laurent81784c32012-11-19 14:55:58 -08005949bool AudioFlinger::RecordThread::threadLoop()
5950{
Eric Laurent81784c32012-11-19 14:55:58 -08005951 nsecs_t lastWarning = 0;
5952
5953 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08005954
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005955reacquire_wakelock:
5956 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08005957 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005958 {
5959 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005960 size_t size = mActiveTracks.size();
5961 activeTracksGen = mActiveTracksGen;
5962 if (size > 0) {
5963 // FIXME an arbitrary choice
5964 activeTrack = mActiveTracks[0];
5965 acquireWakeLock_l(activeTrack->uid());
5966 if (size > 1) {
5967 SortedVector<int> tmp;
5968 for (size_t i = 0; i < size; i++) {
5969 tmp.add(mActiveTracks[i]->uid());
5970 }
5971 updateWakeLockUids_l(tmp);
5972 }
5973 } else {
5974 acquireWakeLock_l(-1);
5975 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005976 }
5977
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005978 // used to request a deferred sleep, to be executed later while mutex is unlocked
5979 uint32_t sleepUs = 0;
5980
5981 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005982 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005983 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07005984
Glenn Kasten5edadd42013-08-14 16:30:49 -07005985 // sleep with mutex unlocked
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005986 if (sleepUs > 0) {
Glenn Kastene7754022014-10-31 12:11:26 -07005987 ATRACE_BEGIN("sleep");
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005988 usleep(sleepUs);
Glenn Kastene7754022014-10-31 12:11:26 -07005989 ATRACE_END();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005990 sleepUs = 0;
Glenn Kasten5edadd42013-08-14 16:30:49 -07005991 }
5992
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005993 // activeTracks accumulates a copy of a subset of mActiveTracks
5994 Vector< sp<RecordTrack> > activeTracks;
5995
Glenn Kasten735f45f2014-08-18 15:51:59 -07005996 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005997 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07005998
Glenn Kasten735f45f2014-08-18 15:51:59 -07005999 // reference to a fast track which is about to be removed
6000 sp<RecordTrack> fastTrackToRemove;
6001
Eric Laurent81784c32012-11-19 14:55:58 -08006002 { // scope for mLock
6003 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08006004
Eric Laurent021cf962014-05-13 10:18:14 -07006005 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006006
Eric Laurent000a4192014-01-29 15:17:32 -08006007 // check exitPending here because checkForNewParameters_l() and
6008 // checkForNewParameters_l() can temporarily release mLock
6009 if (exitPending()) {
6010 break;
6011 }
6012
Glenn Kasten2b806402013-11-20 16:37:38 -08006013 // if no active track(s), then standby and release wakelock
6014 size_t size = mActiveTracks.size();
6015 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07006016 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006017 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08006018 releaseWakeLock_l();
6019 ALOGV("RecordThread: loop stopping");
6020 // go to sleep
6021 mWaitWorkCV.wait(mLock);
6022 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006023 goto reacquire_wakelock;
6024 }
6025
Glenn Kasten2b806402013-11-20 16:37:38 -08006026 if (mActiveTracksGen != activeTracksGen) {
6027 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006028 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08006029 for (size_t i = 0; i < size; i++) {
6030 tmp.add(mActiveTracks[i]->uid());
6031 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006032 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08006033 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006034
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006035 bool doBroadcast = false;
6036 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07006037
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006038 activeTrack = mActiveTracks[i];
6039 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07006040 if (activeTrack->isFastTrack()) {
6041 ALOG_ASSERT(fastTrackToRemove == 0);
6042 fastTrackToRemove = activeTrack;
6043 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006044 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08006045 mActiveTracks.remove(activeTrack);
6046 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006047 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07006048 continue;
6049 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006050
6051 TrackBase::track_state activeTrackState = activeTrack->mState;
6052 switch (activeTrackState) {
6053
6054 case TrackBase::PAUSING:
6055 mActiveTracks.remove(activeTrack);
6056 mActiveTracksGen++;
6057 doBroadcast = true;
6058 size--;
6059 continue;
6060
6061 case TrackBase::STARTING_1:
6062 sleepUs = 10000;
6063 i++;
6064 continue;
6065
6066 case TrackBase::STARTING_2:
6067 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006068 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07006069 activeTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006070 break;
6071
6072 case TrackBase::ACTIVE:
6073 break;
6074
6075 case TrackBase::IDLE:
6076 i++;
6077 continue;
6078
6079 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08006080 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07006081 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006082
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006083 activeTracks.add(activeTrack);
6084 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07006085
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006086 if (activeTrack->isFastTrack()) {
6087 ALOG_ASSERT(!mFastTrackAvail);
6088 ALOG_ASSERT(fastTrack == 0);
6089 fastTrack = activeTrack;
6090 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006091 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006092 if (doBroadcast) {
6093 mStartStopCond.broadcast();
6094 }
6095
6096 // sleep if there are no active tracks to process
6097 if (activeTracks.size() == 0) {
6098 if (sleepUs == 0) {
6099 sleepUs = kRecordThreadSleepUs;
6100 }
6101 continue;
6102 }
6103 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07006104
Eric Laurent81784c32012-11-19 14:55:58 -08006105 lockEffectChains_l(effectChains);
6106 }
6107
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006108 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07006109
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006110 size_t size = effectChains.size();
6111 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006112 // thread mutex is not locked, but effect chain is locked
6113 effectChains[i]->process_l();
6114 }
6115
Glenn Kasten735f45f2014-08-18 15:51:59 -07006116 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006117 if (mFastCapture != 0) {
6118 FastCaptureStateQueue *sq = mFastCapture->sq();
6119 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07006120 bool didModify = false;
6121 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006122 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
6123 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
6124 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6125 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6126 if (old == -1) {
6127 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6128 }
6129 }
6130 state->mCommand = FastCaptureState::READ_WRITE;
6131#if 0 // FIXME
6132 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08006133 FastThreadDumpState::kSamplingNforLowRamDevice :
6134 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006135#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07006136 didModify = true;
6137 }
6138 audio_track_cblk_t *cblkOld = state->mCblk;
6139 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
6140 if (cblkNew != cblkOld) {
6141 state->mCblk = cblkNew;
6142 // block until acked if removing a fast track
6143 if (cblkOld != NULL) {
6144 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
6145 }
6146 didModify = true;
6147 }
6148 sq->end(didModify);
6149 if (didModify) {
6150 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006151#if 0
6152 if (kUseFastCapture == FastCapture_Dynamic) {
6153 mNormalSource = mPipeSource;
6154 }
6155#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006156 }
6157 }
6158
Glenn Kasten735f45f2014-08-18 15:51:59 -07006159 // now run the fast track destructor with thread mutex unlocked
6160 fastTrackToRemove.clear();
6161
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006162 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
6163 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
6164 // slow, then this RecordThread will overrun by not calling HAL read often enough.
6165 // If destination is non-contiguous, first read past the nominal end of buffer, then
6166 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006167
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006168 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006169 ssize_t framesRead;
6170
6171 // If an NBAIO source is present, use it to read the normal capture's data
6172 if (mPipeSource != 0) {
6173 size_t framesToRead = mBufferSize / mFrameSize;
Andy Hung57446612015-04-19 23:56:46 -07006174 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
Glenn Kastend79072e2016-01-06 08:41:20 -08006175 framesToRead);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006176 if (framesRead == 0) {
6177 // since pipe is non-blocking, simulate blocking input
6178 sleepUs = (framesToRead * 1000000LL) / mSampleRate;
6179 }
6180 // otherwise use the HAL / AudioStreamIn directly
6181 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07006182 ATRACE_BEGIN("read");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006183 ssize_t bytesRead = mInput->stream->read(mInput->stream,
Andy Hung57446612015-04-19 23:56:46 -07006184 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize);
Glenn Kastenec6a7032016-03-14 07:40:23 -07006185 ATRACE_END();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006186 if (bytesRead < 0) {
6187 framesRead = bytesRead;
6188 } else {
6189 framesRead = bytesRead / mFrameSize;
6190 }
6191 }
6192
Andy Hung3f0c9022016-01-15 17:49:46 -08006193 // Update server timestamp with server stats
6194 // systemTime() is optional if the hardware supports timestamps.
6195 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
6196 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6197
6198 // Update server timestamp with kernel stats
6199 if (mInput->stream->get_capture_position != nullptr) {
6200 int64_t position, time;
6201 int ret = mInput->stream->get_capture_position(mInput->stream, &position, &time);
6202 if (ret == NO_ERROR) {
6203 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
6204 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
6205 // Note: In general record buffers should tend to be empty in
6206 // a properly running pipeline.
6207 //
6208 // Also, it is not advantageous to call get_presentation_position during the read
6209 // as the read obtains a lock, preventing the timestamp call from executing.
6210 }
6211 }
6212 // Use this to track timestamp information
6213 // ALOGD("%s", mTimestamp.toString().c_str());
6214
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006215 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006216 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006217 // Force input into standby so that it tries to recover at next read attempt
6218 inputStandBy();
6219 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006220 }
6221 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006222 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006223 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006224 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006225
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006226 if (mTeeSink != 0) {
Andy Hung57446612015-04-19 23:56:46 -07006227 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006228 }
6229 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006230 {
6231 size_t part1 = mRsmpInFramesP2 - rear;
6232 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07006233 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006234 (framesRead - part1) * mFrameSize);
6235 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006236 }
6237 rear = mRsmpInRear += framesRead;
6238
6239 size = activeTracks.size();
6240 // loop over each active track
6241 for (size_t i = 0; i < size; i++) {
6242 activeTrack = activeTracks[i];
6243
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006244 // skip fast tracks, as those are handled directly by FastCapture
6245 if (activeTrack->isFastTrack()) {
6246 continue;
6247 }
6248
Andy Hung73c02e42015-03-29 01:13:58 -07006249 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07006250 // TODO: Update the activeTrack buffer converter in case of reconfigure.
6251
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006252 enum {
6253 OVERRUN_UNKNOWN,
6254 OVERRUN_TRUE,
6255 OVERRUN_FALSE
6256 } overrun = OVERRUN_UNKNOWN;
6257
6258 // loop over getNextBuffer to handle circular sink
6259 for (;;) {
6260
6261 activeTrack->mSink.frameCount = ~0;
6262 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
6263 size_t framesOut = activeTrack->mSink.frameCount;
6264 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
6265
Andy Hung73c02e42015-03-29 01:13:58 -07006266 // check available frames and handle overrun conditions
6267 // if the record track isn't draining fast enough.
6268 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006269 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07006270 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
6271 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006272 overrun = OVERRUN_TRUE;
6273 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006274 if (framesOut == 0 || framesIn == 0) {
6275 break;
6276 }
6277
Andy Hung6770c6f2015-04-07 13:43:36 -07006278 // Don't allow framesOut to be larger than what is possible with resampling
6279 // from framesIn.
6280 // This isn't strictly necessary but helps limit buffer resizing in
6281 // RecordBufferConverter. TODO: remove when no longer needed.
6282 framesOut = min(framesOut,
6283 destinationFramesPossible(
6284 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07006285 // process frames from the RecordThread buffer provider to the RecordTrack buffer
6286 framesOut = activeTrack->mRecordBufferConverter->convert(
6287 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006288
6289 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
6290 overrun = OVERRUN_FALSE;
6291 }
6292
6293 if (activeTrack->mFramesToDrop == 0) {
6294 if (framesOut > 0) {
6295 activeTrack->mSink.frameCount = framesOut;
6296 activeTrack->releaseBuffer(&activeTrack->mSink);
6297 }
6298 } else {
6299 // FIXME could do a partial drop of framesOut
6300 if (activeTrack->mFramesToDrop > 0) {
6301 activeTrack->mFramesToDrop -= framesOut;
6302 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006303 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006304 }
6305 } else {
6306 activeTrack->mFramesToDrop += framesOut;
6307 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
6308 activeTrack->mSyncStartEvent->isCancelled()) {
6309 ALOGW("Synced record %s, session %d, trigger session %d",
6310 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
6311 activeTrack->sessionId(),
6312 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08006313 activeTrack->mSyncStartEvent->triggerSession() :
6314 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006315 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006316 }
6317 }
6318 }
6319
6320 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006321 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006322 }
6323 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006324
6325 switch (overrun) {
6326 case OVERRUN_TRUE:
6327 // client isn't retrieving buffers fast enough
6328 if (!activeTrack->setOverflow()) {
6329 nsecs_t now = systemTime();
6330 // FIXME should lastWarning per track?
6331 if ((now - lastWarning) > kWarningThrottleNs) {
6332 ALOGW("RecordThread: buffer overflow");
6333 lastWarning = now;
6334 }
6335 }
6336 break;
6337 case OVERRUN_FALSE:
6338 activeTrack->clearOverflow();
6339 break;
6340 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006341 break;
6342 }
6343
Andy Hung3f0c9022016-01-15 17:49:46 -08006344 // update frame information and push timestamp out
6345 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08006346 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08006347 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
6348 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006349 }
6350
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006351unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08006352 // enable changes in effect chain
6353 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006354 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08006355 }
6356
Glenn Kasten93e471f2013-08-19 08:40:07 -07006357 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08006358
6359 {
6360 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07006361 for (size_t i = 0; i < mTracks.size(); i++) {
6362 sp<RecordTrack> track = mTracks[i];
6363 track->invalidate();
6364 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006365 mActiveTracks.clear();
6366 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08006367 mStartStopCond.broadcast();
6368 }
6369
6370 releaseWakeLock();
6371
6372 ALOGV("RecordThread %p exiting", this);
6373 return false;
6374}
6375
Glenn Kasten93e471f2013-08-19 08:40:07 -07006376void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08006377{
6378 if (!mStandby) {
6379 inputStandBy();
6380 mStandby = true;
6381 }
6382}
6383
6384void AudioFlinger::RecordThread::inputStandBy()
6385{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006386 // Idle the fast capture if it's currently running
6387 if (mFastCapture != 0) {
6388 FastCaptureStateQueue *sq = mFastCapture->sq();
6389 FastCaptureState *state = sq->begin();
6390 if (!(state->mCommand & FastCaptureState::IDLE)) {
6391 state->mCommand = FastCaptureState::COLD_IDLE;
6392 state->mColdFutexAddr = &mFastCaptureFutex;
6393 state->mColdGen++;
6394 mFastCaptureFutex = 0;
6395 sq->end();
6396 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
6397 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
6398#if 0
6399 if (kUseFastCapture == FastCapture_Dynamic) {
6400 // FIXME
6401 }
6402#endif
6403#ifdef AUDIO_WATCHDOG
6404 // FIXME
6405#endif
6406 } else {
6407 sq->end(false /*didModify*/);
6408 }
6409 }
Eric Laurent81784c32012-11-19 14:55:58 -08006410 mInput->stream->common.standby(&mInput->stream->common);
6411}
6412
Glenn Kasten05997e22014-03-13 15:08:33 -07006413// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07006414sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08006415 const sp<AudioFlinger::Client>& client,
6416 uint32_t sampleRate,
6417 audio_format_t format,
6418 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08006419 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08006420 audio_session_t sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07006421 size_t *notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006422 int uid,
Eric Laurent05067782016-06-01 18:27:28 -07006423 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08006424 pid_t tid,
6425 status_t *status)
6426{
Glenn Kasten74935e42013-12-19 08:56:45 -08006427 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08006428 sp<RecordTrack> track;
6429 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07006430 audio_input_flags_t inputFlags = mInput->flags;
6431
6432 // special case for FAST flag considered OK if fast capture is present
6433 if (hasFastCapture()) {
6434 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
6435 }
6436
6437 // Check if requested flags are compatible with output stream flags
6438 if ((*flags & inputFlags) != *flags) {
6439 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
6440 " input flags (%08x)",
6441 *flags, inputFlags);
6442 *flags = (audio_input_flags_t)(*flags & inputFlags);
6443 }
Eric Laurent81784c32012-11-19 14:55:58 -08006444
Glenn Kasten90e58b12013-07-31 16:16:02 -07006445 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07006446 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006447 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07006448 // we formerly checked for a callback handler (non-0 tid),
6449 // but that is no longer required for TRANSFER_OBTAIN mode
6450 //
Glenn Kasten74105912014-07-03 12:28:53 -07006451 // frame count is not specified, or is exactly the pipe depth
6452 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006453 // PCM data
6454 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006455 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006456 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006457 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006458 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006459 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07006460 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006461 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006462 hasFastCapture() &&
6463 // there are sufficient fast track slots available
6464 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07006465 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07006466 // check compatibility with audio effects.
6467 Mutex::Autolock _l(mLock);
6468 // Do not accept FAST flag if the session has software effects
6469 sp<EffectChain> chain = getEffectChain_l(sessionId);
6470 if (chain != 0) {
Eric Laurent122f7e72016-06-29 11:53:29 -07006471 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_RAW) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07006472 "AUDIO_INPUT_FLAG_RAW denied: effect present on session");
6473 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_RAW);
6474 if (chain->hasSoftwareEffect()) {
6475 ALOGV("AUDIO_INPUT_FLAG_FAST denied: software effect present on session");
6476 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
6477 }
6478 }
Eric Laurent122f7e72016-06-29 11:53:29 -07006479 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07006480 "AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
6481 frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006482 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006483 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
Glenn Kasten74105912014-07-03 12:28:53 -07006484 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006485 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07006486 frameCount, mFrameCount, mPipeFramesP2,
6487 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
6488 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07006489 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07006490 }
6491 }
6492
6493 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07006494 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07006495 // fast track: frame count is exactly the pipe depth
6496 frameCount = mPipeFramesP2;
6497 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
6498 *notificationFrames = mFrameCount;
6499 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006500 // not fast track: max notification period is resampled equivalent of one HAL buffer time
6501 // or 20 ms if there is a fast capture
6502 // TODO This could be a roundupRatio inline, and const
6503 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
6504 * sampleRate + mSampleRate - 1) / mSampleRate;
6505 // minimum number of notification periods is at least kMinNotifications,
6506 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
6507 static const size_t kMinNotifications = 3;
6508 static const uint32_t kMinMs = 30;
6509 // TODO This could be a roundupRatio inline
6510 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
6511 // TODO This could be a roundupRatio inline
6512 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
6513 maxNotificationFrames;
6514 const size_t minFrameCount = maxNotificationFrames *
6515 max(kMinNotifications, minNotificationsByMs);
6516 frameCount = max(frameCount, minFrameCount);
6517 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
6518 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07006519 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07006520 }
Glenn Kasten74935e42013-12-19 08:56:45 -08006521 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07006522
Glenn Kasten15e57982013-09-24 11:52:37 -07006523 lStatus = initCheck();
6524 if (lStatus != NO_ERROR) {
6525 ALOGE("createRecordTrack_l() audio driver not initialized");
6526 goto Exit;
6527 }
Eric Laurent81784c32012-11-19 14:55:58 -08006528
6529 { // scope for mLock
6530 Mutex::Autolock _l(mLock);
6531
6532 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07006533 format, channelMask, frameCount, NULL, sessionId, uid,
6534 *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08006535
Glenn Kasten03003332013-08-06 15:40:54 -07006536 lStatus = track->initCheck();
6537 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07006538 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08006539 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08006540 goto Exit;
6541 }
6542 mTracks.add(track);
6543
6544 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6545 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6546 mAudioFlinger->btNrecIsOff();
6547 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6548 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006549
Eric Laurent05067782016-06-01 18:27:28 -07006550 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006551 pid_t callingPid = IPCThreadState::self()->getCallingPid();
6552 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
6553 // so ask activity manager to do this on our behalf
6554 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
6555 }
Eric Laurent81784c32012-11-19 14:55:58 -08006556 }
Glenn Kasten05997e22014-03-13 15:08:33 -07006557
Eric Laurent81784c32012-11-19 14:55:58 -08006558 lStatus = NO_ERROR;
6559
6560Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07006561 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08006562 return track;
6563}
6564
6565status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6566 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08006567 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08006568{
6569 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6570 sp<ThreadBase> strongMe = this;
6571 status_t status = NO_ERROR;
6572
6573 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006574 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006575 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006576 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08006577 triggerSession,
6578 recordTrack->sessionId(),
6579 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006580 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08006581 // Sync event can be cancelled by the trigger session if the track is not in a
6582 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006583 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006584 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006585 } else {
6586 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006587 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006588 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08006589 }
6590 }
6591
6592 {
Glenn Kasten47c20702013-08-13 15:37:35 -07006593 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08006594 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006595 if (mActiveTracks.indexOf(recordTrack) >= 0) {
6596 if (recordTrack->mState == TrackBase::PAUSING) {
6597 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006598 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006599 } else {
6600 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08006601 }
6602 return status;
6603 }
6604
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006605 // TODO consider other ways of handling this, such as changing the state to :STARTING and
6606 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6607 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006608 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08006609 mActiveTracks.add(recordTrack);
6610 mActiveTracksGen++;
Eric Laurent83b88082014-06-20 18:31:16 -07006611 status_t status = NO_ERROR;
6612 if (recordTrack->isExternalTrack()) {
6613 mLock.unlock();
Glenn Kastend848eb42016-03-08 13:42:11 -08006614 status = AudioSystem::startInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006615 mLock.lock();
6616 // FIXME should verify that recordTrack is still in mActiveTracks
6617 if (status != NO_ERROR) {
6618 mActiveTracks.remove(recordTrack);
6619 mActiveTracksGen++;
6620 recordTrack->clearSyncStartEvent();
6621 ALOGV("RecordThread::start error %d", status);
6622 return status;
6623 }
Eric Laurent81784c32012-11-19 14:55:58 -08006624 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006625 // Catch up with current buffer indices if thread is already running.
6626 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
6627 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6628 // see previously buffered data before it called start(), but with greater risk of overrun.
6629
Andy Hung73c02e42015-03-29 01:13:58 -07006630 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07006631 // clear any converter state as new data will be discontinuous
6632 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006633 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08006634 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08006635 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08006636 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006637 ALOGV("Record failed to start");
6638 status = BAD_VALUE;
6639 goto startError;
6640 }
Eric Laurent81784c32012-11-19 14:55:58 -08006641 return status;
6642 }
Glenn Kasten7c027242012-12-26 14:43:16 -08006643
Eric Laurent81784c32012-11-19 14:55:58 -08006644startError:
Eric Laurent83b88082014-06-20 18:31:16 -07006645 if (recordTrack->isExternalTrack()) {
Glenn Kastend848eb42016-03-08 13:42:11 -08006646 AudioSystem::stopInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006647 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006648 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006649 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08006650 return status;
6651}
6652
Eric Laurent81784c32012-11-19 14:55:58 -08006653void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6654{
6655 sp<SyncEvent> strongEvent = event.promote();
6656
6657 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08006658 sp<RefBase> ptr = strongEvent->cookie().promote();
6659 if (ptr != 0) {
6660 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6661 recordTrack->handleSyncStartEvent(strongEvent);
6662 }
Eric Laurent81784c32012-11-19 14:55:58 -08006663 }
6664}
6665
Glenn Kastena8356f62013-07-25 14:37:52 -07006666bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08006667 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07006668 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006669 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08006670 return false;
6671 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006672 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006673 recordTrack->mState = TrackBase::PAUSING;
6674 // do not wait for mStartStopCond if exiting
6675 if (exitPending()) {
6676 return true;
6677 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006678 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08006679 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006680 // if we have been restarted, recordTrack is in mActiveTracks here
6681 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006682 ALOGV("Record stopped OK");
6683 return true;
6684 }
6685 return false;
6686}
6687
Glenn Kasten0f11b512014-01-31 16:18:54 -08006688bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08006689{
6690 return false;
6691}
6692
Glenn Kasten0f11b512014-01-31 16:18:54 -08006693status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006694{
6695#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6696 if (!isValidSyncEvent(event)) {
6697 return BAD_VALUE;
6698 }
6699
Glenn Kastend848eb42016-03-08 13:42:11 -08006700 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08006701 status_t ret = NAME_NOT_FOUND;
6702
6703 Mutex::Autolock _l(mLock);
6704
6705 for (size_t i = 0; i < mTracks.size(); i++) {
6706 sp<RecordTrack> track = mTracks[i];
6707 if (eventSession == track->sessionId()) {
6708 (void) track->setSyncEvent(event);
6709 ret = NO_ERROR;
6710 }
6711 }
6712 return ret;
6713#else
6714 return BAD_VALUE;
6715#endif
6716}
6717
6718// destroyTrack_l() must be called with ThreadBase::mLock held
6719void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6720{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006721 track->terminate();
6722 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006723 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006724 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006725 removeTrack_l(track);
6726 }
6727}
6728
6729void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6730{
6731 mTracks.remove(track);
6732 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006733 if (track->isFastTrack()) {
6734 ALOG_ASSERT(!mFastTrackAvail);
6735 mFastTrackAvail = true;
6736 }
Eric Laurent81784c32012-11-19 14:55:58 -08006737}
6738
6739void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6740{
6741 dumpInternals(fd, args);
6742 dumpTracks(fd, args);
6743 dumpEffectChains(fd, args);
6744}
6745
6746void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6747{
Elliott Hughes87cebad2014-05-22 10:14:43 -07006748 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08006749
Glenn Kasten44182c22015-03-05 17:12:23 -08006750 dumpBase(fd, args);
6751
6752 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006753 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006754 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006755 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006756 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08006757
Glenn Kasten2f90c512015-12-02 11:40:09 -08006758 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
6759 // while we are dumping it. It may be inconsistent, but it won't mutate!
6760 // This is a large object so we place it on the heap.
6761 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
6762 const FastCaptureDumpState *copy = new FastCaptureDumpState(mFastCaptureDumpState);
6763 copy->dump(fd);
6764 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08006765}
6766
Glenn Kasten0f11b512014-01-31 16:18:54 -08006767void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006768{
6769 const size_t SIZE = 256;
6770 char buffer[SIZE];
6771 String8 result;
6772
Marco Nelissenb2208842014-02-07 14:00:50 -08006773 size_t numtracks = mTracks.size();
6774 size_t numactive = mActiveTracks.size();
6775 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006776 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006777 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006778 dprintf(fd, " of which %zu are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006779 RecordTrack::appendDumpHeader(result);
6780 for (size_t i = 0; i < numtracks ; ++i) {
6781 sp<RecordTrack> track = mTracks[i];
6782 if (track != 0) {
6783 bool active = mActiveTracks.indexOf(track) >= 0;
6784 if (active) {
6785 numactiveseen++;
6786 }
6787 track->dump(buffer, SIZE, active);
6788 result.append(buffer);
6789 }
Eric Laurent81784c32012-11-19 14:55:58 -08006790 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006791 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006792 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006793 }
6794
Marco Nelissenb2208842014-02-07 14:00:50 -08006795 if (numactiveseen != numactive) {
6796 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6797 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006798 result.append(buffer);
6799 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006800 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006801 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006802 if (mTracks.indexOf(track) < 0) {
6803 track->dump(buffer, SIZE, true);
6804 result.append(buffer);
6805 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006806 }
Eric Laurent81784c32012-11-19 14:55:58 -08006807
6808 }
6809 write(fd, result.string(), result.size());
6810}
6811
Andy Hung73c02e42015-03-29 01:13:58 -07006812
6813void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
6814{
6815 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6816 RecordThread *recordThread = (RecordThread *) threadBase.get();
6817 mRsmpInFront = recordThread->mRsmpInRear;
6818 mRsmpInUnrel = 0;
6819}
6820
6821void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
6822 size_t *framesAvailable, bool *hasOverrun)
6823{
6824 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6825 RecordThread *recordThread = (RecordThread *) threadBase.get();
6826 const int32_t rear = recordThread->mRsmpInRear;
6827 const int32_t front = mRsmpInFront;
6828 const ssize_t filled = rear - front;
6829
6830 size_t framesIn;
6831 bool overrun = false;
6832 if (filled < 0) {
6833 // should not happen, but treat like a massive overrun and re-sync
6834 framesIn = 0;
6835 mRsmpInFront = rear;
6836 overrun = true;
6837 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
6838 framesIn = (size_t) filled;
6839 } else {
6840 // client is not keeping up with server, but give it latest data
6841 framesIn = recordThread->mRsmpInFrames;
6842 mRsmpInFront = /* front = */ rear - framesIn;
6843 overrun = true;
6844 }
6845 if (framesAvailable != NULL) {
6846 *framesAvailable = framesIn;
6847 }
6848 if (hasOverrun != NULL) {
6849 *hasOverrun = overrun;
6850 }
6851}
6852
Eric Laurent81784c32012-11-19 14:55:58 -08006853// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006854status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08006855 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006856{
Andy Hung73c02e42015-03-29 01:13:58 -07006857 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006858 if (threadBase == 0) {
6859 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006860 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006861 return NOT_ENOUGH_DATA;
6862 }
6863 RecordThread *recordThread = (RecordThread *) threadBase.get();
6864 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07006865 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07006866 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006867 // FIXME should not be P2 (don't want to increase latency)
6868 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006869 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07006870 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006871 front &= recordThread->mRsmpInFramesP2 - 1;
6872 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07006873 if (part1 > (size_t) filled) {
6874 part1 = filled;
6875 }
6876 size_t ask = buffer->frameCount;
6877 ALOG_ASSERT(ask > 0);
6878 if (part1 > ask) {
6879 part1 = ask;
6880 }
6881 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07006882 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07006883 buffer->raw = NULL;
6884 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07006885 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07006886 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08006887 }
6888
Andy Hung57446612015-04-19 23:56:46 -07006889 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07006890 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07006891 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08006892 return NO_ERROR;
6893}
6894
6895// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006896void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
6897 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006898{
Glenn Kasten85948432013-08-19 12:09:05 -07006899 size_t stepCount = buffer->frameCount;
6900 if (stepCount == 0) {
6901 return;
6902 }
Andy Hung73c02e42015-03-29 01:13:58 -07006903 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
6904 mRsmpInUnrel -= stepCount;
6905 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006906 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006907 buffer->frameCount = 0;
6908}
6909
Andy Hung97a893e2015-03-29 01:03:07 -07006910AudioFlinger::RecordThread::RecordBufferConverter::RecordBufferConverter(
6911 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6912 uint32_t srcSampleRate,
6913 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6914 uint32_t dstSampleRate) :
6915 mSrcChannelMask(AUDIO_CHANNEL_INVALID), // updateParameters will set following vars
6916 // mSrcFormat
6917 // mSrcSampleRate
6918 // mDstChannelMask
6919 // mDstFormat
6920 // mDstSampleRate
6921 // mSrcChannelCount
6922 // mDstChannelCount
6923 // mDstFrameSize
6924 mBuf(NULL), mBufFrames(0), mBufFrameSize(0),
Andy Hungd330ee42015-04-20 13:23:41 -07006925 mResampler(NULL),
6926 mIsLegacyDownmix(false),
6927 mIsLegacyUpmix(false),
6928 mRequiresFloat(false),
6929 mInputConverterProvider(NULL)
Andy Hung97a893e2015-03-29 01:03:07 -07006930{
6931 (void)updateParameters(srcChannelMask, srcFormat, srcSampleRate,
6932 dstChannelMask, dstFormat, dstSampleRate);
6933}
6934
6935AudioFlinger::RecordThread::RecordBufferConverter::~RecordBufferConverter() {
6936 free(mBuf);
6937 delete mResampler;
Andy Hungd330ee42015-04-20 13:23:41 -07006938 delete mInputConverterProvider;
Andy Hung97a893e2015-03-29 01:03:07 -07006939}
6940
6941size_t AudioFlinger::RecordThread::RecordBufferConverter::convert(void *dst,
6942 AudioBufferProvider *provider, size_t frames)
6943{
Andy Hungd330ee42015-04-20 13:23:41 -07006944 if (mInputConverterProvider != NULL) {
6945 mInputConverterProvider->setBufferProvider(provider);
6946 provider = mInputConverterProvider;
6947 }
6948
6949 if (mResampler == NULL) {
Andy Hung97a893e2015-03-29 01:03:07 -07006950 ALOGVV("NO RESAMPLING sampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6951 mSrcSampleRate, mSrcFormat, mDstFormat);
6952
6953 AudioBufferProvider::Buffer buffer;
6954 for (size_t i = frames; i > 0; ) {
6955 buffer.frameCount = i;
Glenn Kastend79072e2016-01-06 08:41:20 -08006956 status_t status = provider->getNextBuffer(&buffer);
Andy Hung97a893e2015-03-29 01:03:07 -07006957 if (status != OK || buffer.frameCount == 0) {
6958 frames -= i; // cannot fill request.
6959 break;
6960 }
Andy Hungd330ee42015-04-20 13:23:41 -07006961 // format convert to destination buffer
6962 convertNoResampler(dst, buffer.raw, buffer.frameCount);
Andy Hung97a893e2015-03-29 01:03:07 -07006963
6964 dst = (int8_t*)dst + buffer.frameCount * mDstFrameSize;
6965 i -= buffer.frameCount;
6966 provider->releaseBuffer(&buffer);
6967 }
6968 } else {
6969 ALOGVV("RESAMPLING mSrcSampleRate:%u mDstSampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6970 mSrcSampleRate, mDstSampleRate, mSrcFormat, mDstFormat);
6971
Andy Hungd330ee42015-04-20 13:23:41 -07006972 // reallocate buffer if needed
6973 if (mBufFrameSize != 0 && mBufFrames < frames) {
6974 free(mBuf);
6975 mBufFrames = frames;
6976 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6977 }
Andy Hung97a893e2015-03-29 01:03:07 -07006978 // resampler accumulates, but we only have one source track
Andy Hungd330ee42015-04-20 13:23:41 -07006979 memset(mBuf, 0, frames * mBufFrameSize);
6980 frames = mResampler->resample((int32_t*)mBuf, frames, provider);
6981 // format convert to destination buffer
6982 convertResampler(dst, mBuf, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006983 }
6984 return frames;
6985}
6986
6987status_t AudioFlinger::RecordThread::RecordBufferConverter::updateParameters(
6988 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6989 uint32_t srcSampleRate,
6990 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6991 uint32_t dstSampleRate)
6992{
6993 // quick evaluation if there is any change.
6994 if (mSrcFormat == srcFormat
6995 && mSrcChannelMask == srcChannelMask
6996 && mSrcSampleRate == srcSampleRate
6997 && mDstFormat == dstFormat
6998 && mDstChannelMask == dstChannelMask
6999 && mDstSampleRate == dstSampleRate) {
7000 return NO_ERROR;
7001 }
7002
Andy Hungdb4c0312015-05-06 08:46:52 -07007003 ALOGV("RecordBufferConverter updateParameters srcMask:%#x dstMask:%#x"
7004 " srcFormat:%#x dstFormat:%#x srcRate:%u dstRate:%u",
7005 srcChannelMask, dstChannelMask, srcFormat, dstFormat, srcSampleRate, dstSampleRate);
Andy Hung97a893e2015-03-29 01:03:07 -07007006 const bool valid =
7007 audio_is_input_channel(srcChannelMask)
7008 && audio_is_input_channel(dstChannelMask)
7009 && audio_is_valid_format(srcFormat) && audio_is_linear_pcm(srcFormat)
7010 && audio_is_valid_format(dstFormat) && audio_is_linear_pcm(dstFormat)
7011 && (srcSampleRate <= dstSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX)
7012 ; // no upsampling checks for now
7013 if (!valid) {
7014 return BAD_VALUE;
7015 }
7016
7017 mSrcFormat = srcFormat;
7018 mSrcChannelMask = srcChannelMask;
7019 mSrcSampleRate = srcSampleRate;
7020 mDstFormat = dstFormat;
7021 mDstChannelMask = dstChannelMask;
7022 mDstSampleRate = dstSampleRate;
7023
7024 // compute derived parameters
7025 mSrcChannelCount = audio_channel_count_from_in_mask(srcChannelMask);
7026 mDstChannelCount = audio_channel_count_from_in_mask(dstChannelMask);
7027 mDstFrameSize = mDstChannelCount * audio_bytes_per_sample(mDstFormat);
7028
Andy Hungd330ee42015-04-20 13:23:41 -07007029 // do we need to resample?
7030 delete mResampler;
7031 mResampler = NULL;
7032 if (mSrcSampleRate != mDstSampleRate) {
7033 mResampler = AudioResampler::create(AUDIO_FORMAT_PCM_FLOAT,
7034 mSrcChannelCount, mDstSampleRate);
7035 mResampler->setSampleRate(mSrcSampleRate);
7036 mResampler->setVolume(AudioMixer::UNITY_GAIN_FLOAT, AudioMixer::UNITY_GAIN_FLOAT);
7037 }
7038
7039 // are we running legacy channel conversion modes?
7040 mIsLegacyDownmix = (mSrcChannelMask == AUDIO_CHANNEL_IN_STEREO
7041 || mSrcChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK)
7042 && mDstChannelMask == AUDIO_CHANNEL_IN_MONO;
7043 mIsLegacyUpmix = mSrcChannelMask == AUDIO_CHANNEL_IN_MONO
7044 && (mDstChannelMask == AUDIO_CHANNEL_IN_STEREO
7045 || mDstChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK);
7046
7047 // do we need to process in float?
7048 mRequiresFloat = mResampler != NULL || mIsLegacyDownmix || mIsLegacyUpmix;
7049
7050 // do we need a staging buffer to convert for destination (we can still optimize this)?
7051 // we use mBufFrameSize > 0 to indicate both frame size as well as buffer necessity
7052 if (mResampler != NULL) {
7053 mBufFrameSize = max(mSrcChannelCount, FCC_2)
7054 * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
Andy Hunga97630b2015-07-22 23:27:24 -07007055 } else if (mIsLegacyUpmix || mIsLegacyDownmix) { // legacy modes always float
Andy Hungd330ee42015-04-20 13:23:41 -07007056 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
7057 } else if (mSrcChannelMask != mDstChannelMask && mDstFormat != mSrcFormat) {
Andy Hung97a893e2015-03-29 01:03:07 -07007058 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(mSrcFormat);
7059 } else {
7060 mBufFrameSize = 0;
7061 }
7062 mBufFrames = 0; // force the buffer to be resized.
7063
Andy Hungd330ee42015-04-20 13:23:41 -07007064 // do we need an input converter buffer provider to give us float?
7065 delete mInputConverterProvider;
7066 mInputConverterProvider = NULL;
7067 if (mRequiresFloat && mSrcFormat != AUDIO_FORMAT_PCM_FLOAT) {
7068 mInputConverterProvider = new ReformatBufferProvider(
7069 audio_channel_count_from_in_mask(mSrcChannelMask),
7070 mSrcFormat,
7071 AUDIO_FORMAT_PCM_FLOAT,
7072 256 /* provider buffer frame count */);
7073 }
7074
7075 // do we need a remixer to do channel mask conversion
7076 if (!mIsLegacyDownmix && !mIsLegacyUpmix && mSrcChannelMask != mDstChannelMask) {
7077 (void) memcpy_by_index_array_initialization_from_channel_mask(
7078 mIdxAry, ARRAY_SIZE(mIdxAry), mDstChannelMask, mSrcChannelMask);
Andy Hung97a893e2015-03-29 01:03:07 -07007079 }
7080 return NO_ERROR;
7081}
7082
Andy Hungd330ee42015-04-20 13:23:41 -07007083void AudioFlinger::RecordThread::RecordBufferConverter::convertNoResampler(
7084 void *dst, const void *src, size_t frames)
Andy Hung97a893e2015-03-29 01:03:07 -07007085{
Andy Hungd330ee42015-04-20 13:23:41 -07007086 // src is native type unless there is legacy upmix or downmix, whereupon it is float.
Andy Hung97a893e2015-03-29 01:03:07 -07007087 if (mBufFrameSize != 0 && mBufFrames < frames) {
7088 free(mBuf);
7089 mBufFrames = frames;
7090 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
7091 }
Andy Hungd330ee42015-04-20 13:23:41 -07007092 // do we need to do legacy upmix and downmix?
7093 if (mIsLegacyUpmix || mIsLegacyDownmix) {
Andy Hung97a893e2015-03-29 01:03:07 -07007094 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07007095 if (mIsLegacyUpmix) {
7096 upmix_to_stereo_float_from_mono_float((float *)dstBuf,
7097 (const float *)src, frames);
7098 } else /*mIsLegacyDownmix */ {
7099 downmix_to_mono_float_from_stereo_float((float *)dstBuf,
7100 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07007101 }
Andy Hungd330ee42015-04-20 13:23:41 -07007102 if (mBuf != NULL) {
7103 memcpy_by_audio_format(dst, mDstFormat, mBuf, AUDIO_FORMAT_PCM_FLOAT,
7104 frames * mDstChannelCount);
7105 }
7106 return;
7107 }
7108 // do we need to do channel mask conversion?
7109 if (mSrcChannelMask != mDstChannelMask) {
Andy Hung97a893e2015-03-29 01:03:07 -07007110 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07007111 memcpy_by_index_array(dstBuf, mDstChannelCount,
7112 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mSrcFormat), frames);
7113 if (dstBuf == dst) {
7114 return; // format is the same
7115 }
7116 }
7117 // convert to destination buffer
7118 const void *convertBuf = mBuf != NULL ? mBuf : src;
7119 memcpy_by_audio_format(dst, mDstFormat, convertBuf, mSrcFormat,
7120 frames * mDstChannelCount);
7121}
7122
7123void AudioFlinger::RecordThread::RecordBufferConverter::convertResampler(
7124 void *dst, /*not-a-const*/ void *src, size_t frames)
7125{
7126 // src buffer format is ALWAYS float when entering this routine
7127 if (mIsLegacyUpmix) {
7128 ; // mono to stereo already handled by resampler
7129 } else if (mIsLegacyDownmix
7130 || (mSrcChannelMask == mDstChannelMask && mSrcChannelCount == 1)) {
7131 // the resampler outputs stereo for mono input channel (a feature?)
7132 // must convert to mono
7133 downmix_to_mono_float_from_stereo_float((float *)src,
7134 (const float *)src, frames);
7135 } else if (mSrcChannelMask != mDstChannelMask) {
7136 // convert to mono channel again for channel mask conversion (could be skipped
7137 // with further optimization).
Andy Hung97a893e2015-03-29 01:03:07 -07007138 if (mSrcChannelCount == 1) {
Andy Hungd330ee42015-04-20 13:23:41 -07007139 downmix_to_mono_float_from_stereo_float((float *)src,
7140 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07007141 }
Andy Hungd330ee42015-04-20 13:23:41 -07007142 // convert to destination format (in place, OK as float is larger than other types)
7143 if (mDstFormat != AUDIO_FORMAT_PCM_FLOAT) {
7144 memcpy_by_audio_format(src, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
7145 frames * mSrcChannelCount);
7146 }
7147 // channel convert and save to dst
7148 memcpy_by_index_array(dst, mDstChannelCount,
7149 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mDstFormat), frames);
7150 return;
Andy Hung97a893e2015-03-29 01:03:07 -07007151 }
Andy Hungd330ee42015-04-20 13:23:41 -07007152 // convert to destination format and save to dst
7153 memcpy_by_audio_format(dst, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
7154 frames * mDstChannelCount);
Andy Hung97a893e2015-03-29 01:03:07 -07007155}
7156
Eric Laurent10351942014-05-08 18:49:52 -07007157bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
7158 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007159{
7160 bool reconfig = false;
7161
Eric Laurent10351942014-05-08 18:49:52 -07007162 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007163
Eric Laurent10351942014-05-08 18:49:52 -07007164 audio_format_t reqFormat = mFormat;
7165 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07007166 // 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 -07007167 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
7168
7169 AudioParameter param = AudioParameter(keyValuePair);
7170 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07007171
7172 // scope for AutoPark extends to end of method
7173 AutoPark<FastCapture> park(mFastCapture);
7174
Eric Laurent10351942014-05-08 18:49:52 -07007175 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
7176 // channel count change can be requested. Do we mandate the first client defines the
7177 // HAL sampling rate and channel count or do we allow changes on the fly?
7178 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
7179 samplingRate = value;
7180 reconfig = true;
7181 }
7182 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07007183 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07007184 status = BAD_VALUE;
7185 } else {
7186 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08007187 reconfig = true;
7188 }
Eric Laurent10351942014-05-08 18:49:52 -07007189 }
7190 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
7191 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07007192 if (!audio_is_input_channel(mask) ||
7193 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007194 status = BAD_VALUE;
7195 } else {
7196 channelMask = mask;
7197 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007198 }
Eric Laurent10351942014-05-08 18:49:52 -07007199 }
7200 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7201 // do not accept frame count changes if tracks are open as the track buffer
7202 // size depends on frame count and correct behavior would not be guaranteed
7203 // if frame count is changed after track creation
7204 if (mActiveTracks.size() > 0) {
7205 status = INVALID_OPERATION;
7206 } else {
7207 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007208 }
Eric Laurent10351942014-05-08 18:49:52 -07007209 }
7210 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7211 // forward device change to effects that have requested to be
7212 // aware of attached audio device.
7213 for (size_t i = 0; i < mEffectChains.size(); i++) {
7214 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08007215 }
Eric Laurent81784c32012-11-19 14:55:58 -08007216
Eric Laurent10351942014-05-08 18:49:52 -07007217 // store input device and output device but do not forward output device to audio HAL.
7218 // Note that status is ignored by the caller for output device
7219 // (see AudioFlinger::setParameters()
7220 if (audio_is_output_devices(value)) {
7221 mOutDevice = value;
7222 status = BAD_VALUE;
7223 } else {
7224 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07007225 if (value != AUDIO_DEVICE_NONE) {
7226 mPrevInDevice = value;
7227 }
Eric Laurent10351942014-05-08 18:49:52 -07007228 // disable AEC and NS if the device is a BT SCO headset supporting those
7229 // pre processings
7230 if (mTracks.size() > 0) {
7231 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7232 mAudioFlinger->btNrecIsOff();
7233 for (size_t i = 0; i < mTracks.size(); i++) {
7234 sp<RecordTrack> track = mTracks[i];
7235 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7236 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08007237 }
7238 }
7239 }
Eric Laurent10351942014-05-08 18:49:52 -07007240 }
7241 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
7242 mAudioSource != (audio_source_t)value) {
7243 // forward device change to effects that have requested to be
7244 // aware of attached audio device.
7245 for (size_t i = 0; i < mEffectChains.size(); i++) {
7246 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08007247 }
Eric Laurent10351942014-05-08 18:49:52 -07007248 mAudioSource = (audio_source_t)value;
7249 }
Glenn Kastene198c362013-08-13 09:13:36 -07007250
Eric Laurent10351942014-05-08 18:49:52 -07007251 if (status == NO_ERROR) {
7252 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7253 keyValuePair.string());
7254 if (status == INVALID_OPERATION) {
7255 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08007256 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7257 keyValuePair.string());
Eric Laurent10351942014-05-08 18:49:52 -07007258 }
7259 if (reconfig) {
7260 if (status == BAD_VALUE &&
Andy Hung97a893e2015-03-29 01:03:07 -07007261 audio_is_linear_pcm(mInput->stream->common.get_format(&mInput->stream->common)) &&
7262 audio_is_linear_pcm(reqFormat) &&
Eric Laurent10351942014-05-08 18:49:52 -07007263 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
Andy Hung97a893e2015-03-29 01:03:07 -07007264 <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate)) &&
Andy Hunge5412692014-05-16 11:25:07 -07007265 audio_channel_count_from_in_mask(
Andy Hungd1abb8f2015-05-05 23:42:34 -07007266 mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007267 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007268 }
Eric Laurent10351942014-05-08 18:49:52 -07007269 if (status == NO_ERROR) {
7270 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007271 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08007272 }
7273 }
Eric Laurent81784c32012-11-19 14:55:58 -08007274 }
Eric Laurent10351942014-05-08 18:49:52 -07007275
Eric Laurent81784c32012-11-19 14:55:58 -08007276 return reconfig;
7277}
7278
7279String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
7280{
Eric Laurent81784c32012-11-19 14:55:58 -08007281 Mutex::Autolock _l(mLock);
7282 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07007283 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08007284 }
7285
Glenn Kastend8ea6992013-07-16 14:17:15 -07007286 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
7287 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08007288 free(s);
7289 return out_s8;
7290}
7291
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007292void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007293 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7294
7295 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08007296
7297 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007298 case AUDIO_INPUT_OPENED:
7299 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07007300 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07007301 desc->mChannelMask = mChannelMask;
7302 desc->mSamplingRate = mSampleRate;
7303 desc->mFormat = mFormat;
7304 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07007305 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07007306 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007307 break;
7308
Eric Laurent73e26b62015-04-27 16:55:58 -07007309 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08007310 default:
7311 break;
7312 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007313 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08007314}
7315
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007316void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007317{
Eric Laurent81784c32012-11-19 14:55:58 -08007318 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
7319 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Andy Hunge5412692014-05-16 11:25:07 -07007320 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Andy Hungd330ee42015-04-20 13:23:41 -07007321 if (mChannelCount > FCC_8) {
7322 ALOGE("HAL channel count %d > %d", mChannelCount, FCC_8);
7323 }
Andy Hung463be252014-07-10 16:56:07 -07007324 mHALFormat = mInput->stream->common.get_format(&mInput->stream->common);
7325 mFormat = mHALFormat;
Andy Hungd330ee42015-04-20 13:23:41 -07007326 if (!audio_is_linear_pcm(mFormat)) {
7327 ALOGE("HAL format %#x is not linear pcm", mFormat);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07007328 }
Eric Laurent665470b2014-07-03 16:37:08 -07007329 mFrameSize = audio_stream_in_frame_size(mInput->stream);
Glenn Kasten548efc92012-11-29 08:48:51 -08007330 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
7331 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007332 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08007333 // 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 -07007334 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08007335 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007336 // A larger value should allow more old data to be read after a track calls start(),
7337 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07007338 //
7339 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08007340 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07007341 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07007342 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07007343 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007344
7345 // TODO optimize audio capture buffer sizes ...
7346 // Here we calculate the size of the sliding buffer used as a source
7347 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
7348 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
7349 // be better to have it derived from the pipe depth in the long term.
7350 // The current value is higher than necessary. However it should not add to latency.
7351
Glenn Kasten85948432013-08-19 12:09:05 -07007352 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Andy Hung0a01c2f2015-09-21 12:44:54 -07007353 size_t bufferSize = (mRsmpInFramesP2 + mFrameCount - 1) * mFrameSize;
7354 (void)posix_memalign(&mRsmpInBuffer, 32, bufferSize);
7355 memset(mRsmpInBuffer, 0, bufferSize); // if posix_memalign fails, will segv here.
Eric Laurent81784c32012-11-19 14:55:58 -08007356
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007357 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
7358 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08007359}
7360
Glenn Kasten5f972c02014-01-13 09:59:31 -08007361uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08007362{
7363 Mutex::Autolock _l(mLock);
7364 if (initCheck() != NO_ERROR) {
7365 return 0;
7366 }
7367
7368 return mInput->stream->get_input_frames_lost(mInput->stream);
7369}
7370
Eric Laurent4c415062016-06-17 16:14:16 -07007371// hasAudioSession_l() must be called with ThreadBase::mLock held
7372uint32_t AudioFlinger::RecordThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08007373{
Eric Laurent81784c32012-11-19 14:55:58 -08007374 uint32_t result = 0;
7375 if (getEffectChain_l(sessionId) != 0) {
7376 result = EFFECT_SESSION;
7377 }
7378
7379 for (size_t i = 0; i < mTracks.size(); ++i) {
7380 if (sessionId == mTracks[i]->sessionId()) {
7381 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07007382 if (mTracks[i]->isFastTrack()) {
7383 result |= FAST_SESSION;
7384 }
Eric Laurent81784c32012-11-19 14:55:58 -08007385 break;
7386 }
7387 }
7388
7389 return result;
7390}
7391
Glenn Kastend848eb42016-03-08 13:42:11 -08007392KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08007393{
Glenn Kastend848eb42016-03-08 13:42:11 -08007394 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08007395 Mutex::Autolock _l(mLock);
7396 for (size_t j = 0; j < mTracks.size(); ++j) {
7397 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08007398 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08007399 if (ids.indexOfKey(sessionId) < 0) {
7400 ids.add(sessionId, true);
7401 }
7402 }
7403 return ids;
7404}
7405
7406AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7407{
7408 Mutex::Autolock _l(mLock);
7409 AudioStreamIn *input = mInput;
7410 mInput = NULL;
7411 return input;
7412}
7413
7414// this method must always be called either with ThreadBase mLock held or inside the thread loop
7415audio_stream_t* AudioFlinger::RecordThread::stream() const
7416{
7417 if (mInput == NULL) {
7418 return NULL;
7419 }
7420 return &mInput->stream->common;
7421}
7422
7423status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7424{
7425 // only one chain per input thread
7426 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07007427 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08007428 return INVALID_OPERATION;
7429 }
7430 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07007431 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08007432 chain->setInBuffer(NULL);
7433 chain->setOutBuffer(NULL);
7434
7435 checkSuspendOnAddEffectChain_l(chain);
7436
Eric Laurent1b928682014-10-02 19:41:47 -07007437 // make sure enabled pre processing effects state is communicated to the HAL as we
7438 // just moved them to a new input stream.
7439 chain->syncHalEffectsState();
7440
Eric Laurent81784c32012-11-19 14:55:58 -08007441 mEffectChains.add(chain);
7442
7443 return NO_ERROR;
7444}
7445
7446size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7447{
7448 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7449 ALOGW_IF(mEffectChains.size() != 1,
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007450 "removeEffectChain_l() %p invalid chain size %zu on thread %p",
Eric Laurent81784c32012-11-19 14:55:58 -08007451 chain.get(), mEffectChains.size(), this);
7452 if (mEffectChains.size() == 1) {
7453 mEffectChains.removeAt(0);
7454 }
7455 return 0;
7456}
7457
Eric Laurent1c333e22014-05-20 10:48:17 -07007458status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7459 audio_patch_handle_t *handle)
7460{
7461 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007462
7463 // store new device and send to effects
7464 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07007465 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07007466 for (size_t i = 0; i < mEffectChains.size(); i++) {
7467 mEffectChains[i]->setDevice_l(mInDevice);
7468 }
7469
7470 // disable AEC and NS if the device is a BT SCO headset supporting those
7471 // pre processings
7472 if (mTracks.size() > 0) {
7473 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7474 mAudioFlinger->btNrecIsOff();
7475 for (size_t i = 0; i < mTracks.size(); i++) {
7476 sp<RecordTrack> track = mTracks[i];
7477 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7478 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
7479 }
7480 }
7481
7482 // store new source and send to effects
7483 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7484 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07007485 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07007486 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07007487 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007488 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007489
Eric Laurent054d9d32015-04-24 08:48:48 -07007490 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007491 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
7492 status = hwDevice->create_audio_patch(hwDevice,
7493 patch->num_sources,
7494 patch->sources,
7495 patch->num_sinks,
7496 patch->sinks,
7497 handle);
7498 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007499 char *address;
7500 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7501 address = audio_device_address_to_parameter(
7502 patch->sources[0].ext.device.type,
7503 patch->sources[0].ext.device.address);
7504 } else {
7505 address = (char *)calloc(1, 1);
7506 }
7507 AudioParameter param = AudioParameter(String8(address));
7508 free(address);
7509 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING),
7510 (int)patch->sources[0].ext.device.type);
7511 param.addInt(String8(AUDIO_PARAMETER_STREAM_INPUT_SOURCE),
7512 (int)patch->sinks[0].ext.mix.usecase.source);
7513 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7514 param.toString().string());
7515 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07007516 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007517
Eric Laurente8726fe2015-06-26 09:39:24 -07007518 if (mInDevice != mPrevInDevice) {
7519 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7520 mPrevInDevice = mInDevice;
7521 }
Eric Laurent296fb132015-05-01 11:38:42 -07007522
Eric Laurent1c333e22014-05-20 10:48:17 -07007523 return status;
7524}
7525
7526status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7527{
7528 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007529
7530 mInDevice = AUDIO_DEVICE_NONE;
7531
Eric Laurent1c333e22014-05-20 10:48:17 -07007532 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
7533 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
7534 status = hwDevice->release_audio_patch(hwDevice, handle);
7535 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007536 AudioParameter param;
7537 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
7538 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7539 param.toString().string());
Eric Laurent1c333e22014-05-20 10:48:17 -07007540 }
7541 return status;
7542}
7543
Eric Laurent83b88082014-06-20 18:31:16 -07007544void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
7545{
7546 Mutex::Autolock _l(mLock);
7547 mTracks.add(record);
7548}
7549
7550void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
7551{
7552 Mutex::Autolock _l(mLock);
7553 destroyTrack_l(record);
7554}
7555
7556void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
7557{
7558 ThreadBase::getAudioPortConfig(config);
7559 config->role = AUDIO_PORT_ROLE_SINK;
7560 config->ext.mix.hw_module = mInput->audioHwDev->handle();
7561 config->ext.mix.usecase.source = mAudioSource;
7562}
Eric Laurent1c333e22014-05-20 10:48:17 -07007563
Glenn Kasten63238ef2015-03-02 15:50:29 -08007564} // namespace android