blob: 70840cb0b5be299e624c7f4ead4dac2ea14222c7 [file] [log] [blame]
Eric Laurent81784c32012-11-19 14:55:58 -08001/*
2**
3** Copyright 2012, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
Alex Ray371eb972012-11-30 11:11:54 -080021#define ATRACE_TAG ATRACE_TAG_AUDIO
Eric Laurent81784c32012-11-19 14:55:58 -080022
Glenn Kasten153b9fe2013-07-15 11:23:36 -070023#include "Configuration.h"
Eric Laurent81784c32012-11-19 14:55:58 -080024#include <math.h>
25#include <fcntl.h>
Glenn Kastenad8510a2015-02-17 16:24:07 -080026#include <linux/futex.h>
Eric Laurent81784c32012-11-19 14:55:58 -080027#include <sys/stat.h>
Glenn Kastenad8510a2015-02-17 16:24:07 -080028#include <sys/syscall.h>
Eric Laurent81784c32012-11-19 14:55:58 -080029#include <cutils/properties.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070030#include <media/AudioParameter.h>
Andy Hungcd044842014-08-07 11:04:34 -070031#include <media/AudioResamplerPublic.h>
Eric Laurent81784c32012-11-19 14:55:58 -080032#include <utils/Log.h>
Alex Ray371eb972012-11-30 11:11:54 -080033#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080034
35#include <private/media/AudioTrackShared.h>
36#include <hardware/audio.h>
37#include <audio_effects/effect_ns.h>
38#include <audio_effects/effect_aec.h>
Andy Hung2ddee192015-12-18 17:34:44 -080039#include <audio_utils/conversion.h>
Eric Laurent81784c32012-11-19 14:55:58 -080040#include <audio_utils/primitives.h>
Andy Hung98ef9782014-03-04 14:46:50 -080041#include <audio_utils/format.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070042#include <audio_utils/minifloat.h>
Eric Laurent81784c32012-11-19 14:55:58 -080043
44// NBAIO implementations
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070045#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080046#include <media/nbaio/AudioStreamOutSink.h>
47#include <media/nbaio/MonoPipe.h>
48#include <media/nbaio/MonoPipeReader.h>
49#include <media/nbaio/Pipe.h>
50#include <media/nbaio/PipeReader.h>
51#include <media/nbaio/SourceAudioBufferProvider.h>
Wei Jia3f273d12015-11-24 09:06:49 -080052#include <mediautils/BatteryNotifier.h>
Eric Laurent81784c32012-11-19 14:55:58 -080053
54#include <powermanager/PowerManager.h>
55
Eric Laurent81784c32012-11-19 14:55:58 -080056#include "AudioFlinger.h"
57#include "AudioMixer.h"
Andy Hungd330ee42015-04-20 13:23:41 -070058#include "BufferProviders.h"
Eric Laurent81784c32012-11-19 14:55:58 -080059#include "FastMixer.h"
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070060#include "FastCapture.h"
Eric Laurent81784c32012-11-19 14:55:58 -080061#include "ServiceUtilities.h"
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -070062#include "mediautils/SchedulingPolicyService.h"
Eric Laurent81784c32012-11-19 14:55:58 -080063
Eric Laurent81784c32012-11-19 14:55:58 -080064#ifdef ADD_BATTERY_DATA
65#include <media/IMediaPlayerService.h>
66#include <media/IMediaDeathNotifier.h>
67#endif
68
Eric Laurent81784c32012-11-19 14:55:58 -080069#ifdef DEBUG_CPU_USAGE
70#include <cpustats/CentralTendencyStatistics.h>
71#include <cpustats/ThreadCpuUsage.h>
72#endif
73
Glenn Kastenc05b8d72016-03-24 09:48:17 -070074#include "AutoPark.h"
75
Eric Laurent81784c32012-11-19 14:55:58 -080076// ----------------------------------------------------------------------------
77
78// Note: the following macro is used for extremely verbose logging message. In
79// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
80// 0; but one side effect of this is to turn all LOGV's as well. Some messages
81// are so verbose that we want to suppress them even when we have ALOG_ASSERT
82// turned on. Do not uncomment the #def below unless you really know what you
83// are doing and want to see all of the extremely verbose messages.
84//#define VERY_VERY_VERBOSE_LOGGING
85#ifdef VERY_VERY_VERBOSE_LOGGING
86#define ALOGVV ALOGV
87#else
88#define ALOGVV(a...) do { } while(0)
89#endif
90
Andy Hung6770c6f2015-04-07 13:43:36 -070091// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -070092#define max(a, b) ((a) > (b) ? (a) : (b))
Andy Hung6770c6f2015-04-07 13:43:36 -070093template <typename T>
94static inline T min(const T& a, const T& b)
95{
96 return a < b ? a : b;
97}
Glenn Kasten49d00ad2014-07-21 11:22:03 -070098
Andy Hungd330ee42015-04-20 13:23:41 -070099#ifndef ARRAY_SIZE
Chih-Hung Hsiehbf291732016-05-17 15:16:07 -0700100#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
Andy Hungd330ee42015-04-20 13:23:41 -0700101#endif
102
Eric Laurent81784c32012-11-19 14:55:58 -0800103namespace android {
104
105// retry counts for buffer fill timeout
106// 50 * ~20msecs = 1 second
107static const int8_t kMaxTrackRetries = 50;
108static const int8_t kMaxTrackStartupRetries = 50;
109// allow less retry attempts on direct output thread.
110// direct outputs can be a scarce resource in audio hardware and should
111// be released as quickly as possible.
112static const int8_t kMaxTrackRetriesDirect = 2;
Eric Laurente93cc032016-05-05 10:15:10 -0700113
Eric Laurent51716182016-02-29 18:00:56 -0800114
Eric Laurent81784c32012-11-19 14:55:58 -0800115
116// don't warn about blocked writes or record buffer overflows more often than this
117static const nsecs_t kWarningThrottleNs = seconds(5);
118
119// RecordThread loop sleep time upon application overrun or audio HAL read error
120static const int kRecordThreadSleepUs = 5000;
121
Eric Laurent10351942014-05-08 18:49:52 -0700122// maximum time to wait in sendConfigEvent_l() for a status to be received
123static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800124
125// minimum sleep time for the mixer thread loop when tracks are active but in underrun
126static const uint32_t kMinThreadSleepTimeUs = 5000;
127// maximum divider applied to the active sleep time in the mixer thread loop
128static const uint32_t kMaxThreadSleepTimeShift = 2;
129
Andy Hung09a50072014-02-27 14:30:47 -0800130// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700131// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800132static const uint32_t kMinNormalSinkBufferSizeMs = 20;
133// maximum normal sink buffer size
134static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800135
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700136// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
137// FIXME This should be based on experimentally observed scheduling jitter
138static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
139
Eric Laurent972a1732013-09-04 09:42:59 -0700140// Offloaded output thread standby delay: allows track transition without going to standby
141static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
142
Eric Laurent51716182016-02-29 18:00:56 -0800143// Direct output thread minimum sleep time in idle or active(underrun) state
144static const nsecs_t kDirectMinSleepTimeUs = 10000;
145
Glenn Kasten1b291842016-07-18 14:55:21 -0700146// The universal constant for ubiquitous 20ms value. The value of 20ms seems to provide a good
147// balance between power consumption and latency, and allows threads to be scheduled reliably
148// by the CFS scheduler.
149// FIXME Express other hardcoded references to 20ms with references to this constant and move
150// it appropriately.
151#define FMS_20 20
Eric Laurent51716182016-02-29 18:00:56 -0800152
Eric Laurent81784c32012-11-19 14:55:58 -0800153// Whether to use fast mixer
154static const enum {
155 FastMixer_Never, // never initialize or use: for debugging only
156 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
157 // normal mixer multiplier is 1
158 FastMixer_Static, // initialize if needed, then use all the time if initialized,
159 // multiplier is calculated based on min & max normal mixer buffer size
160 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
161 // multiplier is calculated based on min & max normal mixer buffer size
162 // FIXME for FastMixer_Dynamic:
163 // Supporting this option will require fixing HALs that can't handle large writes.
164 // For example, one HAL implementation returns an error from a large write,
165 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
166 // We could either fix the HAL implementations, or provide a wrapper that breaks
167 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
168} kUseFastMixer = FastMixer_Static;
169
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700170// Whether to use fast capture
171static const enum {
172 FastCapture_Never, // never initialize or use: for debugging only
173 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
174 FastCapture_Static, // initialize if needed, then use all the time if initialized
175} kUseFastCapture = FastCapture_Static;
176
Eric Laurent81784c32012-11-19 14:55:58 -0800177// Priorities for requestPriority
178static const int kPriorityAudioApp = 2;
179static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700180static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800181
Glenn Kastenea38ee72016-04-18 11:08:01 -0700182// IAudioFlinger::createTrack() has an in/out parameter 'pFrameCount' for the total size of the
183// track buffer in shared memory. Zero on input means to use a default value. For fast tracks,
184// AudioFlinger derives the default from HAL buffer size and 'fast track multiplier'.
Glenn Kasten03490092014-05-27 12:30:54 -0700185
186// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800187static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800188
Glenn Kasten03490092014-05-27 12:30:54 -0700189// The minimum and maximum allowed values
190static const int kFastTrackMultiplierMin = 1;
191static const int kFastTrackMultiplierMax = 2;
192
193// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
194static int sFastTrackMultiplier = kFastTrackMultiplier;
195
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700196// See Thread::readOnlyHeap().
197// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
198// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
199// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Glenn Kasten9f81de32014-07-27 15:02:23 -0700200static const size_t kRecordThreadReadOnlyHeapSize = 0x2000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700201
Eric Laurent81784c32012-11-19 14:55:58 -0800202// ----------------------------------------------------------------------------
203
Glenn Kasten03490092014-05-27 12:30:54 -0700204static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
205
206static void sFastTrackMultiplierInit()
207{
208 char value[PROPERTY_VALUE_MAX];
209 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
210 char *endptr;
211 unsigned long ul = strtoul(value, &endptr, 0);
212 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
213 sFastTrackMultiplier = (int) ul;
214 }
215 }
216}
217
218// ----------------------------------------------------------------------------
219
Eric Laurent81784c32012-11-19 14:55:58 -0800220#ifdef ADD_BATTERY_DATA
221// To collect the amplifier usage
222static void addBatteryData(uint32_t params) {
223 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
224 if (service == NULL) {
225 // it already logged
226 return;
227 }
228
229 service->addBatteryData(params);
230}
231#endif
232
Andy Hung3f0c9022016-01-15 17:49:46 -0800233// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
234struct {
235 // call when you acquire a partial wakelock
236 void acquire(const sp<IBinder> &wakeLockToken) {
237 pthread_mutex_lock(&mLock);
238 if (wakeLockToken.get() == nullptr) {
239 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
240 } else {
241 if (mCount == 0) {
242 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
243 }
244 ++mCount;
245 }
246 pthread_mutex_unlock(&mLock);
247 }
248
249 // call when you release a partial wakelock.
250 void release(const sp<IBinder> &wakeLockToken) {
251 if (wakeLockToken.get() == nullptr) {
252 return;
253 }
254 pthread_mutex_lock(&mLock);
255 if (--mCount < 0) {
256 ALOGE("negative wakelock count");
257 mCount = 0;
258 }
259 pthread_mutex_unlock(&mLock);
260 }
261
262 // retrieves the boottime timebase offset from monotonic.
263 int64_t getBoottimeOffset() {
264 pthread_mutex_lock(&mLock);
265 int64_t boottimeOffset = mBoottimeOffset;
266 pthread_mutex_unlock(&mLock);
267 return boottimeOffset;
268 }
269
270 // Adjusts the timebase offset between TIMEBASE_MONOTONIC
271 // and the selected timebase.
272 // Currently only TIMEBASE_BOOTTIME is allowed.
273 //
274 // This only needs to be called upon acquiring the first partial wakelock
275 // after all other partial wakelocks are released.
276 //
277 // We do an empirical measurement of the offset rather than parsing
278 // /proc/timer_list since the latter is not a formal kernel ABI.
279 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
280 int clockbase;
281 switch (timebase) {
282 case ExtendedTimestamp::TIMEBASE_BOOTTIME:
283 clockbase = SYSTEM_TIME_BOOTTIME;
284 break;
285 default:
286 LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
287 break;
288 }
289 // try three times to get the clock offset, choose the one
290 // with the minimum gap in measurements.
291 const int tries = 3;
292 nsecs_t bestGap, measured;
293 for (int i = 0; i < tries; ++i) {
294 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
295 const nsecs_t tbase = systemTime(clockbase);
296 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
297 const nsecs_t gap = tmono2 - tmono;
298 if (i == 0 || gap < bestGap) {
299 bestGap = gap;
300 measured = tbase - ((tmono + tmono2) >> 1);
301 }
302 }
303
304 // to avoid micro-adjusting, we don't change the timebase
305 // unless it is significantly different.
306 //
307 // Assumption: It probably takes more than toleranceNs to
308 // suspend and resume the device.
309 static int64_t toleranceNs = 10000; // 10 us
310 if (llabs(*offset - measured) > toleranceNs) {
311 ALOGV("Adjusting timebase offset old: %lld new: %lld",
312 (long long)*offset, (long long)measured);
313 *offset = measured;
314 }
315 }
316
317 pthread_mutex_t mLock;
318 int32_t mCount;
319 int64_t mBoottimeOffset;
320} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
Eric Laurent81784c32012-11-19 14:55:58 -0800321
322// ----------------------------------------------------------------------------
323// CPU Stats
324// ----------------------------------------------------------------------------
325
326class CpuStats {
327public:
328 CpuStats();
329 void sample(const String8 &title);
330#ifdef DEBUG_CPU_USAGE
331private:
332 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
333 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
334
335 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
336
337 int mCpuNum; // thread's current CPU number
338 int mCpukHz; // frequency of thread's current CPU in kHz
339#endif
340};
341
342CpuStats::CpuStats()
343#ifdef DEBUG_CPU_USAGE
344 : mCpuNum(-1), mCpukHz(-1)
345#endif
346{
347}
348
Glenn Kasten0f11b512014-01-31 16:18:54 -0800349void CpuStats::sample(const String8 &title
350#ifndef DEBUG_CPU_USAGE
351 __unused
352#endif
353 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800354#ifdef DEBUG_CPU_USAGE
355 // get current thread's delta CPU time in wall clock ns
356 double wcNs;
357 bool valid = mCpuUsage.sampleAndEnable(wcNs);
358
359 // record sample for wall clock statistics
360 if (valid) {
361 mWcStats.sample(wcNs);
362 }
363
364 // get the current CPU number
365 int cpuNum = sched_getcpu();
366
367 // get the current CPU frequency in kHz
368 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
369
370 // check if either CPU number or frequency changed
371 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
372 mCpuNum = cpuNum;
373 mCpukHz = cpukHz;
374 // ignore sample for purposes of cycles
375 valid = false;
376 }
377
378 // if no change in CPU number or frequency, then record sample for cycle statistics
379 if (valid && mCpukHz > 0) {
380 double cycles = wcNs * cpukHz * 0.000001;
381 mHzStats.sample(cycles);
382 }
383
384 unsigned n = mWcStats.n();
385 // mCpuUsage.elapsed() is expensive, so don't call it every loop
386 if ((n & 127) == 1) {
387 long long elapsed = mCpuUsage.elapsed();
388 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
389 double perLoop = elapsed / (double) n;
390 double perLoop100 = perLoop * 0.01;
391 double perLoop1k = perLoop * 0.001;
392 double mean = mWcStats.mean();
393 double stddev = mWcStats.stddev();
394 double minimum = mWcStats.minimum();
395 double maximum = mWcStats.maximum();
396 double meanCycles = mHzStats.mean();
397 double stddevCycles = mHzStats.stddev();
398 double minCycles = mHzStats.minimum();
399 double maxCycles = mHzStats.maximum();
400 mCpuUsage.resetElapsed();
401 mWcStats.reset();
402 mHzStats.reset();
403 ALOGD("CPU usage for %s over past %.1f secs\n"
404 " (%u mixer loops at %.1f mean ms per loop):\n"
405 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
406 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
407 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
408 title.string(),
409 elapsed * .000000001, n, perLoop * .000001,
410 mean * .001,
411 stddev * .001,
412 minimum * .001,
413 maximum * .001,
414 mean / perLoop100,
415 stddev / perLoop100,
416 minimum / perLoop100,
417 maximum / perLoop100,
418 meanCycles / perLoop1k,
419 stddevCycles / perLoop1k,
420 minCycles / perLoop1k,
421 maxCycles / perLoop1k);
422
423 }
424 }
425#endif
426};
427
428// ----------------------------------------------------------------------------
429// ThreadBase
430// ----------------------------------------------------------------------------
431
Glenn Kasten97b7b752014-09-28 13:04:24 -0700432// static
433const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
434{
435 switch (type) {
436 case MIXER:
437 return "MIXER";
438 case DIRECT:
439 return "DIRECT";
440 case DUPLICATING:
441 return "DUPLICATING";
442 case RECORD:
443 return "RECORD";
444 case OFFLOAD:
445 return "OFFLOAD";
446 default:
447 return "unknown";
448 }
449}
450
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800451String8 devicesToString(audio_devices_t devices)
452{
453 static const struct mapping {
454 audio_devices_t mDevices;
455 const char * mString;
456 } mappingsOut[] = {
Glenn Kasten818da522015-12-02 13:53:26 -0800457 {AUDIO_DEVICE_OUT_EARPIECE, "EARPIECE"},
458 {AUDIO_DEVICE_OUT_SPEAKER, "SPEAKER"},
459 {AUDIO_DEVICE_OUT_WIRED_HEADSET, "WIRED_HEADSET"},
460 {AUDIO_DEVICE_OUT_WIRED_HEADPHONE, "WIRED_HEADPHONE"},
461 {AUDIO_DEVICE_OUT_BLUETOOTH_SCO, "BLUETOOTH_SCO"},
462 {AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET, "BLUETOOTH_SCO_HEADSET"},
463 {AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT, "BLUETOOTH_SCO_CARKIT"},
464 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, "BLUETOOTH_A2DP"},
465 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,"BLUETOOTH_A2DP_HEADPHONES"},
466 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER, "BLUETOOTH_A2DP_SPEAKER"},
467 {AUDIO_DEVICE_OUT_AUX_DIGITAL, "AUX_DIGITAL"},
468 {AUDIO_DEVICE_OUT_HDMI, "HDMI"},
469 {AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET,"ANLG_DOCK_HEADSET"},
470 {AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET,"DGTL_DOCK_HEADSET"},
471 {AUDIO_DEVICE_OUT_USB_ACCESSORY, "USB_ACCESSORY"},
472 {AUDIO_DEVICE_OUT_USB_DEVICE, "USB_DEVICE"},
473 {AUDIO_DEVICE_OUT_TELEPHONY_TX, "TELEPHONY_TX"},
474 {AUDIO_DEVICE_OUT_LINE, "LINE"},
475 {AUDIO_DEVICE_OUT_HDMI_ARC, "HDMI_ARC"},
476 {AUDIO_DEVICE_OUT_SPDIF, "SPDIF"},
477 {AUDIO_DEVICE_OUT_FM, "FM"},
478 {AUDIO_DEVICE_OUT_AUX_LINE, "AUX_LINE"},
479 {AUDIO_DEVICE_OUT_SPEAKER_SAFE, "SPEAKER_SAFE"},
480 {AUDIO_DEVICE_OUT_IP, "IP"},
Eric Laurent58545be2016-02-22 18:54:20 -0800481 {AUDIO_DEVICE_OUT_BUS, "BUS"},
Glenn Kasten818da522015-12-02 13:53:26 -0800482 {AUDIO_DEVICE_NONE, "NONE"}, // must be last
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800483 }, mappingsIn[] = {
Glenn Kasten818da522015-12-02 13:53:26 -0800484 {AUDIO_DEVICE_IN_COMMUNICATION, "COMMUNICATION"},
485 {AUDIO_DEVICE_IN_AMBIENT, "AMBIENT"},
486 {AUDIO_DEVICE_IN_BUILTIN_MIC, "BUILTIN_MIC"},
487 {AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET, "BLUETOOTH_SCO_HEADSET"},
488 {AUDIO_DEVICE_IN_WIRED_HEADSET, "WIRED_HEADSET"},
489 {AUDIO_DEVICE_IN_AUX_DIGITAL, "AUX_DIGITAL"},
490 {AUDIO_DEVICE_IN_VOICE_CALL, "VOICE_CALL"},
491 {AUDIO_DEVICE_IN_TELEPHONY_RX, "TELEPHONY_RX"},
492 {AUDIO_DEVICE_IN_BACK_MIC, "BACK_MIC"},
493 {AUDIO_DEVICE_IN_REMOTE_SUBMIX, "REMOTE_SUBMIX"},
494 {AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET, "ANLG_DOCK_HEADSET"},
495 {AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET, "DGTL_DOCK_HEADSET"},
496 {AUDIO_DEVICE_IN_USB_ACCESSORY, "USB_ACCESSORY"},
497 {AUDIO_DEVICE_IN_USB_DEVICE, "USB_DEVICE"},
498 {AUDIO_DEVICE_IN_FM_TUNER, "FM_TUNER"},
499 {AUDIO_DEVICE_IN_TV_TUNER, "TV_TUNER"},
500 {AUDIO_DEVICE_IN_LINE, "LINE"},
501 {AUDIO_DEVICE_IN_SPDIF, "SPDIF"},
502 {AUDIO_DEVICE_IN_BLUETOOTH_A2DP, "BLUETOOTH_A2DP"},
503 {AUDIO_DEVICE_IN_LOOPBACK, "LOOPBACK"},
504 {AUDIO_DEVICE_IN_IP, "IP"},
Eric Laurent58545be2016-02-22 18:54:20 -0800505 {AUDIO_DEVICE_IN_BUS, "BUS"},
Glenn Kasten818da522015-12-02 13:53:26 -0800506 {AUDIO_DEVICE_NONE, "NONE"}, // must be last
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800507 };
508 String8 result;
509 audio_devices_t allDevices = AUDIO_DEVICE_NONE;
510 const mapping *entry;
511 if (devices & AUDIO_DEVICE_BIT_IN) {
512 devices &= ~AUDIO_DEVICE_BIT_IN;
513 entry = mappingsIn;
514 } else {
515 entry = mappingsOut;
516 }
517 for ( ; entry->mDevices != AUDIO_DEVICE_NONE; entry++) {
518 allDevices = (audio_devices_t) (allDevices | entry->mDevices);
519 if (devices & entry->mDevices) {
520 if (!result.isEmpty()) {
521 result.append("|");
522 }
523 result.append(entry->mString);
524 }
525 }
526 if (devices & ~allDevices) {
527 if (!result.isEmpty()) {
528 result.append("|");
529 }
530 result.appendFormat("0x%X", devices & ~allDevices);
531 }
532 if (result.isEmpty()) {
533 result.append(entry->mString);
534 }
535 return result;
536}
537
538String8 inputFlagsToString(audio_input_flags_t flags)
539{
540 static const struct mapping {
541 audio_input_flags_t mFlag;
542 const char * mString;
543 } mappings[] = {
Glenn Kasten818da522015-12-02 13:53:26 -0800544 {AUDIO_INPUT_FLAG_FAST, "FAST"},
545 {AUDIO_INPUT_FLAG_HW_HOTWORD, "HW_HOTWORD"},
546 {AUDIO_INPUT_FLAG_RAW, "RAW"},
547 {AUDIO_INPUT_FLAG_SYNC, "SYNC"},
548 {AUDIO_INPUT_FLAG_NONE, "NONE"}, // must be last
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800549 };
550 String8 result;
551 audio_input_flags_t allFlags = AUDIO_INPUT_FLAG_NONE;
552 const mapping *entry;
553 for (entry = mappings; entry->mFlag != AUDIO_INPUT_FLAG_NONE; entry++) {
554 allFlags = (audio_input_flags_t) (allFlags | entry->mFlag);
555 if (flags & entry->mFlag) {
556 if (!result.isEmpty()) {
557 result.append("|");
558 }
559 result.append(entry->mString);
560 }
561 }
562 if (flags & ~allFlags) {
563 if (!result.isEmpty()) {
564 result.append("|");
565 }
566 result.appendFormat("0x%X", flags & ~allFlags);
567 }
568 if (result.isEmpty()) {
569 result.append(entry->mString);
570 }
571 return result;
572}
573
574String8 outputFlagsToString(audio_output_flags_t flags)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700575{
576 static const struct mapping {
577 audio_output_flags_t mFlag;
578 const char * mString;
579 } mappings[] = {
Glenn Kasten818da522015-12-02 13:53:26 -0800580 {AUDIO_OUTPUT_FLAG_DIRECT, "DIRECT"},
581 {AUDIO_OUTPUT_FLAG_PRIMARY, "PRIMARY"},
582 {AUDIO_OUTPUT_FLAG_FAST, "FAST"},
583 {AUDIO_OUTPUT_FLAG_DEEP_BUFFER, "DEEP_BUFFER"},
584 {AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,"COMPRESS_OFFLOAD"},
585 {AUDIO_OUTPUT_FLAG_NON_BLOCKING, "NON_BLOCKING"},
586 {AUDIO_OUTPUT_FLAG_HW_AV_SYNC, "HW_AV_SYNC"},
587 {AUDIO_OUTPUT_FLAG_RAW, "RAW"},
588 {AUDIO_OUTPUT_FLAG_SYNC, "SYNC"},
589 {AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO, "IEC958_NONAUDIO"},
590 {AUDIO_OUTPUT_FLAG_NONE, "NONE"}, // must be last
Glenn Kasten97b7b752014-09-28 13:04:24 -0700591 };
592 String8 result;
593 audio_output_flags_t allFlags = AUDIO_OUTPUT_FLAG_NONE;
594 const mapping *entry;
595 for (entry = mappings; entry->mFlag != AUDIO_OUTPUT_FLAG_NONE; entry++) {
596 allFlags = (audio_output_flags_t) (allFlags | entry->mFlag);
597 if (flags & entry->mFlag) {
598 if (!result.isEmpty()) {
599 result.append("|");
600 }
601 result.append(entry->mString);
602 }
603 }
604 if (flags & ~allFlags) {
605 if (!result.isEmpty()) {
606 result.append("|");
607 }
608 result.appendFormat("0x%X", flags & ~allFlags);
609 }
610 if (result.isEmpty()) {
611 result.append(entry->mString);
612 }
613 return result;
614}
615
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800616const char *sourceToString(audio_source_t source)
617{
618 switch (source) {
619 case AUDIO_SOURCE_DEFAULT: return "default";
620 case AUDIO_SOURCE_MIC: return "mic";
621 case AUDIO_SOURCE_VOICE_UPLINK: return "voice uplink";
622 case AUDIO_SOURCE_VOICE_DOWNLINK: return "voice downlink";
623 case AUDIO_SOURCE_VOICE_CALL: return "voice call";
624 case AUDIO_SOURCE_CAMCORDER: return "camcorder";
625 case AUDIO_SOURCE_VOICE_RECOGNITION: return "voice recognition";
626 case AUDIO_SOURCE_VOICE_COMMUNICATION: return "voice communication";
627 case AUDIO_SOURCE_REMOTE_SUBMIX: return "remote submix";
rago8a397d52015-12-02 11:27:57 -0800628 case AUDIO_SOURCE_UNPROCESSED: return "unprocessed";
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800629 case AUDIO_SOURCE_FM_TUNER: return "FM tuner";
630 case AUDIO_SOURCE_HOTWORD: return "hotword";
631 default: return "unknown";
632 }
633}
634
Eric Laurent81784c32012-11-19 14:55:58 -0800635AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -0700636 audio_devices_t outDevice, audio_devices_t inDevice, type_t type, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -0800637 : Thread(false /*canCallJava*/),
638 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700639 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700640 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800641 // are set by PlaybackThread::readOutputParameters_l() or
642 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700643 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800644 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700645 mPrevOutDevice(AUDIO_DEVICE_NONE), mPrevInDevice(AUDIO_DEVICE_NONE),
646 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800647 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700648 mDeathRecipient(new PMDeathRecipient(this)),
Wei Jia3f273d12015-11-24 09:06:49 -0800649 mSystemReady(systemReady),
650 mNotifiedBatteryStart(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800651{
Eric Laurent296fb132015-05-01 11:38:42 -0700652 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800653}
654
655AudioFlinger::ThreadBase::~ThreadBase()
656{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700657 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700658 mConfigEvents.clear();
659
Eric Laurent81784c32012-11-19 14:55:58 -0800660 // do not lock the mutex in destructor
661 releaseWakeLock_l();
662 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800663 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800664 binder->unlinkToDeath(mDeathRecipient);
665 }
666}
667
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700668status_t AudioFlinger::ThreadBase::readyToRun()
669{
670 status_t status = initCheck();
671 if (status == NO_ERROR) {
672 ALOGI("AudioFlinger's thread %p ready to run", this);
673 } else {
674 ALOGE("No working audio driver found.");
675 }
676 return status;
677}
678
Eric Laurent81784c32012-11-19 14:55:58 -0800679void AudioFlinger::ThreadBase::exit()
680{
681 ALOGV("ThreadBase::exit");
682 // do any cleanup required for exit to succeed
683 preExit();
684 {
685 // This lock prevents the following race in thread (uniprocessor for illustration):
686 // if (!exitPending()) {
687 // // context switch from here to exit()
688 // // exit() calls requestExit(), what exitPending() observes
689 // // exit() calls signal(), which is dropped since no waiters
690 // // context switch back from exit() to here
691 // mWaitWorkCV.wait(...);
692 // // now thread is hung
693 // }
694 AutoMutex lock(mLock);
695 requestExit();
696 mWaitWorkCV.broadcast();
697 }
698 // When Thread::requestExitAndWait is made virtual and this method is renamed to
699 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
700 requestExitAndWait();
701}
702
703status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
704{
Eric Laurent81784c32012-11-19 14:55:58 -0800705 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
706 Mutex::Autolock _l(mLock);
707
Eric Laurent10351942014-05-08 18:49:52 -0700708 return sendSetParameterConfigEvent_l(keyValuePairs);
709}
710
711// sendConfigEvent_l() must be called with ThreadBase::mLock held
712// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
713status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
714{
715 status_t status = NO_ERROR;
716
Eric Laurent72e3f392015-05-20 14:43:50 -0700717 if (event->mRequiresSystemReady && !mSystemReady) {
718 event->mWaitStatus = false;
719 mPendingConfigEvents.add(event);
720 return status;
721 }
Eric Laurent10351942014-05-08 18:49:52 -0700722 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700723 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800724 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700725 mLock.unlock();
726 {
727 Mutex::Autolock _l(event->mLock);
728 while (event->mWaitStatus) {
729 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
730 event->mStatus = TIMED_OUT;
731 event->mWaitStatus = false;
732 }
733 }
734 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800735 }
Eric Laurent10351942014-05-08 18:49:52 -0700736 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800737 return status;
738}
739
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700740void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800741{
742 Mutex::Autolock _l(mLock);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700743 sendIoConfigEvent_l(event, pid);
Eric Laurent81784c32012-11-19 14:55:58 -0800744}
745
746// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700747void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800748{
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700749 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid);
Eric Laurent10351942014-05-08 18:49:52 -0700750 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800751}
752
Eric Laurent72e3f392015-05-20 14:43:50 -0700753void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio)
754{
755 Mutex::Autolock _l(mLock);
756 sendPrioConfigEvent_l(pid, tid, prio);
757}
758
Eric Laurent81784c32012-11-19 14:55:58 -0800759// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
760void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
761{
Eric Laurent10351942014-05-08 18:49:52 -0700762 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio);
763 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800764}
765
Eric Laurent10351942014-05-08 18:49:52 -0700766// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
767status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800768{
Andy Hung2ddee192015-12-18 17:34:44 -0800769 sp<ConfigEvent> configEvent;
770 AudioParameter param(keyValuePair);
771 int value;
772 if (param.getInt(String8(AUDIO_PARAMETER_MONO_OUTPUT), value) == NO_ERROR) {
773 setMasterMono_l(value != 0);
774 if (param.size() == 1) {
775 return NO_ERROR; // should be a solo parameter - we don't pass down
776 }
777 param.remove(String8(AUDIO_PARAMETER_MONO_OUTPUT));
778 configEvent = new SetParameterConfigEvent(param.toString());
779 } else {
780 configEvent = new SetParameterConfigEvent(keyValuePair);
781 }
Eric Laurent10351942014-05-08 18:49:52 -0700782 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700783}
784
Eric Laurent1c333e22014-05-20 10:48:17 -0700785status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
786 const struct audio_patch *patch,
787 audio_patch_handle_t *handle)
788{
789 Mutex::Autolock _l(mLock);
790 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
791 status_t status = sendConfigEvent_l(configEvent);
792 if (status == NO_ERROR) {
793 CreateAudioPatchConfigEventData *data =
794 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
795 *handle = data->mHandle;
796 }
797 return status;
798}
799
800status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
801 const audio_patch_handle_t handle)
802{
803 Mutex::Autolock _l(mLock);
804 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
805 return sendConfigEvent_l(configEvent);
806}
807
808
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700809// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700810void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700811{
Eric Laurent10351942014-05-08 18:49:52 -0700812 bool configChanged = false;
813
Eric Laurent81784c32012-11-19 14:55:58 -0800814 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700815 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700816 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800817 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700818 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700819 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700820 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
821 // FIXME Need to understand why this has to be done asynchronously
822 int err = requestPriority(data->mPid, data->mTid, data->mPrio,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700823 true /*asynchronous*/);
824 if (err != 0) {
825 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700826 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700827 }
828 } break;
829 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700830 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700831 ioConfigChanged(data->mEvent, data->mPid);
Eric Laurent10351942014-05-08 18:49:52 -0700832 } break;
833 case CFG_EVENT_SET_PARAMETER: {
834 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
835 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
836 configChanged = true;
Glenn Kastend5418eb2013-08-14 13:11:06 -0700837 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700838 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700839 case CFG_EVENT_CREATE_AUDIO_PATCH: {
840 CreateAudioPatchConfigEventData *data =
841 (CreateAudioPatchConfigEventData *)event->mData.get();
842 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
843 } break;
844 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
845 ReleaseAudioPatchConfigEventData *data =
846 (ReleaseAudioPatchConfigEventData *)event->mData.get();
847 event->mStatus = releaseAudioPatch_l(data->mHandle);
848 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700849 default:
Eric Laurent10351942014-05-08 18:49:52 -0700850 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700851 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800852 }
Eric Laurent10351942014-05-08 18:49:52 -0700853 {
854 Mutex::Autolock _l(event->mLock);
855 if (event->mWaitStatus) {
856 event->mWaitStatus = false;
857 event->mCond.signal();
858 }
859 }
860 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
861 }
862
863 if (configChanged) {
864 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800865 }
Eric Laurent81784c32012-11-19 14:55:58 -0800866}
867
Marco Nelissenb2208842014-02-07 14:00:50 -0800868String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
869 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700870 const audio_channel_representation_t representation =
871 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700872
873 switch (representation) {
874 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
875 if (output) {
876 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
877 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
878 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
879 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
880 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
881 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
882 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
883 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
884 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
885 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
886 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
887 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
888 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
889 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
890 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
891 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
892 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
893 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
894 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
895 } else {
896 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
897 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
898 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
899 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
900 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
901 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
902 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
903 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
904 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
905 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
906 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
907 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
908 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
909 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
910 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
911 }
912 const int len = s.length();
913 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -0700914 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -0700915 s.unlockBuffer(len - 2); // remove trailing ", "
916 }
917 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800918 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700919 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
920 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
921 return s;
922 default:
923 s.appendFormat("unknown mask, representation:%d bits:%#x",
924 representation, audio_channel_mask_get_bits(mask));
925 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800926 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800927}
928
Glenn Kasten0f11b512014-01-31 16:18:54 -0800929void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800930{
931 const size_t SIZE = 256;
932 char buffer[SIZE];
933 String8 result;
934
935 bool locked = AudioFlinger::dumpTryLock(mLock);
936 if (!locked) {
Glenn Kasten97b7b752014-09-28 13:04:24 -0700937 dprintf(fd, "thread %p may be deadlocked\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -0800938 }
939
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800940 dprintf(fd, " Thread name: %s\n", mThreadName);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700941 dprintf(fd, " I/O handle: %d\n", mId);
942 dprintf(fd, " TID: %d\n", getTid());
943 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700944 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700945 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700946 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat));
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700947 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700948 dprintf(fd, " Channel count: %u\n", mChannelCount);
949 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800950 channelMaskToString(mChannelMask, mType != RECORD).string());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700951 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat));
952 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700953 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800954 size_t numConfig = mConfigEvents.size();
955 if (numConfig) {
956 for (size_t i = 0; i < numConfig; i++) {
957 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700958 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800959 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700960 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800961 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700962 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800963 }
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800964 dprintf(fd, " Output device: %#x (%s)\n", mOutDevice, devicesToString(mOutDevice).string());
965 dprintf(fd, " Input device: %#x (%s)\n", mInDevice, devicesToString(mInDevice).string());
966 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, sourceToString(mAudioSource));
Eric Laurent81784c32012-11-19 14:55:58 -0800967
968 if (locked) {
969 mLock.unlock();
970 }
971}
972
973void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
974{
975 const size_t SIZE = 256;
976 char buffer[SIZE];
977 String8 result;
978
Marco Nelissenb2208842014-02-07 14:00:50 -0800979 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000980 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800981 write(fd, buffer, strlen(buffer));
982
Marco Nelissenb2208842014-02-07 14:00:50 -0800983 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800984 sp<EffectChain> chain = mEffectChains[i];
985 if (chain != 0) {
986 chain->dump(fd, args);
987 }
988 }
989}
990
Marco Nelissene14a5d62013-10-03 08:51:24 -0700991void AudioFlinger::ThreadBase::acquireWakeLock(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800992{
993 Mutex::Autolock _l(mLock);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700994 acquireWakeLock_l(uid);
Eric Laurent81784c32012-11-19 14:55:58 -0800995}
996
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100997String16 AudioFlinger::ThreadBase::getWakeLockTag()
998{
999 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -08001000 case MIXER:
1001 return String16("AudioMix");
1002 case DIRECT:
1003 return String16("AudioDirectOut");
1004 case DUPLICATING:
1005 return String16("AudioDup");
1006 case RECORD:
1007 return String16("AudioIn");
1008 case OFFLOAD:
1009 return String16("AudioOffload");
1010 default:
1011 ALOG_ASSERT(false);
1012 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001013 }
1014}
1015
Marco Nelissene14a5d62013-10-03 08:51:24 -07001016void AudioFlinger::ThreadBase::acquireWakeLock_l(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -08001017{
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001018 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001019 if (mPowerManager != 0) {
1020 sp<IBinder> binder = new BBinder();
Marco Nelissene14a5d62013-10-03 08:51:24 -07001021 status_t status;
1022 if (uid >= 0) {
Eric Laurent547789d2013-10-04 11:46:55 -07001023 status = mPowerManager->acquireWakeLockWithUid(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -07001024 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001025 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -07001026 String16("audioserver"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -07001027 uid,
1028 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -07001029 } else {
Eric Laurent547789d2013-10-04 11:46:55 -07001030 status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -07001031 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001032 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -07001033 String16("audioserver"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -07001034 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -07001035 }
Eric Laurent81784c32012-11-19 14:55:58 -08001036 if (status == NO_ERROR) {
1037 mWakeLockToken = binder;
1038 }
Glenn Kastend7dca052015-03-05 16:05:54 -08001039 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -08001040 }
Wei Jia3f273d12015-11-24 09:06:49 -08001041
1042 if (!mNotifiedBatteryStart) {
1043 BatteryNotifier::getInstance().noteStartAudio();
1044 mNotifiedBatteryStart = true;
1045 }
Andy Hung3f0c9022016-01-15 17:49:46 -08001046 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -08001047 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
1048 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -08001049}
1050
1051void AudioFlinger::ThreadBase::releaseWakeLock()
1052{
1053 Mutex::Autolock _l(mLock);
1054 releaseWakeLock_l();
1055}
1056
1057void AudioFlinger::ThreadBase::releaseWakeLock_l()
1058{
Andy Hung3f0c9022016-01-15 17:49:46 -08001059 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -08001060 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001061 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001062 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -07001063 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
1064 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -08001065 }
1066 mWakeLockToken.clear();
1067 }
Wei Jia3f273d12015-11-24 09:06:49 -08001068
1069 if (mNotifiedBatteryStart) {
1070 BatteryNotifier::getInstance().noteStopAudio();
1071 mNotifiedBatteryStart = false;
1072 }
Eric Laurent81784c32012-11-19 14:55:58 -08001073}
1074
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001075void AudioFlinger::ThreadBase::updateWakeLockUids(const SortedVector<int> &uids) {
1076 Mutex::Autolock _l(mLock);
1077 updateWakeLockUids_l(uids);
1078}
1079
1080void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -07001081 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001082 // use checkService() to avoid blocking if power service is not up yet
1083 sp<IBinder> binder =
1084 defaultServiceManager()->checkService(String16("power"));
1085 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001086 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001087 } else {
1088 mPowerManager = interface_cast<IPowerManager>(binder);
1089 binder->linkToDeath(mDeathRecipient);
1090 }
1091 }
1092}
1093
1094void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<int> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001095 getPowerManager_l();
Andy Hung438e7572015-12-14 15:51:17 -08001096 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
1097 if (mSystemReady) {
1098 ALOGE("no wake lock to update, but system ready!");
1099 } else {
1100 ALOGW("no wake lock to update, system not ready yet");
1101 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001102 return;
1103 }
1104 if (mPowerManager != 0) {
1105 sp<IBinder> binder = new BBinder();
1106 status_t status;
Glenn Kasten3abc2de2014-09-05 16:45:52 -07001107 status = mPowerManager->updateWakeLockUids(mWakeLockToken, uids.size(), uids.array(),
1108 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent4d231dc2016-03-11 18:38:23 -08001109 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001110 }
1111}
1112
Eric Laurent81784c32012-11-19 14:55:58 -08001113void AudioFlinger::ThreadBase::clearPowerManager()
1114{
1115 Mutex::Autolock _l(mLock);
1116 releaseWakeLock_l();
1117 mPowerManager.clear();
1118}
1119
Glenn Kasten0f11b512014-01-31 16:18:54 -08001120void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001121{
1122 sp<ThreadBase> thread = mThread.promote();
1123 if (thread != 0) {
1124 thread->clearPowerManager();
1125 }
1126 ALOGW("power manager service died !!!");
1127}
1128
1129void AudioFlinger::ThreadBase::setEffectSuspended(
Glenn Kastend848eb42016-03-08 13:42:11 -08001130 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001131{
1132 Mutex::Autolock _l(mLock);
1133 setEffectSuspended_l(type, suspend, sessionId);
1134}
1135
1136void AudioFlinger::ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001137 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001138{
1139 sp<EffectChain> chain = getEffectChain_l(sessionId);
1140 if (chain != 0) {
1141 if (type != NULL) {
1142 chain->setEffectSuspended_l(type, suspend);
1143 } else {
1144 chain->setEffectSuspendedAll_l(suspend);
1145 }
1146 }
1147
1148 updateSuspendedSessions_l(type, suspend, sessionId);
1149}
1150
1151void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1152{
1153 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1154 if (index < 0) {
1155 return;
1156 }
1157
1158 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1159 mSuspendedSessions.valueAt(index);
1160
1161 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001162 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001163 for (int j = 0; j < desc->mRefCount; j++) {
1164 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1165 chain->setEffectSuspendedAll_l(true);
1166 } else {
1167 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1168 desc->mType.timeLow);
1169 chain->setEffectSuspended_l(&desc->mType, true);
1170 }
1171 }
1172 }
1173}
1174
1175void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1176 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001177 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001178{
1179 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1180
1181 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1182
1183 if (suspend) {
1184 if (index >= 0) {
1185 sessionEffects = mSuspendedSessions.valueAt(index);
1186 } else {
1187 mSuspendedSessions.add(sessionId, sessionEffects);
1188 }
1189 } else {
1190 if (index < 0) {
1191 return;
1192 }
1193 sessionEffects = mSuspendedSessions.valueAt(index);
1194 }
1195
1196
1197 int key = EffectChain::kKeyForSuspendAll;
1198 if (type != NULL) {
1199 key = type->timeLow;
1200 }
1201 index = sessionEffects.indexOfKey(key);
1202
1203 sp<SuspendedSessionDesc> desc;
1204 if (suspend) {
1205 if (index >= 0) {
1206 desc = sessionEffects.valueAt(index);
1207 } else {
1208 desc = new SuspendedSessionDesc();
1209 if (type != NULL) {
1210 desc->mType = *type;
1211 }
1212 sessionEffects.add(key, desc);
1213 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1214 }
1215 desc->mRefCount++;
1216 } else {
1217 if (index < 0) {
1218 return;
1219 }
1220 desc = sessionEffects.valueAt(index);
1221 if (--desc->mRefCount == 0) {
1222 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1223 sessionEffects.removeItemsAt(index);
1224 if (sessionEffects.isEmpty()) {
1225 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1226 sessionId);
1227 mSuspendedSessions.removeItem(sessionId);
1228 }
1229 }
1230 }
1231 if (!sessionEffects.isEmpty()) {
1232 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1233 }
1234}
1235
1236void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1237 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001238 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001239{
1240 Mutex::Autolock _l(mLock);
1241 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1242}
1243
1244void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1245 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001246 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001247{
1248 if (mType != RECORD) {
1249 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1250 // another session. This gives the priority to well behaved effect control panels
1251 // and applications not using global effects.
1252 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1253 // global effects
1254 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1255 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1256 }
1257 }
1258
1259 sp<EffectChain> chain = getEffectChain_l(sessionId);
1260 if (chain != 0) {
1261 chain->checkSuspendOnEffectEnabled(effect, enabled);
1262 }
1263}
1264
Eric Laurent4c415062016-06-17 16:14:16 -07001265// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1266status_t AudioFlinger::RecordThread::checkEffectCompatibility_l(
1267 const effect_descriptor_t *desc, audio_session_t sessionId)
1268{
1269 // No global effect sessions on record threads
1270 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1271 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1272 desc->name, mThreadName);
1273 return BAD_VALUE;
1274 }
1275 // only pre processing effects on record thread
1276 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1277 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1278 desc->name, mThreadName);
1279 return BAD_VALUE;
1280 }
1281 audio_input_flags_t flags = mInput->flags;
1282 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1283 if (flags & AUDIO_INPUT_FLAG_RAW) {
1284 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1285 desc->name, mThreadName);
1286 return BAD_VALUE;
1287 }
1288 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1289 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1290 desc->name, mThreadName);
1291 return BAD_VALUE;
1292 }
1293 }
1294 return NO_ERROR;
1295}
1296
1297// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1298status_t AudioFlinger::PlaybackThread::checkEffectCompatibility_l(
1299 const effect_descriptor_t *desc, audio_session_t sessionId)
1300{
1301 // no preprocessing on playback threads
1302 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
1303 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback"
1304 " thread %s", desc->name, mThreadName);
1305 return BAD_VALUE;
1306 }
1307
1308 switch (mType) {
1309 case MIXER: {
1310 // Reject any effect on mixer multichannel sinks.
1311 // TODO: fix both format and multichannel issues with effects.
1312 if (mChannelCount != FCC_2) {
1313 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d) on MIXER"
1314 " thread %s", desc->name, mChannelCount, mThreadName);
1315 return BAD_VALUE;
1316 }
1317 audio_output_flags_t flags = mOutput->flags;
1318 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1319 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1320 // global effects are applied only to non fast tracks if they are SW
1321 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1322 break;
1323 }
1324 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1325 // only post processing on output stage session
1326 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1327 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1328 " on output stage session", desc->name);
1329 return BAD_VALUE;
1330 }
1331 } else {
1332 // no restriction on effects applied on non fast tracks
1333 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1334 break;
1335 }
1336 }
1337 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
1338 ALOGW("checkEffectCompatibility_l(): effect %s on playback thread in raw mode",
1339 desc->name);
1340 return BAD_VALUE;
1341 }
1342 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1343 ALOGW("checkEffectCompatibility_l(): non HW effect %s on playback thread"
1344 " in fast mode", desc->name);
1345 return BAD_VALUE;
1346 }
1347 }
1348 } break;
1349 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001350 // nothing actionable on offload threads, if the effect:
1351 // - is offloadable: the effect can be created
1352 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1353 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001354 break;
1355 case DIRECT:
1356 // Reject any effect on Direct output threads for now, since the format of
1357 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1358 ALOGW("checkEffectCompatibility_l(): effect %s on DIRECT output thread %s",
1359 desc->name, mThreadName);
1360 return BAD_VALUE;
1361 case DUPLICATING:
1362 // Reject any effect on mixer multichannel sinks.
1363 // TODO: fix both format and multichannel issues with effects.
1364 if (mChannelCount != FCC_2) {
1365 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d)"
1366 " on DUPLICATING thread %s", desc->name, mChannelCount, mThreadName);
1367 return BAD_VALUE;
1368 }
1369 if ((sessionId == AUDIO_SESSION_OUTPUT_STAGE) || (sessionId == AUDIO_SESSION_OUTPUT_MIX)) {
1370 ALOGW("checkEffectCompatibility_l(): global effect %s on DUPLICATING"
1371 " thread %s", desc->name, mThreadName);
1372 return BAD_VALUE;
1373 }
1374 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
1375 ALOGW("checkEffectCompatibility_l(): post processing effect %s on"
1376 " DUPLICATING thread %s", desc->name, mThreadName);
1377 return BAD_VALUE;
1378 }
1379 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1380 ALOGW("checkEffectCompatibility_l(): HW tunneled effect %s on"
1381 " DUPLICATING thread %s", desc->name, mThreadName);
1382 return BAD_VALUE;
1383 }
1384 break;
1385 default:
1386 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1387 }
1388
1389 return NO_ERROR;
1390}
1391
Eric Laurent81784c32012-11-19 14:55:58 -08001392// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1393sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1394 const sp<AudioFlinger::Client>& client,
1395 const sp<IEffectClient>& effectClient,
1396 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001397 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001398 effect_descriptor_t *desc,
1399 int *enabled,
Glenn Kasten9156ef32013-08-06 15:39:08 -07001400 status_t *status)
Eric Laurent81784c32012-11-19 14:55:58 -08001401{
1402 sp<EffectModule> effect;
1403 sp<EffectHandle> handle;
1404 status_t lStatus;
1405 sp<EffectChain> chain;
1406 bool chainCreated = false;
1407 bool effectCreated = false;
1408 bool effectRegistered = false;
1409
1410 lStatus = initCheck();
1411 if (lStatus != NO_ERROR) {
1412 ALOGW("createEffect_l() Audio driver not initialized.");
1413 goto Exit;
1414 }
1415
Eric Laurent81784c32012-11-19 14:55:58 -08001416 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1417
1418 { // scope for mLock
1419 Mutex::Autolock _l(mLock);
1420
Eric Laurent4c415062016-06-17 16:14:16 -07001421 lStatus = checkEffectCompatibility_l(desc, sessionId);
1422 if (lStatus != NO_ERROR) {
1423 goto Exit;
1424 }
1425
Eric Laurent81784c32012-11-19 14:55:58 -08001426 // check for existing effect chain with the requested audio session
1427 chain = getEffectChain_l(sessionId);
1428 if (chain == 0) {
1429 // create a new chain for this session
1430 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1431 chain = new EffectChain(this, sessionId);
1432 addEffectChain_l(chain);
1433 chain->setStrategy(getStrategyForSession_l(sessionId));
1434 chainCreated = true;
1435 } else {
1436 effect = chain->getEffectFromDesc_l(desc);
1437 }
1438
1439 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1440
1441 if (effect == 0) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08001442 audio_unique_id_t id = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001443 // Check CPU and memory usage
1444 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
1445 if (lStatus != NO_ERROR) {
1446 goto Exit;
1447 }
1448 effectRegistered = true;
1449 // create a new effect module if none present in the chain
1450 effect = new EffectModule(this, chain, desc, id, sessionId);
1451 lStatus = effect->status();
1452 if (lStatus != NO_ERROR) {
1453 goto Exit;
1454 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001455 effect->setOffloaded(mType == OFFLOAD, mId);
1456
Eric Laurent81784c32012-11-19 14:55:58 -08001457 lStatus = chain->addEffect_l(effect);
1458 if (lStatus != NO_ERROR) {
1459 goto Exit;
1460 }
1461 effectCreated = true;
1462
1463 effect->setDevice(mOutDevice);
1464 effect->setDevice(mInDevice);
1465 effect->setMode(mAudioFlinger->getMode());
1466 effect->setAudioSource(mAudioSource);
1467 }
1468 // create effect handle and connect it to effect module
1469 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001470 lStatus = handle->initCheck();
1471 if (lStatus == OK) {
1472 lStatus = effect->addHandle(handle.get());
1473 }
Eric Laurent81784c32012-11-19 14:55:58 -08001474 if (enabled != NULL) {
1475 *enabled = (int)effect->isEnabled();
1476 }
1477 }
1478
1479Exit:
1480 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1481 Mutex::Autolock _l(mLock);
1482 if (effectCreated) {
1483 chain->removeEffect_l(effect);
1484 }
1485 if (effectRegistered) {
1486 AudioSystem::unregisterEffect(effect->id());
1487 }
1488 if (chainCreated) {
1489 removeEffectChain_l(chain);
1490 }
1491 handle.clear();
1492 }
1493
Glenn Kasten9156ef32013-08-06 15:39:08 -07001494 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001495 return handle;
1496}
1497
Glenn Kastend848eb42016-03-08 13:42:11 -08001498sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1499 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001500{
1501 Mutex::Autolock _l(mLock);
1502 return getEffect_l(sessionId, effectId);
1503}
1504
Glenn Kastend848eb42016-03-08 13:42:11 -08001505sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1506 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001507{
1508 sp<EffectChain> chain = getEffectChain_l(sessionId);
1509 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1510}
1511
1512// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1513// PlaybackThread::mLock held
1514status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1515{
1516 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001517 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001518 sp<EffectChain> chain = getEffectChain_l(sessionId);
1519 bool chainCreated = false;
1520
Eric Laurent5baf2af2013-09-12 17:37:00 -07001521 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1522 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1523 this, effect->desc().name, effect->desc().flags);
1524
Eric Laurent81784c32012-11-19 14:55:58 -08001525 if (chain == 0) {
1526 // create a new chain for this session
1527 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1528 chain = new EffectChain(this, sessionId);
1529 addEffectChain_l(chain);
1530 chain->setStrategy(getStrategyForSession_l(sessionId));
1531 chainCreated = true;
1532 }
1533 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1534
1535 if (chain->getEffectFromId_l(effect->id()) != 0) {
1536 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1537 this, effect->desc().name, chain.get());
1538 return BAD_VALUE;
1539 }
1540
Eric Laurent5baf2af2013-09-12 17:37:00 -07001541 effect->setOffloaded(mType == OFFLOAD, mId);
1542
Eric Laurent81784c32012-11-19 14:55:58 -08001543 status_t status = chain->addEffect_l(effect);
1544 if (status != NO_ERROR) {
1545 if (chainCreated) {
1546 removeEffectChain_l(chain);
1547 }
1548 return status;
1549 }
1550
1551 effect->setDevice(mOutDevice);
1552 effect->setDevice(mInDevice);
1553 effect->setMode(mAudioFlinger->getMode());
1554 effect->setAudioSource(mAudioSource);
1555 return NO_ERROR;
1556}
1557
1558void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
1559
1560 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
1561 effect_descriptor_t desc = effect->desc();
1562 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1563 detachAuxEffect_l(effect->id());
1564 }
1565
1566 sp<EffectChain> chain = effect->chain().promote();
1567 if (chain != 0) {
1568 // remove effect chain if removing last effect
1569 if (chain->removeEffect_l(effect) == 0) {
1570 removeEffectChain_l(chain);
1571 }
1572 } else {
1573 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1574 }
1575}
1576
1577void AudioFlinger::ThreadBase::lockEffectChains_l(
1578 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1579{
1580 effectChains = mEffectChains;
1581 for (size_t i = 0; i < mEffectChains.size(); i++) {
1582 mEffectChains[i]->lock();
1583 }
1584}
1585
1586void AudioFlinger::ThreadBase::unlockEffectChains(
1587 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1588{
1589 for (size_t i = 0; i < effectChains.size(); i++) {
1590 effectChains[i]->unlock();
1591 }
1592}
1593
Glenn Kastend848eb42016-03-08 13:42:11 -08001594sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001595{
1596 Mutex::Autolock _l(mLock);
1597 return getEffectChain_l(sessionId);
1598}
1599
Glenn Kastend848eb42016-03-08 13:42:11 -08001600sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1601 const
Eric Laurent81784c32012-11-19 14:55:58 -08001602{
1603 size_t size = mEffectChains.size();
1604 for (size_t i = 0; i < size; i++) {
1605 if (mEffectChains[i]->sessionId() == sessionId) {
1606 return mEffectChains[i];
1607 }
1608 }
1609 return 0;
1610}
1611
1612void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1613{
1614 Mutex::Autolock _l(mLock);
1615 size_t size = mEffectChains.size();
1616 for (size_t i = 0; i < size; i++) {
1617 mEffectChains[i]->setMode_l(mode);
1618 }
1619}
1620
Eric Laurent83b88082014-06-20 18:31:16 -07001621void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1622{
1623 config->type = AUDIO_PORT_TYPE_MIX;
1624 config->ext.mix.handle = mId;
1625 config->sample_rate = mSampleRate;
1626 config->format = mFormat;
1627 config->channel_mask = mChannelMask;
1628 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1629 AUDIO_PORT_CONFIG_FORMAT;
1630}
1631
Eric Laurent72e3f392015-05-20 14:43:50 -07001632void AudioFlinger::ThreadBase::systemReady()
1633{
1634 Mutex::Autolock _l(mLock);
1635 if (mSystemReady) {
1636 return;
1637 }
1638 mSystemReady = true;
1639
1640 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1641 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1642 }
1643 mPendingConfigEvents.clear();
1644}
1645
Eric Laurent83b88082014-06-20 18:31:16 -07001646
Eric Laurent81784c32012-11-19 14:55:58 -08001647// ----------------------------------------------------------------------------
1648// Playback
1649// ----------------------------------------------------------------------------
1650
1651AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1652 AudioStreamOut* output,
1653 audio_io_handle_t id,
1654 audio_devices_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07001655 type_t type,
Eric Laurente93cc032016-05-05 10:15:10 -07001656 bool systemReady)
Eric Laurent72e3f392015-05-20 14:43:50 -07001657 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001658 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001659 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001660 mMixerBuffer(NULL),
1661 mMixerBufferSize(0),
1662 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1663 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001664 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001665 mEffectBuffer(NULL),
1666 mEffectBufferSize(0),
1667 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1668 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001669 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001670 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07001671 mSuspendedFrames(0),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001672 mActiveTracksGeneration(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001673 // mStreamTypes[] initialized in constructor body
1674 mOutput(output),
Andy Hung69488c42016-05-16 18:43:33 -07001675 mLastWriteTime(-1), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001676 mMixerStatus(MIXER_IDLE),
1677 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001678 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001679 mBytesRemaining(0),
1680 mCurrentWriteLength(0),
1681 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001682 mWriteAckSequence(0),
1683 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001684 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001685 mScreenState(AudioFlinger::mScreenState),
1686 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001687 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Andy Hunge10393e2015-06-12 13:59:33 -07001688 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001689{
Glenn Kastend7dca052015-03-05 16:05:54 -08001690 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1691 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001692
1693 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1694 // it would be safer to explicitly pass initial masterVolume/masterMute as
1695 // parameter.
1696 //
1697 // If the HAL we are using has support for master volume or master mute,
1698 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1699 // and the mute set to false).
1700 mMasterVolume = audioFlinger->masterVolume_l();
1701 mMasterMute = audioFlinger->masterMute_l();
1702 if (mOutput && mOutput->audioHwDev) {
1703 if (mOutput->audioHwDev->canSetMasterVolume()) {
1704 mMasterVolume = 1.0;
1705 }
1706
1707 if (mOutput->audioHwDev->canSetMasterMute()) {
1708 mMasterMute = false;
1709 }
1710 }
1711
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001712 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001713
Eric Laurent223fd5c2014-11-11 13:43:36 -08001714 // ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001715 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001716 stream = (audio_stream_type_t) (stream + 1)) {
1717 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1718 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1719 }
Eric Laurent81784c32012-11-19 14:55:58 -08001720}
1721
1722AudioFlinger::PlaybackThread::~PlaybackThread()
1723{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001724 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001725 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001726 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001727 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001728}
1729
1730void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1731{
1732 dumpInternals(fd, args);
1733 dumpTracks(fd, args);
1734 dumpEffectChains(fd, args);
1735}
1736
Glenn Kasten0f11b512014-01-31 16:18:54 -08001737void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001738{
1739 const size_t SIZE = 256;
1740 char buffer[SIZE];
1741 String8 result;
1742
Marco Nelissenb2208842014-02-07 14:00:50 -08001743 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001744 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1745 const stream_type_t *st = &mStreamTypes[i];
1746 if (i > 0) {
1747 result.appendFormat(", ");
1748 }
1749 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1750 if (st->mute) {
1751 result.append("M");
1752 }
1753 }
1754 result.append("\n");
1755 write(fd, result.string(), result.length());
1756 result.clear();
1757
Eric Laurent81784c32012-11-19 14:55:58 -08001758 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1759 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001760 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001761 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001762
1763 size_t numtracks = mTracks.size();
1764 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001765 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001766 size_t numactiveseen = 0;
1767 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001768 dprintf(fd, " of which %zu are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001769 Track::appendDumpHeader(result);
1770 for (size_t i = 0; i < numtracks; ++i) {
1771 sp<Track> track = mTracks[i];
1772 if (track != 0) {
1773 bool active = mActiveTracks.indexOf(track) >= 0;
1774 if (active) {
1775 numactiveseen++;
1776 }
1777 track->dump(buffer, SIZE, active);
1778 result.append(buffer);
1779 }
1780 }
1781 } else {
1782 result.append("\n");
1783 }
1784 if (numactiveseen != numactive) {
1785 // some tracks in the active list were not in the tracks list
1786 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1787 " not in the track list\n");
1788 result.append(buffer);
1789 Track::appendDumpHeader(result);
1790 for (size_t i = 0; i < numactive; ++i) {
1791 sp<Track> track = mActiveTracks[i].promote();
1792 if (track != 0 && mTracks.indexOf(track) < 0) {
1793 track->dump(buffer, SIZE, true);
1794 result.append(buffer);
1795 }
1796 }
1797 }
1798
1799 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001800}
1801
1802void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1803{
Glenn Kasten97b7b752014-09-28 13:04:24 -07001804 dprintf(fd, "\nOutput thread %p type %d (%s):\n", this, type(), threadTypeToString(type()));
Glenn Kasten44182c22015-03-05 17:12:23 -08001805
1806 dumpBase(fd, args);
1807
Elliott Hughes87cebad2014-05-22 10:14:43 -07001808 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001809 dprintf(fd, " Last write occurred (msecs): %llu\n",
1810 (unsigned long long) ns2ms(systemTime() - mLastWriteTime));
Elliott Hughes87cebad2014-05-22 10:14:43 -07001811 dprintf(fd, " Total writes: %d\n", mNumWrites);
1812 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1813 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1814 dprintf(fd, " Suspend count: %d\n", mSuspended);
1815 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1816 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1817 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1818 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08001819 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001820 AudioStreamOut *output = mOutput;
1821 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
1822 String8 flagsAsString = outputFlagsToString(flags);
1823 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n", output, flags, flagsAsString.string());
Eric Laurent81784c32012-11-19 14:55:58 -08001824}
1825
1826// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001827
1828void AudioFlinger::PlaybackThread::onFirstRef()
1829{
Glenn Kastend7dca052015-03-05 16:05:54 -08001830 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001831}
1832
1833// ThreadBase virtuals
1834void AudioFlinger::PlaybackThread::preExit()
1835{
1836 ALOGV(" preExit()");
1837 // FIXME this is using hard-coded strings but in the future, this functionality will be
1838 // converted to use audio HAL extensions required to support tunneling
1839 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1840}
1841
1842// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1843sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1844 const sp<AudioFlinger::Client>& client,
1845 audio_stream_type_t streamType,
1846 uint32_t sampleRate,
1847 audio_format_t format,
1848 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001849 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001850 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08001851 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07001852 audio_output_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08001853 pid_t tid,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001854 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -08001855 status_t *status)
1856{
Glenn Kasten74935e42013-12-19 08:56:45 -08001857 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001858 sp<Track> track;
1859 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07001860 audio_output_flags_t outputFlags = mOutput->flags;
1861
1862 // special case for FAST flag considered OK if fast mixer is present
1863 if (hasFastMixer()) {
1864 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
1865 }
1866
1867 // Check if requested flags are compatible with output stream flags
1868 if ((*flags & outputFlags) != *flags) {
1869 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
1870 *flags, outputFlags);
1871 *flags = (audio_output_flags_t)(*flags & outputFlags);
1872 }
Eric Laurent81784c32012-11-19 14:55:58 -08001873
Eric Laurent81784c32012-11-19 14:55:58 -08001874 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07001875 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08001876 if (
Eric Laurent81784c32012-11-19 14:55:58 -08001877 // PCM data
1878 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001879 // TODO: extract as a data library function that checks that a computationally
1880 // expensive downmixer is not required: isFastOutputChannelConversion()
Andy Hung9a592762014-07-21 21:56:01 -07001881 (channelMask == mChannelMask ||
Andy Hung1f439e12015-05-19 12:57:41 -07001882 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1883 (channelMask == AUDIO_CHANNEL_OUT_MONO
1884 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001885 // hardware sample rate
1886 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001887 // normal mixer has an associated fast mixer
1888 hasFastMixer() &&
1889 // there are sufficient fast track slots available
1890 (mFastTrackAvailMask != 0)
1891 // FIXME test that MixerThread for this fast track has a capable output HAL
1892 // FIXME add a permission test also?
1893 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07001894 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
1895 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001896 // read the fast track multiplier property the first time it is needed
1897 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1898 if (ok != 0) {
1899 ALOGE("%s pthread_once failed: %d", __func__, ok);
1900 }
Andy Hunge0a269a2016-03-23 15:13:42 -07001901 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08001902 }
Eric Laurent4c415062016-06-17 16:14:16 -07001903
1904 // check compatibility with audio effects.
1905 { // scope for mLock
1906 Mutex::Autolock _l(mLock);
1907 // do not accept RAW flag if post processing are present. Note that post processing on
1908 // a fast mixer are necessarily hardware
1909 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE);
1910 if (chain != 0) {
Eric Laurent122f7e72016-06-29 11:53:29 -07001911 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_RAW) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07001912 "AUDIO_OUTPUT_FLAG_RAW denied: post processing effect present");
1913 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_RAW);
1914 }
1915 // Do not accept FAST flag if software global effects are present
1916 chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
1917 if (chain != 0) {
Eric Laurent122f7e72016-06-29 11:53:29 -07001918 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_RAW) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07001919 "AUDIO_OUTPUT_FLAG_RAW denied: global effect present");
1920 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_RAW);
1921 if (chain->hasSoftwareEffect()) {
1922 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: software global effect present");
1923 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
1924 }
1925 }
1926 // Do not accept FAST flag if the session has software effects
1927 chain = getEffectChain_l(sessionId);
1928 if (chain != 0) {
Eric Laurent122f7e72016-06-29 11:53:29 -07001929 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_RAW) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07001930 "AUDIO_OUTPUT_FLAG_RAW denied: effect present on session");
1931 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_RAW);
1932 if (chain->hasSoftwareEffect()) {
1933 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: software effect present on session");
1934 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
1935 }
1936 }
1937 }
Eric Laurent122f7e72016-06-29 11:53:29 -07001938 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07001939 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
1940 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08001941 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001942 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
1943 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07001944 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001945 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08001946 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001947 audio_is_linear_pcm(format),
1948 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07001949 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08001950 }
1951 }
1952 // For normal PCM streaming tracks, update minimum frame count.
1953 // For compatibility with AudioTrack calculation, buffer depth is forced
1954 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1955 // This is probably too conservative, but legacy application code may depend on it.
1956 // If you change this calculation, also review the start threshold which is related.
Eric Laurent05067782016-06-01 18:27:28 -07001957 if (!(*flags & AUDIO_OUTPUT_FLAG_FAST)
Phil Burkfdb3c072016-02-09 10:47:02 -08001958 && audio_has_proportional_frames(format) && sharedBuffer == 0) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001959 // this must match AudioTrack.cpp calculateMinFrameCount().
1960 // TODO: Move to a common library
Eric Laurent81784c32012-11-19 14:55:58 -08001961 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1962 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1963 if (minBufCount < 2) {
1964 minBufCount = 2;
1965 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07001966 // For normal mixing tracks, if speed is > 1.0f (normal), AudioTrack
1967 // or the client should compute and pass in a larger buffer request.
Andy Hung0e48d252015-01-26 11:43:15 -08001968 size_t minFrameCount =
Andy Hung8edb8dc2015-03-26 19:13:55 -07001969 minBufCount * sourceFramesNeededWithTimestretch(
1970 sampleRate, mNormalFrameCount,
1971 mSampleRate, AUDIO_TIMESTRETCH_SPEED_NORMAL /*speed*/);
Andy Hung0e48d252015-01-26 11:43:15 -08001972 if (frameCount < minFrameCount) { // including frameCount == 0
Eric Laurent81784c32012-11-19 14:55:58 -08001973 frameCount = minFrameCount;
1974 }
Eric Laurent81784c32012-11-19 14:55:58 -08001975 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001976 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001977
Glenn Kastenc3df8382014-03-13 15:05:25 -07001978 switch (mType) {
1979
1980 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08001981 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08001982 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001983 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1984 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001985 sampleRate, format, channelMask, mOutput, mFormat);
1986 lStatus = BAD_VALUE;
1987 goto Exit;
1988 }
1989 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001990 break;
1991
1992 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001993 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001994 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1995 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001996 sampleRate, format, channelMask, mOutput, mFormat);
1997 lStatus = BAD_VALUE;
1998 goto Exit;
1999 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002000 break;
2001
2002 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002003 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002004 ALOGE("createTrack_l() Bad parameter: format %#x \""
2005 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002006 format, mOutput, mFormat);
2007 lStatus = BAD_VALUE;
2008 goto Exit;
2009 }
Andy Hungcd044842014-08-07 11:04:34 -07002010 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002011 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2012 lStatus = BAD_VALUE;
2013 goto Exit;
2014 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002015 break;
2016
Eric Laurent81784c32012-11-19 14:55:58 -08002017 }
2018
2019 lStatus = initCheck();
2020 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002021 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002022 goto Exit;
2023 }
2024
2025 { // scope for mLock
2026 Mutex::Autolock _l(mLock);
2027
2028 // all tracks in same audio session must share the same routing strategy otherwise
2029 // conflicts will happen when tracks are moved from one output to another by audio policy
2030 // manager
2031 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
2032 for (size_t i = 0; i < mTracks.size(); ++i) {
2033 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002034 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002035 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
2036 if (sessionId == t->sessionId() && strategy != actual) {
2037 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2038 strategy, actual);
2039 lStatus = BAD_VALUE;
2040 goto Exit;
2041 }
2042 }
2043 }
2044
Glenn Kastend79072e2016-01-06 08:41:20 -08002045 track = new Track(this, client, streamType, sampleRate, format,
2046 channelMask, frameCount, NULL, sharedBuffer,
2047 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT);
Glenn Kasten03003332013-08-06 15:40:54 -07002048
Glenn Kasten03003332013-08-06 15:40:54 -07002049 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2050 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002051 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002052 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002053 goto Exit;
2054 }
2055 mTracks.add(track);
2056
2057 sp<EffectChain> chain = getEffectChain_l(sessionId);
2058 if (chain != 0) {
2059 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2060 track->setMainBuffer(chain->inBuffer());
2061 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
2062 chain->incTrackCnt();
2063 }
2064
Eric Laurent05067782016-06-01 18:27:28 -07002065 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002066 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2067 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2068 // so ask activity manager to do this on our behalf
2069 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
2070 }
2071 }
2072
2073 lStatus = NO_ERROR;
2074
2075Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002076 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002077 return track;
2078}
2079
2080uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2081{
2082 return latency;
2083}
2084
2085uint32_t AudioFlinger::PlaybackThread::latency() const
2086{
2087 Mutex::Autolock _l(mLock);
2088 return latency_l();
2089}
2090uint32_t AudioFlinger::PlaybackThread::latency_l() const
2091{
2092 if (initCheck() == NO_ERROR) {
2093 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
2094 } else {
2095 return 0;
2096 }
2097}
2098
2099void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2100{
2101 Mutex::Autolock _l(mLock);
2102 // Don't apply master volume in SW if our HAL can do it for us.
2103 if (mOutput && mOutput->audioHwDev &&
2104 mOutput->audioHwDev->canSetMasterVolume()) {
2105 mMasterVolume = 1.0;
2106 } else {
2107 mMasterVolume = value;
2108 }
2109}
2110
2111void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2112{
2113 Mutex::Autolock _l(mLock);
2114 // Don't apply master mute in SW if our HAL can do it for us.
2115 if (mOutput && mOutput->audioHwDev &&
2116 mOutput->audioHwDev->canSetMasterMute()) {
2117 mMasterMute = false;
2118 } else {
2119 mMasterMute = muted;
2120 }
2121}
2122
2123void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2124{
2125 Mutex::Autolock _l(mLock);
2126 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002127 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002128}
2129
2130void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2131{
2132 Mutex::Autolock _l(mLock);
2133 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002134 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002135}
2136
2137float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2138{
2139 Mutex::Autolock _l(mLock);
2140 return mStreamTypes[stream].volume;
2141}
2142
2143// addTrack_l() must be called with ThreadBase::mLock held
2144status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2145{
2146 status_t status = ALREADY_EXISTS;
2147
Eric Laurent81784c32012-11-19 14:55:58 -08002148 if (mActiveTracks.indexOf(track) < 0) {
2149 // the track is newly added, make sure it fills up all its
2150 // buffers before playing. This is to ensure the client will
2151 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002152 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002153 TrackBase::track_state state = track->mState;
2154 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002155 status = AudioSystem::startOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002156 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002157 mLock.lock();
2158 // abort track was stopped/paused while we released the lock
2159 if (state != track->mState) {
2160 if (status == NO_ERROR) {
2161 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002162 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002163 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002164 mLock.lock();
2165 }
2166 return INVALID_OPERATION;
2167 }
2168 // abort if start is rejected by audio policy manager
2169 if (status != NO_ERROR) {
2170 return PERMISSION_DENIED;
2171 }
2172#ifdef ADD_BATTERY_DATA
2173 // to track the speaker usage
2174 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2175#endif
2176 }
2177
Eric Laurent51716182016-02-29 18:00:56 -08002178 // set retry count for buffer fill
2179 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002180 if (track->isStopping_1()) {
2181 track->mRetryCount = kMaxTrackStopRetriesOffload;
2182 } else {
2183 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2184 }
2185 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002186 } else {
2187 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002188 track->mFillingUpStatus =
2189 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002190 }
2191
Eric Laurent81784c32012-11-19 14:55:58 -08002192 track->mResetDone = false;
2193 track->mPresentationCompleteFrames = 0;
2194 mActiveTracks.add(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002195 mWakeLockUids.add(track->uid());
2196 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07002197 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07002198 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2199 if (chain != 0) {
2200 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2201 track->sessionId());
2202 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002203 }
2204
2205 status = NO_ERROR;
2206 }
2207
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002208 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002209 return status;
2210}
2211
Eric Laurentbfb1b832013-01-07 09:53:42 -08002212bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002213{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002214 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002215 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002216 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2217 track->mState = TrackBase::STOPPED;
2218 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002219 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002220 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002221 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002222 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002223
2224 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002225}
2226
2227void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2228{
2229 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
2230 mTracks.remove(track);
2231 deleteTrackName_l(track->name());
2232 // redundant as track is about to be destroyed, for dumpsys only
2233 track->mName = -1;
2234 if (track->isFastTrack()) {
2235 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002236 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002237 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2238 mFastTrackAvailMask |= 1 << index;
2239 // redundant as track is about to be destroyed, for dumpsys only
2240 track->mFastIndex = -1;
2241 }
2242 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2243 if (chain != 0) {
2244 chain->decTrackCnt();
2245 }
2246}
2247
Eric Laurentede6c3b2013-09-19 14:37:46 -07002248void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002249{
2250 // Thread could be blocked waiting for async
2251 // so signal it to handle state changes immediately
2252 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
2253 // be lost so we also flag to prevent it blocking on mWaitWorkCV
2254 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002255 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002256}
2257
Eric Laurent81784c32012-11-19 14:55:58 -08002258String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2259{
Eric Laurent81784c32012-11-19 14:55:58 -08002260 Mutex::Autolock _l(mLock);
2261 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07002262 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002263 }
2264
Glenn Kastend8ea6992013-07-16 14:17:15 -07002265 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
2266 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08002267 free(s);
2268 return out_s8;
2269}
2270
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002271void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002272 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2273 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002274
Eric Laurent73e26b62015-04-27 16:55:58 -07002275 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002276
2277 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002278 case AUDIO_OUTPUT_OPENED:
2279 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002280 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002281 desc->mChannelMask = mChannelMask;
2282 desc->mSamplingRate = mSampleRate;
2283 desc->mFormat = mFormat;
2284 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002285 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002286 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002287 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002288 break;
2289
Eric Laurent73e26b62015-04-27 16:55:58 -07002290 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002291 default:
2292 break;
2293 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002294 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002295}
2296
Eric Laurentbfb1b832013-01-07 09:53:42 -08002297void AudioFlinger::PlaybackThread::writeCallback()
2298{
2299 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002300 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002301}
2302
2303void AudioFlinger::PlaybackThread::drainCallback()
2304{
2305 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002306 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002307}
2308
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002309void AudioFlinger::PlaybackThread::errorCallback()
2310{
2311 ALOG_ASSERT(mCallbackThread != 0);
2312 mCallbackThread->setAsyncError();
2313}
2314
Eric Laurent3b4529e2013-09-05 18:09:19 -07002315void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002316{
2317 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002318 // reject out of sequence requests
2319 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2320 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002321 mWaitWorkCV.signal();
2322 }
2323}
2324
Eric Laurent3b4529e2013-09-05 18:09:19 -07002325void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002326{
2327 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002328 // reject out of sequence requests
2329 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
2330 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002331 mWaitWorkCV.signal();
2332 }
2333}
2334
2335// static
2336int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
Glenn Kasten0f11b512014-01-31 16:18:54 -08002337 void *param __unused,
Eric Laurentbfb1b832013-01-07 09:53:42 -08002338 void *cookie)
2339{
2340 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
2341 ALOGV("asyncCallback() event %d", event);
2342 switch (event) {
2343 case STREAM_CBK_EVENT_WRITE_READY:
2344 me->writeCallback();
2345 break;
2346 case STREAM_CBK_EVENT_DRAIN_READY:
2347 me->drainCallback();
2348 break;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002349 case STREAM_CBK_EVENT_ERROR:
2350 me->errorCallback();
2351 break;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002352 default:
2353 ALOGW("asyncCallback() unknown event %d", event);
2354 break;
2355 }
2356 return 0;
2357}
2358
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002359void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002360{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002361 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002362 mSampleRate = mOutput->getSampleRate();
2363 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002364 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002365 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002366 }
Andy Hung9a592762014-07-21 21:56:01 -07002367 if ((mType == MIXER || mType == DUPLICATING)
2368 && !isValidPcmSinkChannelMask(mChannelMask)) {
2369 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2370 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002371 }
Andy Hunge5412692014-05-16 11:25:07 -07002372 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002373
2374 // Get actual HAL format.
Andy Hung463be252014-07-10 16:56:07 -07002375 mHALFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Phil Burkca5e6142015-07-14 09:42:29 -07002376 // Get format from the shim, which will be different than the HAL format
2377 // if playing compressed audio over HDMI passthrough.
2378 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002379 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002380 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002381 }
Andy Hung6146c082014-03-18 11:56:15 -07002382 if ((mType == MIXER || mType == DUPLICATING)
2383 && !isValidPcmSinkFormat(mFormat)) {
2384 LOG_FATAL("HAL format %#x not supported for mixed output",
2385 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002386 }
Phil Burk062e67a2015-02-11 13:40:50 -08002387 mFrameSize = mOutput->getFrameSize();
Glenn Kasten70949c42013-08-06 07:40:12 -07002388 mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
2389 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002390 if (mFrameCount & 15) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002391 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002392 mFrameCount);
2393 }
2394
Eric Laurentbfb1b832013-01-07 09:53:42 -08002395 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
2396 (mOutput->stream->set_callback != NULL)) {
2397 if (mOutput->stream->set_callback(mOutput->stream,
2398 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
2399 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002400 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002401 }
2402 }
2403
Eric Laurentd1f69b02014-12-15 14:33:13 -08002404 mHwSupportsPause = false;
2405 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
2406 if (mOutput->stream->pause != NULL) {
2407 if (mOutput->stream->resume != NULL) {
2408 mHwSupportsPause = true;
2409 } else {
2410 ALOGW("direct output implements pause but not resume");
2411 }
2412 } else if (mOutput->stream->resume != NULL) {
2413 ALOGW("direct output implements resume but not pause");
2414 }
2415 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002416 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2417 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2418 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002419
Andy Hungfbfc3952015-01-15 13:33:51 -08002420 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2421 // For best precision, we use float instead of the associated output
2422 // device format (typically PCM 16 bit).
2423
2424 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2425 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2426 mBufferSize = mFrameSize * mFrameCount;
2427
2428 // TODO: We currently use the associated output device channel mask and sample rate.
2429 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2430 // (if a valid mask) to avoid premature downmix.
2431 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2432 // instead of the output device sample rate to avoid loss of high frequency information.
2433 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2434 }
2435
Andy Hung09a50072014-02-27 14:30:47 -08002436 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002437 double multiplier = 1.0;
2438 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2439 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002440 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2441 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002442
Eric Laurent81784c32012-11-19 14:55:58 -08002443 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2444 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2445 maxNormalFrameCount = maxNormalFrameCount & ~15;
2446 if (maxNormalFrameCount < minNormalFrameCount) {
2447 maxNormalFrameCount = minNormalFrameCount;
2448 }
2449 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2450 if (multiplier <= 1.0) {
2451 multiplier = 1.0;
2452 } else if (multiplier <= 2.0) {
2453 if (2 * mFrameCount <= maxNormalFrameCount) {
2454 multiplier = 2.0;
2455 } else {
2456 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2457 }
2458 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002459 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002460 }
2461 }
2462 mNormalFrameCount = multiplier * mFrameCount;
2463 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002464 if (mType == MIXER || mType == DUPLICATING) {
2465 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2466 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002467 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002468 mNormalFrameCount);
2469
Andy Hung08fb1742015-05-31 23:22:10 -07002470 // Check if we want to throttle the processing to no more than 2x normal rate
2471 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002472 mThreadThrottleTimeMs = 0;
2473 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002474 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2475
Andy Hung010a1a12014-03-13 13:57:33 -07002476 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2477 // Originally this was int16_t[] array, need to remove legacy implications.
2478 free(mSinkBuffer);
2479 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002480 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2481 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2482 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002483 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002484
Andy Hung69aed5f2014-02-25 17:24:40 -08002485 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2486 // drives the output.
2487 free(mMixerBuffer);
2488 mMixerBuffer = NULL;
2489 if (mMixerBufferEnabled) {
2490 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2491 mMixerBufferSize = mNormalFrameCount * mChannelCount
2492 * audio_bytes_per_sample(mMixerBufferFormat);
2493 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2494 }
Andy Hung98ef9782014-03-04 14:46:50 -08002495 free(mEffectBuffer);
2496 mEffectBuffer = NULL;
2497 if (mEffectBufferEnabled) {
2498 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2499 mEffectBufferSize = mNormalFrameCount * mChannelCount
2500 * audio_bytes_per_sample(mEffectBufferFormat);
2501 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2502 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002503
Eric Laurent81784c32012-11-19 14:55:58 -08002504 // force reconfiguration of effect chains and engines to take new buffer size and audio
2505 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002506 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002507 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2508 // matter.
2509 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2510 Vector< sp<EffectChain> > effectChains = mEffectChains;
2511 for (size_t i = 0; i < effectChains.size(); i ++) {
2512 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2513 }
2514}
2515
2516
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002517status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002518{
2519 if (halFrames == NULL || dspFrames == NULL) {
2520 return BAD_VALUE;
2521 }
2522 Mutex::Autolock _l(mLock);
2523 if (initCheck() != NO_ERROR) {
2524 return INVALID_OPERATION;
2525 }
Andy Hung818e7a32016-02-16 18:08:07 -08002526 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002527 *halFrames = framesWritten;
2528
2529 if (isSuspended()) {
2530 // return an estimation of rendered frames when the output is suspended
2531 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002532 *dspFrames = (uint32_t)
2533 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002534 return NO_ERROR;
2535 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002536 status_t status;
2537 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002538 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002539 *dspFrames = (size_t)frames;
2540 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002541 }
2542}
2543
Eric Laurent4c415062016-06-17 16:14:16 -07002544// hasAudioSession_l() must be called with ThreadBase::mLock held
2545uint32_t AudioFlinger::PlaybackThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08002546{
Eric Laurent81784c32012-11-19 14:55:58 -08002547 uint32_t result = 0;
2548 if (getEffectChain_l(sessionId) != 0) {
2549 result = EFFECT_SESSION;
2550 }
2551
2552 for (size_t i = 0; i < mTracks.size(); ++i) {
2553 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002554 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002555 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07002556 if (track->isFastTrack()) {
2557 result |= FAST_SESSION;
2558 }
Eric Laurent81784c32012-11-19 14:55:58 -08002559 break;
2560 }
2561 }
2562
2563 return result;
2564}
2565
Glenn Kastend848eb42016-03-08 13:42:11 -08002566uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08002567{
2568 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2569 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2570 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2571 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2572 }
2573 for (size_t i = 0; i < mTracks.size(); i++) {
2574 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002575 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002576 return AudioSystem::getStrategyForStream(track->streamType());
2577 }
2578 }
2579 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2580}
2581
2582
Phil Burk062e67a2015-02-11 13:40:50 -08002583AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002584{
2585 Mutex::Autolock _l(mLock);
2586 return mOutput;
2587}
2588
Phil Burk062e67a2015-02-11 13:40:50 -08002589AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002590{
2591 Mutex::Autolock _l(mLock);
2592 AudioStreamOut *output = mOutput;
2593 mOutput = NULL;
2594 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2595 // must push a NULL and wait for ack
2596 mOutputSink.clear();
2597 mPipeSink.clear();
2598 mNormalSink.clear();
2599 return output;
2600}
2601
2602// this method must always be called either with ThreadBase mLock held or inside the thread loop
2603audio_stream_t* AudioFlinger::PlaybackThread::stream() const
2604{
2605 if (mOutput == NULL) {
2606 return NULL;
2607 }
2608 return &mOutput->stream->common;
2609}
2610
2611uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2612{
2613 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2614}
2615
2616status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2617{
2618 if (!isValidSyncEvent(event)) {
2619 return BAD_VALUE;
2620 }
2621
2622 Mutex::Autolock _l(mLock);
2623
2624 for (size_t i = 0; i < mTracks.size(); ++i) {
2625 sp<Track> track = mTracks[i];
2626 if (event->triggerSession() == track->sessionId()) {
2627 (void) track->setSyncEvent(event);
2628 return NO_ERROR;
2629 }
2630 }
2631
2632 return NAME_NOT_FOUND;
2633}
2634
2635bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2636{
2637 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2638}
2639
2640void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2641 const Vector< sp<Track> >& tracksToRemove)
2642{
2643 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002644 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002645 for (size_t i = 0 ; i < count ; i++) {
2646 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002647 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002648 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002649 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002650#ifdef ADD_BATTERY_DATA
2651 // to track the speaker usage
2652 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2653#endif
2654 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002655 AudioSystem::releaseOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002656 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002657 }
Eric Laurent81784c32012-11-19 14:55:58 -08002658 }
2659 }
2660 }
Eric Laurent81784c32012-11-19 14:55:58 -08002661}
2662
2663void AudioFlinger::PlaybackThread::checkSilentMode_l()
2664{
2665 if (!mMasterMute) {
2666 char value[PROPERTY_VALUE_MAX];
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07002667 if (mOutDevice == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) {
2668 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
2669 return;
2670 }
Eric Laurent81784c32012-11-19 14:55:58 -08002671 if (property_get("ro.audio.silent", value, "0") > 0) {
2672 char *endptr;
2673 unsigned long ul = strtoul(value, &endptr, 0);
2674 if (*endptr == '\0' && ul != 0) {
2675 ALOGD("Silence is golden");
2676 // The setprop command will not allow a property to be changed after
2677 // the first time it is set, so we don't have to worry about un-muting.
2678 setMasterMute_l(true);
2679 }
2680 }
2681 }
2682}
2683
2684// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002685ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002686{
Eric Laurent81784c32012-11-19 14:55:58 -08002687 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002688 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002689 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002690
2691 // If an NBAIO sink is present, use it to write the normal mixer's submix
2692 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002693
Andy Hung010a1a12014-03-13 13:57:33 -07002694 const size_t count = mBytesRemaining / mFrameSize;
2695
Simon Wilson2d590962012-11-29 15:18:50 -08002696 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002697 // update the setpoint when AudioFlinger::mScreenState changes
2698 uint32_t screenState = AudioFlinger::mScreenState;
2699 if (screenState != mScreenState) {
2700 mScreenState = screenState;
2701 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2702 if (pipe != NULL) {
2703 pipe->setAvgFrames((mScreenState & 1) ?
2704 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2705 }
2706 }
Andy Hung010a1a12014-03-13 13:57:33 -07002707 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002708 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002709 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002710 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002711 } else {
2712 bytesWritten = framesWritten;
2713 }
2714 // otherwise use the HAL / AudioStreamOut directly
2715 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002716 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002717
Eric Laurentbfb1b832013-01-07 09:53:42 -08002718 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002719 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2720 mWriteAckSequence += 2;
2721 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002722 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002723 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002724 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002725 // FIXME We should have an implementation of timestamps for direct output threads.
2726 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002727 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurent51716182016-02-29 18:00:56 -08002728
Eric Laurentbfb1b832013-01-07 09:53:42 -08002729 if (mUseAsyncWrite &&
2730 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2731 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002732 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002733 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002734 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002735 }
Eric Laurent81784c32012-11-19 14:55:58 -08002736 }
2737
Eric Laurent81784c32012-11-19 14:55:58 -08002738 mNumWrites++;
2739 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002740 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002741 return bytesWritten;
2742}
2743
2744void AudioFlinger::PlaybackThread::threadLoop_drain()
2745{
2746 if (mOutput->stream->drain) {
2747 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2748 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002749 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2750 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002751 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002752 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002753 }
2754 mOutput->stream->drain(mOutput->stream,
2755 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2756 : AUDIO_DRAIN_ALL);
2757 }
2758}
2759
2760void AudioFlinger::PlaybackThread::threadLoop_exit()
2761{
Eric Laurent275e8e92014-11-30 15:14:47 -08002762 {
2763 Mutex::Autolock _l(mLock);
2764 for (size_t i = 0; i < mTracks.size(); i++) {
2765 sp<Track> track = mTracks[i];
2766 track->invalidate();
2767 }
2768 }
Eric Laurent81784c32012-11-19 14:55:58 -08002769}
2770
2771/*
2772The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002773 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002774 - mActiveSleepTimeUs from activeSleepTimeUs()
2775 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08002776 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
2777 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08002778 - maxPeriod from frame count and sample rate (MIXER only)
2779
2780The parameters that affect these derived values are:
2781 - frame count
2782 - frame size
2783 - sample rate
2784 - device type: A2DP or not
2785 - device latency
2786 - format: PCM or not
2787 - active sleep time
2788 - idle sleep time
2789*/
2790
2791void AudioFlinger::PlaybackThread::cacheParameters_l()
2792{
Andy Hung25c2dac2014-02-27 14:56:00 -08002793 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002794 mActiveSleepTimeUs = activeSleepTimeUs();
2795 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08002796
2797 // make sure standby delay is not too short when connected to an A2DP sink to avoid
2798 // truncating audio when going to standby.
2799 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
2800 if ((mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != 0) {
2801 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
2802 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
2803 }
2804 }
Eric Laurent81784c32012-11-19 14:55:58 -08002805}
2806
Eric Laurent13084622016-05-17 10:51:49 -07002807bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08002808{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002809 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08002810 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07002811 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002812 size_t size = mTracks.size();
2813 for (size_t i = 0; i < size; i++) {
2814 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07002815 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002816 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07002817 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002818 }
2819 }
Eric Laurent13084622016-05-17 10:51:49 -07002820 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08002821}
2822
Haynes Mathew George05317d22016-05-03 16:34:26 -07002823void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2824{
2825 Mutex::Autolock _l(mLock);
2826 invalidateTracks_l(streamType);
2827}
2828
Eric Laurent81784c32012-11-19 14:55:58 -08002829status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2830{
Glenn Kastend848eb42016-03-08 13:42:11 -08002831 audio_session_t session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002832 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2833 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002834 bool ownsBuffer = false;
2835
2836 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Glenn Kastend848eb42016-03-08 13:42:11 -08002837 if (session > AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002838 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002839 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002840 if (mType != DIRECT) {
2841 size_t numSamples = mNormalFrameCount * mChannelCount;
2842 buffer = new int16_t[numSamples];
2843 memset(buffer, 0, numSamples * sizeof(int16_t));
2844 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2845 ownsBuffer = true;
2846 }
2847
2848 // Attach all tracks with same session ID to this chain.
2849 for (size_t i = 0; i < mTracks.size(); ++i) {
2850 sp<Track> track = mTracks[i];
2851 if (session == track->sessionId()) {
2852 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2853 buffer);
2854 track->setMainBuffer(buffer);
2855 chain->incTrackCnt();
2856 }
2857 }
2858
2859 // indicate all active tracks in the chain
2860 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2861 sp<Track> track = mActiveTracks[i].promote();
2862 if (track == 0) {
2863 continue;
2864 }
2865 if (session == track->sessionId()) {
2866 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2867 chain->incActiveTrackCnt();
2868 }
2869 }
2870 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002871 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08002872 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002873 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2874 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002875 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Glenn Kastend848eb42016-03-08 13:42:11 -08002876 // chains list in order to be processed last as it contains output stage effects.
Eric Laurent81784c32012-11-19 14:55:58 -08002877 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2878 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08002879 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08002880 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08002881 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08002882 // Effect chain for other sessions are inserted at beginning of effect
2883 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08002884 // sessions is not important.
2885 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
2886 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX,
2887 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08002888 size_t size = mEffectChains.size();
2889 size_t i = 0;
2890 for (i = 0; i < size; i++) {
2891 if (mEffectChains[i]->sessionId() < session) {
2892 break;
2893 }
2894 }
2895 mEffectChains.insertAt(chain, i);
2896 checkSuspendOnAddEffectChain_l(chain);
2897
2898 return NO_ERROR;
2899}
2900
2901size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2902{
Glenn Kastend848eb42016-03-08 13:42:11 -08002903 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08002904
2905 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2906
2907 for (size_t i = 0; i < mEffectChains.size(); i++) {
2908 if (chain == mEffectChains[i]) {
2909 mEffectChains.removeAt(i);
2910 // detach all active tracks from the chain
2911 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2912 sp<Track> track = mActiveTracks[i].promote();
2913 if (track == 0) {
2914 continue;
2915 }
2916 if (session == track->sessionId()) {
2917 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2918 chain.get(), session);
2919 chain->decActiveTrackCnt();
2920 }
2921 }
2922
2923 // detach all tracks with same session ID from this chain
2924 for (size_t i = 0; i < mTracks.size(); ++i) {
2925 sp<Track> track = mTracks[i];
2926 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002927 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002928 chain->decTrackCnt();
2929 }
2930 }
2931 break;
2932 }
2933 }
2934 return mEffectChains.size();
2935}
2936
2937status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002938 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08002939{
2940 Mutex::Autolock _l(mLock);
2941 return attachAuxEffect_l(track, EffectId);
2942}
2943
2944status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002945 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08002946{
2947 status_t status = NO_ERROR;
2948
2949 if (EffectId == 0) {
2950 track->setAuxBuffer(0, NULL);
2951 } else {
2952 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2953 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2954 if (effect != 0) {
2955 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2956 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2957 } else {
2958 status = INVALID_OPERATION;
2959 }
2960 } else {
2961 status = BAD_VALUE;
2962 }
2963 }
2964 return status;
2965}
2966
2967void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2968{
2969 for (size_t i = 0; i < mTracks.size(); ++i) {
2970 sp<Track> track = mTracks[i];
2971 if (track->auxEffectId() == effectId) {
2972 attachAuxEffect_l(track, 0);
2973 }
2974 }
2975}
2976
2977bool AudioFlinger::PlaybackThread::threadLoop()
2978{
2979 Vector< sp<Track> > tracksToRemove;
2980
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002981 mStandbyTimeNs = systemTime();
Andy Hung69488c42016-05-16 18:43:33 -07002982 nsecs_t lastWriteFinished = -1; // time last server write completed
2983 int64_t lastFramesWritten = -1; // track changes in timestamp server frames written
Eric Laurent81784c32012-11-19 14:55:58 -08002984
2985 // MIXER
2986 nsecs_t lastWarning = 0;
2987
2988 // DUPLICATING
2989 // FIXME could this be made local to while loop?
2990 writeFrames = 0;
2991
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002992 int lastGeneration = 0;
2993
Eric Laurent81784c32012-11-19 14:55:58 -08002994 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002995 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002996
2997 if (mType == MIXER) {
2998 sleepTimeShift = 0;
2999 }
3000
3001 CpuStats cpuStats;
3002 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3003
3004 acquireWakeLock();
3005
Glenn Kasten9e58b552013-01-18 15:09:48 -08003006 // mNBLogWriter->log can only be called while thread mutex mLock is held.
3007 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3008 // and then that string will be logged at the next convenient opportunity.
3009 const char *logString = NULL;
3010
Eric Laurent664539d2013-09-23 18:24:31 -07003011 checkSilentMode_l();
3012
Eric Laurent81784c32012-11-19 14:55:58 -08003013 while (!exitPending())
3014 {
3015 cpuStats.sample(myName);
3016
3017 Vector< sp<EffectChain> > effectChains;
3018
Eric Laurent81784c32012-11-19 14:55:58 -08003019 { // scope for mLock
3020
3021 Mutex::Autolock _l(mLock);
3022
Eric Laurent021cf962014-05-13 10:18:14 -07003023 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07003024
Glenn Kasten9e58b552013-01-18 15:09:48 -08003025 if (logString != NULL) {
3026 mNBLogWriter->logTimestamp();
3027 mNBLogWriter->log(logString);
3028 logString = NULL;
3029 }
3030
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003031 // Gather the framesReleased counters for all active tracks,
Andy Hunge10393e2015-06-12 13:59:33 -07003032 // and associate with the sink frames written out. We need
3033 // this to convert the sink timestamp to the track timestamp.
Andy Hung69488c42016-05-16 18:43:33 -07003034 bool kernelLocationUpdate = false;
Andy Hunge10393e2015-06-12 13:59:33 -07003035 if (mNormalSink != 0) {
Andy Hungc54b1ff2016-02-23 14:07:07 -08003036 // Note: The DuplicatingThread may not have a mNormalSink.
Andy Hung818e7a32016-02-16 18:08:07 -08003037 // We always fetch the timestamp here because often the downstream
Andy Hung69488c42016-05-16 18:43:33 -07003038 // sink will block while writing.
Andy Hung818e7a32016-02-16 18:08:07 -08003039 ExtendedTimestamp timestamp; // use private copy to fetch
3040 (void) mNormalSink->getTimestamp(timestamp);
Andy Hung6d7b1192016-05-07 22:59:48 -07003041
3042 // We keep track of the last valid kernel position in case we are in underrun
3043 // and the normal mixer period is the same as the fast mixer period, or there
3044 // is some error from the HAL.
3045 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3046 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3047 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
3048 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3049 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
3050
3051 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3052 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
3053 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3054 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
Andy Hung69488c42016-05-16 18:43:33 -07003055 }
3056
3057 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3058 kernelLocationUpdate = true;
Andy Hung6d7b1192016-05-07 22:59:48 -07003059 } else {
Eric Laurent122f7e72016-06-29 11:53:29 -07003060 ALOGVV("getTimestamp error - no valid kernel position");
Andy Hung6d7b1192016-05-07 22:59:48 -07003061 }
3062
Andy Hung818e7a32016-02-16 18:08:07 -08003063 // copy over kernel info
3064 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
Andy Hung238fa3d2016-07-28 10:53:22 -07003065 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3066 + mSuspendedFrames; // add frames discarded when suspended
Andy Hung818e7a32016-02-16 18:08:07 -08003067 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
3068 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hungc54b1ff2016-02-23 14:07:07 -08003069 }
3070 // mFramesWritten for non-offloaded tracks are contiguous
3071 // even after standby() is called. This is useful for the track frame
3072 // to sink frame mapping.
Andy Hung69488c42016-05-16 18:43:33 -07003073 bool serverLocationUpdate = false;
3074 if (mFramesWritten != lastFramesWritten) {
3075 serverLocationUpdate = true;
3076 lastFramesWritten = mFramesWritten;
3077 }
3078 // Only update timestamps if there is a meaningful change.
3079 // Either the kernel timestamp must be valid or we have written something.
3080 if (kernelLocationUpdate || serverLocationUpdate) {
3081 if (serverLocationUpdate) {
3082 // use the time before we called the HAL write - it is a bit more accurate
3083 // to when the server last read data than the current time here.
3084 //
3085 // If we haven't written anything, mLastWriteTime will be -1
3086 // and we use systemTime().
3087 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
3088 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastWriteTime == -1
3089 ? systemTime() : mLastWriteTime;
3090 }
3091 const size_t size = mActiveTracks.size();
3092 for (size_t i = 0; i < size; ++i) {
3093 sp<Track> t = mActiveTracks[i].promote();
3094 if (t != 0 && !t->isFastTrack()) {
3095 t->updateTrackFrameInfo(
3096 t->mAudioTrackServerProxy->framesReleased(),
3097 mFramesWritten,
3098 mTimestamp);
3099 }
Andy Hunge10393e2015-06-12 13:59:33 -07003100 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07003101 }
3102
Eric Laurent81784c32012-11-19 14:55:58 -08003103 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003104 if (mSignalPending) {
3105 // A signal was raised while we were unlocked
3106 mSignalPending = false;
3107 } else if (waitingAsyncCallback_l()) {
3108 if (exitPending()) {
3109 break;
3110 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003111 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003112 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003113 releaseWakeLock_l();
3114 released = true;
Mikhail Naganove94c27a2016-08-18 17:31:46 -07003115 mWakeLockUids.clear();
3116 mActiveTracksGeneration++;
Marco Nelissen078538c2015-05-12 09:17:57 -07003117 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003118 ALOGV("wait async completion");
3119 mWaitWorkCV.wait(mLock);
3120 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003121 if (released) {
3122 acquireWakeLock_l();
3123 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003124 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3125 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003126
3127 continue;
3128 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003129 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003130 isSuspended()) {
3131 // put audio hardware into standby after short delay
3132 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003133
3134 threadLoop_standby();
3135
3136 mStandby = true;
3137 }
3138
3139 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
3140 // we're about to wait, flush the binder command buffer
3141 IPCThreadState::self()->flushCommands();
3142
3143 clearOutputTracks();
3144
3145 if (exitPending()) {
3146 break;
3147 }
3148
3149 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003150 mWakeLockUids.clear();
3151 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08003152 // wait until we have something to do...
3153 ALOGV("%s going to sleep", myName.string());
3154 mWaitWorkCV.wait(mLock);
3155 ALOGV("%s waking up", myName.string());
3156 acquireWakeLock_l();
3157
3158 mMixerStatus = MIXER_IDLE;
3159 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3160 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003161 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003162 checkSilentMode_l();
3163
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003164 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3165 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003166 if (mType == MIXER) {
3167 sleepTimeShift = 0;
3168 }
3169
3170 continue;
3171 }
3172 }
Eric Laurent81784c32012-11-19 14:55:58 -08003173 // mMixerStatusIgnoringFastTracks is also updated internally
3174 mMixerStatus = prepareTracks_l(&tracksToRemove);
3175
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003176 // compare with previously applied list
3177 if (lastGeneration != mActiveTracksGeneration) {
3178 // update wakelock
3179 updateWakeLockUids_l(mWakeLockUids);
3180 lastGeneration = mActiveTracksGeneration;
3181 }
3182
Eric Laurent81784c32012-11-19 14:55:58 -08003183 // prevent any changes in effect chain list and in each effect chain
3184 // during mixing and effect process as the audio buffers could be deleted
3185 // or modified if an effect is created or deleted
3186 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003187 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003188
Eric Laurentbfb1b832013-01-07 09:53:42 -08003189 if (mBytesRemaining == 0) {
3190 mCurrentWriteLength = 0;
3191 if (mMixerStatus == MIXER_TRACKS_READY) {
3192 // threadLoop_mix() sets mCurrentWriteLength
3193 threadLoop_mix();
3194 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3195 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003196 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003197 // must be written to HAL
3198 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003199 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003200 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003201 }
3202 }
Andy Hung98ef9782014-03-04 14:46:50 -08003203 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003204 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003205 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3206 // or mSinkBuffer (if there are no effects).
3207 //
3208 // This is done pre-effects computation; if effects change to
3209 // support higher precision, this needs to move.
3210 //
3211 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003212 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003213 if (mMixerBufferValid) {
3214 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3215 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3216
Andy Hung2ddee192015-12-18 17:34:44 -08003217 // mono blend occurs for mixer threads only (not direct or offloaded)
3218 // and is handled here if we're going directly to the sink.
3219 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003220 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3221 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003222 }
3223
Andy Hung98ef9782014-03-04 14:46:50 -08003224 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
3225 mNormalFrameCount * mChannelCount);
3226 }
3227
Eric Laurentbfb1b832013-01-07 09:53:42 -08003228 mBytesRemaining = mCurrentWriteLength;
3229 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003230 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3231 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3232 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3233 mBytesWritten += mBytesRemaining;
3234 mFramesWritten += framesRemaining;
3235 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003236 mBytesRemaining = 0;
3237 }
Eric Laurent81784c32012-11-19 14:55:58 -08003238
Eric Laurentbfb1b832013-01-07 09:53:42 -08003239 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003240 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003241 for (size_t i = 0; i < effectChains.size(); i ++) {
3242 effectChains[i]->process_l();
3243 }
Eric Laurent81784c32012-11-19 14:55:58 -08003244 }
3245 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003246 // Process effect chains for offloaded thread even if no audio
3247 // was read from audio track: process only updates effect state
3248 // and thus does have to be synchronized with audio writes but may have
3249 // to be called while waiting for async write callback
3250 if (mType == OFFLOAD) {
3251 for (size_t i = 0; i < effectChains.size(); i ++) {
3252 effectChains[i]->process_l();
3253 }
3254 }
Eric Laurent81784c32012-11-19 14:55:58 -08003255
Andy Hung98ef9782014-03-04 14:46:50 -08003256 // Only if the Effects buffer is enabled and there is data in the
3257 // Effects buffer (buffer valid), we need to
3258 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003259 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003260 if (mEffectBufferValid) {
3261 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003262
3263 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003264 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3265 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003266 }
3267
Andy Hung98ef9782014-03-04 14:46:50 -08003268 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
3269 mNormalFrameCount * mChannelCount);
3270 }
3271
Eric Laurent81784c32012-11-19 14:55:58 -08003272 // enable changes in effect chain
3273 unlockEffectChains(effectChains);
3274
Eric Laurentbfb1b832013-01-07 09:53:42 -08003275 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003276 // mSleepTimeUs == 0 means we must write to audio hardware
3277 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003278 ssize_t ret = 0;
Andy Hung69488c42016-05-16 18:43:33 -07003279 // We save lastWriteFinished here, as previousLastWriteFinished,
3280 // for throttling. On thread start, previousLastWriteFinished will be
3281 // set to -1, which properly results in no throttling after the first write.
3282 nsecs_t previousLastWriteFinished = lastWriteFinished;
3283 nsecs_t delta = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003284 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003285 // FIXME rewrite to reduce number of system calls
3286 mLastWriteTime = systemTime(); // also used for dumpsys
Andy Hung08fb1742015-05-31 23:22:10 -07003287 ret = threadLoop_write();
Andy Hung69488c42016-05-16 18:43:33 -07003288 lastWriteFinished = systemTime();
3289 delta = lastWriteFinished - mLastWriteTime;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003290 if (ret < 0) {
3291 mBytesRemaining = 0;
3292 } else {
3293 mBytesWritten += ret;
3294 mBytesRemaining -= ret;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003295 mFramesWritten += ret / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003296 }
3297 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3298 (mMixerStatus == MIXER_DRAIN_ALL)) {
3299 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003300 }
Andy Hung08fb1742015-05-31 23:22:10 -07003301 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003302 // write blocked detection
Andy Hung08fb1742015-05-31 23:22:10 -07003303 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003304 mNumDelayedWrites++;
Andy Hung69488c42016-05-16 18:43:33 -07003305 if ((lastWriteFinished - lastWarning) > kWarningThrottleNs) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003306 ATRACE_NAME("underrun");
3307 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003308 (unsigned long long) ns2ms(delta), mNumDelayedWrites, this);
Andy Hung69488c42016-05-16 18:43:33 -07003309 lastWarning = lastWriteFinished;
Glenn Kasten4944acb2013-08-19 08:39:20 -07003310 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003311 }
Andy Hung08fb1742015-05-31 23:22:10 -07003312
3313 if (mThreadThrottle
3314 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
3315 && ret > 0) { // we wrote something
3316 // Limit MixerThread data processing to no more than twice the
3317 // expected processing rate.
3318 //
3319 // This helps prevent underruns with NuPlayer and other applications
3320 // which may set up buffers that are close to the minimum size, or use
3321 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3322 //
3323 // The throttle smooths out sudden large data drains from the device,
3324 // e.g. when it comes out of standby, which often causes problems with
3325 // (1) mixer threads without a fast mixer (which has its own warm-up)
3326 // (2) minimum buffer sized tracks (even if the track is full,
3327 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07003328 //
3329 // Total time spent in last processing cycle equals time spent in
3330 // 1. threadLoop_write, as well as time spent in
3331 // 2. threadLoop_mix (significant for heavy mixing, especially
3332 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07003333
Andy Hung69488c42016-05-16 18:43:33 -07003334 // it's OK if deltaMs is an overestimate.
3335 const int32_t deltaMs =
3336 (lastWriteFinished - previousLastWriteFinished) / 1000000;
Andy Hung08fb1742015-05-31 23:22:10 -07003337 const int32_t throttleMs = mHalfBufferMs - deltaMs;
3338 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3339 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003340 // notify of throttle start on verbose log
3341 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3342 "mixer(%p) throttle begin:"
3343 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003344 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003345 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07003346 // Throttle must be attributed to the previous mixer loop's write time
3347 // to allow back-to-back throttling.
3348 lastWriteFinished += throttleMs * 1000000;
Andy Hung40eb1a12015-06-18 13:42:02 -07003349 } else {
3350 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3351 if (diff > 0) {
3352 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07003353 // but prevent spamming for bluetooth
3354 ALOGD_IF(!audio_is_a2dp_out_device(outDevice()),
3355 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07003356 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3357 }
Andy Hung08fb1742015-05-31 23:22:10 -07003358 }
3359 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003360 }
Eric Laurent81784c32012-11-19 14:55:58 -08003361
Eric Laurentbfb1b832013-01-07 09:53:42 -08003362 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003363 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07003364 Mutex::Autolock _l(mLock);
3365 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
3366 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08003367 }
Glenn Kastene7754022014-10-31 12:11:26 -07003368 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003369 }
Eric Laurent81784c32012-11-19 14:55:58 -08003370 }
3371
3372 // Finally let go of removed track(s), without the lock held
3373 // since we can't guarantee the destructors won't acquire that
3374 // same lock. This will also mutate and push a new fast mixer state.
3375 threadLoop_removeTracks(tracksToRemove);
3376 tracksToRemove.clear();
3377
3378 // FIXME I don't understand the need for this here;
3379 // it was in the original code but maybe the
3380 // assignment in saveOutputTracks() makes this unnecessary?
3381 clearOutputTracks();
3382
3383 // Effect chains will be actually deleted here if they were removed from
3384 // mEffectChains list during mixing or effects processing
3385 effectChains.clear();
3386
3387 // FIXME Note that the above .clear() is no longer necessary since effectChains
3388 // is now local to this block, but will keep it for now (at least until merge done).
3389 }
3390
Eric Laurentbfb1b832013-01-07 09:53:42 -08003391 threadLoop_exit();
3392
Eric Laurentcf817a22014-08-04 20:36:31 -07003393 if (!mStandby) {
3394 threadLoop_standby();
3395 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003396 }
3397
3398 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003399 mWakeLockUids.clear();
3400 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08003401
3402 ALOGV("Thread %p type %d exiting", this, mType);
3403 return false;
3404}
3405
Eric Laurentbfb1b832013-01-07 09:53:42 -08003406// removeTracks_l() must be called with ThreadBase::mLock held
3407void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3408{
3409 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003410 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003411 for (size_t i=0 ; i<count ; i++) {
3412 const sp<Track>& track = tracksToRemove.itemAt(i);
3413 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003414 mWakeLockUids.remove(track->uid());
3415 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003416 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3417 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3418 if (chain != 0) {
3419 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3420 track->sessionId());
3421 chain->decActiveTrackCnt();
3422 }
3423 if (track->isTerminated()) {
3424 removeTrack_l(track);
3425 }
3426 }
3427 }
3428
3429}
Eric Laurent81784c32012-11-19 14:55:58 -08003430
Eric Laurentaccc1472013-09-20 09:36:34 -07003431status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3432{
3433 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08003434 ExtendedTimestamp ets;
3435 status_t status = mNormalSink->getTimestamp(ets);
3436 if (status == NO_ERROR) {
3437 status = ets.getBestTimestamp(&timestamp);
3438 }
3439 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07003440 }
Andy Hung9a1c8892014-12-03 11:37:42 -08003441 if ((mType == OFFLOAD || mType == DIRECT)
3442 && mOutput != NULL && mOutput->stream->get_presentation_position) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003443 uint64_t position64;
Phil Burk062e67a2015-02-11 13:40:50 -08003444 int ret = mOutput->getPresentationPosition(&position64, &timestamp.mTime);
Eric Laurentaccc1472013-09-20 09:36:34 -07003445 if (ret == 0) {
3446 timestamp.mPosition = (uint32_t)position64;
3447 return NO_ERROR;
3448 }
3449 }
3450 return INVALID_OPERATION;
3451}
Eric Laurent1c333e22014-05-20 10:48:17 -07003452
Eric Laurent054d9d32015-04-24 08:48:48 -07003453status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3454 audio_patch_handle_t *handle)
3455{
Andy Hungf60abce2016-08-26 11:37:54 -07003456 status_t status;
3457 if (property_get_bool("af.patch_park", false /* default_value */)) {
3458 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3459 // or if HAL does not properly lock against access.
3460 AutoPark<FastMixer> park(mFastMixer);
3461 status = PlaybackThread::createAudioPatch_l(patch, handle);
3462 } else {
3463 status = PlaybackThread::createAudioPatch_l(patch, handle);
3464 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003465 return status;
3466}
3467
Eric Laurent1c333e22014-05-20 10:48:17 -07003468status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3469 audio_patch_handle_t *handle)
3470{
3471 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003472
3473 // store new device and send to effects
3474 audio_devices_t type = AUDIO_DEVICE_NONE;
3475 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3476 type |= patch->sinks[i].ext.device.type;
3477 }
3478
3479#ifdef ADD_BATTERY_DATA
3480 // when changing the audio output device, call addBatteryData to notify
3481 // the change
3482 if (mOutDevice != type) {
3483 uint32_t params = 0;
3484 // check whether speaker is on
3485 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3486 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003487 }
3488
Eric Laurent054d9d32015-04-24 08:48:48 -07003489 audio_devices_t deviceWithoutSpeaker
3490 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3491 // check if any other device (except speaker) is on
3492 if (type & deviceWithoutSpeaker) {
3493 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3494 }
3495
3496 if (params != 0) {
3497 addBatteryData(params);
3498 }
3499 }
3500#endif
3501
3502 for (size_t i = 0; i < mEffectChains.size(); i++) {
3503 mEffectChains[i]->setDevice_l(type);
3504 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003505
3506 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3507 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3508 bool configChanged = mPrevOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003509 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003510 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003511
3512 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003513 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3514 status = hwDevice->createAudioPatch(patch->num_sources,
3515 patch->sources,
3516 patch->num_sinks,
3517 patch->sinks,
3518 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003519 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003520 char *address;
3521 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3522 //FIXME: we only support address on first sink with HAL version < 3.0
3523 address = audio_device_address_to_parameter(
3524 patch->sinks[0].ext.device.type,
3525 patch->sinks[0].ext.device.address);
3526 } else {
3527 address = (char *)calloc(1, 1);
3528 }
3529 AudioParameter param = AudioParameter(String8(address));
3530 free(address);
3531 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), (int)type);
3532 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3533 param.toString().string());
3534 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003535 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003536 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003537 mPrevOutDevice = type;
Eric Laurente8726fe2015-06-26 09:39:24 -07003538 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3539 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003540 return status;
3541}
3542
Eric Laurent054d9d32015-04-24 08:48:48 -07003543status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3544{
Andy Hungf60abce2016-08-26 11:37:54 -07003545 status_t status;
3546 if (property_get_bool("af.patch_park", false /* default_value */)) {
3547 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3548 // or if HAL does not properly lock against access.
3549 AutoPark<FastMixer> park(mFastMixer);
3550 status = PlaybackThread::releaseAudioPatch_l(handle);
3551 } else {
3552 status = PlaybackThread::releaseAudioPatch_l(handle);
3553 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003554 return status;
3555}
3556
Eric Laurent1c333e22014-05-20 10:48:17 -07003557status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3558{
3559 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003560
3561 mOutDevice = AUDIO_DEVICE_NONE;
3562
Eric Laurent1c333e22014-05-20 10:48:17 -07003563 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003564 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3565 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003566 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003567 AudioParameter param;
3568 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
3569 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3570 param.toString().string());
Eric Laurent1c333e22014-05-20 10:48:17 -07003571 }
3572 return status;
3573}
3574
Eric Laurent83b88082014-06-20 18:31:16 -07003575void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3576{
3577 Mutex::Autolock _l(mLock);
3578 mTracks.add(track);
3579}
3580
3581void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3582{
3583 Mutex::Autolock _l(mLock);
3584 destroyTrack_l(track);
3585}
3586
3587void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3588{
3589 ThreadBase::getAudioPortConfig(config);
3590 config->role = AUDIO_PORT_ROLE_SOURCE;
3591 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3592 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3593}
3594
Eric Laurent81784c32012-11-19 14:55:58 -08003595// ----------------------------------------------------------------------------
3596
3597AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003598 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3599 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003600 // mAudioMixer below
3601 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08003602 mFastMixerFutex(0),
3603 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08003604 // mOutputSink below
3605 // mPipeSink below
3606 // mNormalSink below
3607{
3608 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003609 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%zu, "
3610 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003611 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3612 mNormalFrameCount);
3613 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3614
Andy Hungfbfc3952015-01-15 13:33:51 -08003615 if (type == DUPLICATING) {
3616 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3617 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3618 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3619 return;
3620 }
Eric Laurent81784c32012-11-19 14:55:58 -08003621 // create an NBAIO sink for the HAL output stream, and negotiate
3622 mOutputSink = new AudioStreamOutSink(output->stream);
3623 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003624 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003625#if !LOG_NDEBUG
3626 ssize_t index =
3627#else
3628 (void)
3629#endif
3630 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003631 ALOG_ASSERT(index == 0);
3632
3633 // initialize fast mixer depending on configuration
3634 bool initFastMixer;
3635 switch (kUseFastMixer) {
3636 case FastMixer_Never:
3637 initFastMixer = false;
3638 break;
3639 case FastMixer_Always:
3640 initFastMixer = true;
3641 break;
3642 case FastMixer_Static:
3643 case FastMixer_Dynamic:
3644 initFastMixer = mFrameCount < mNormalFrameCount;
3645 break;
3646 }
3647 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003648 audio_format_t fastMixerFormat;
3649 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3650 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3651 } else {
3652 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3653 }
3654 if (mFormat != fastMixerFormat) {
3655 // change our Sink format to accept our intermediate precision
3656 mFormat = fastMixerFormat;
3657 free(mSinkBuffer);
3658 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3659 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3660 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3661 }
Eric Laurent81784c32012-11-19 14:55:58 -08003662
3663 // create a MonoPipe to connect our submix to FastMixer
3664 NBAIO_Format format = mOutputSink->format();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003665#ifdef TEE_SINK
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003666 NBAIO_Format origformat = format;
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003667#endif
Andy Hung1258c1a2014-05-23 21:22:17 -07003668 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07003669 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003670 format.mFormat = fastMixerFormat;
3671 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3672
Eric Laurent81784c32012-11-19 14:55:58 -08003673 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3674 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3675 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3676 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3677 const NBAIO_Format offers[1] = {format};
3678 size_t numCounterOffers = 0;
Glenn Kastenfc302fd2016-04-11 14:11:26 -07003679#if !LOG_NDEBUG || defined(TEE_SINK)
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003680 ssize_t index =
3681#else
3682 (void)
3683#endif
3684 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003685 ALOG_ASSERT(index == 0);
3686 monoPipe->setAvgFrames((mScreenState & 1) ?
3687 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3688 mPipeSink = monoPipe;
3689
Glenn Kasten46909e72013-02-26 09:20:22 -08003690#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003691 if (mTeeSinkOutputEnabled) {
3692 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003693 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3694 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003695 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003696 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003697 ALOG_ASSERT(index == 0);
3698 mTeeSink = teeSink;
3699 PipeReader *teeSource = new PipeReader(*teeSink);
3700 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003701 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003702 ALOG_ASSERT(index == 0);
3703 mTeeSource = teeSource;
3704 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003705#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003706
3707 // create fast mixer and configure it initially with just one fast track for our submix
3708 mFastMixer = new FastMixer();
3709 FastMixerStateQueue *sq = mFastMixer->sq();
3710#ifdef STATE_QUEUE_DUMP
3711 sq->setObserverDump(&mStateQueueObserverDump);
3712 sq->setMutatorDump(&mStateQueueMutatorDump);
3713#endif
3714 FastMixerState *state = sq->begin();
3715 FastTrack *fastTrack = &state->mFastTracks[0];
3716 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3717 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3718 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003719 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3720 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003721 fastTrack->mGeneration++;
3722 state->mFastTracksGen++;
3723 state->mTrackMask = 1;
3724 // fast mixer will use the HAL output sink
3725 state->mOutputSink = mOutputSink.get();
3726 state->mOutputSinkGen++;
3727 state->mFrameCount = mFrameCount;
3728 state->mCommand = FastMixerState::COLD_IDLE;
3729 // already done in constructor initialization list
3730 //mFastMixerFutex = 0;
3731 state->mColdFutexAddr = &mFastMixerFutex;
3732 state->mColdGen++;
3733 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003734#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003735 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003736#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003737 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3738 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003739 sq->end();
3740 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3741
3742 // start the fast mixer
3743 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3744 pid_t tid = mFastMixer->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003745 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003746
3747#ifdef AUDIO_WATCHDOG
3748 // create and start the watchdog
3749 mAudioWatchdog = new AudioWatchdog();
3750 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3751 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3752 tid = mAudioWatchdog->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003753 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003754#endif
3755
Eric Laurent81784c32012-11-19 14:55:58 -08003756 }
3757
3758 switch (kUseFastMixer) {
3759 case FastMixer_Never:
3760 case FastMixer_Dynamic:
3761 mNormalSink = mOutputSink;
3762 break;
3763 case FastMixer_Always:
3764 mNormalSink = mPipeSink;
3765 break;
3766 case FastMixer_Static:
3767 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3768 break;
3769 }
3770}
3771
3772AudioFlinger::MixerThread::~MixerThread()
3773{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003774 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003775 FastMixerStateQueue *sq = mFastMixer->sq();
3776 FastMixerState *state = sq->begin();
3777 if (state->mCommand == FastMixerState::COLD_IDLE) {
3778 int32_t old = android_atomic_inc(&mFastMixerFutex);
3779 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003780 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003781 }
3782 }
3783 state->mCommand = FastMixerState::EXIT;
3784 sq->end();
3785 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3786 mFastMixer->join();
3787 // Though the fast mixer thread has exited, it's state queue is still valid.
3788 // We'll use that extract the final state which contains one remaining fast track
3789 // corresponding to our sub-mix.
3790 state = sq->begin();
3791 ALOG_ASSERT(state->mTrackMask == 1);
3792 FastTrack *fastTrack = &state->mFastTracks[0];
3793 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3794 delete fastTrack->mBufferProvider;
3795 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003796 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003797#ifdef AUDIO_WATCHDOG
3798 if (mAudioWatchdog != 0) {
3799 mAudioWatchdog->requestExit();
3800 mAudioWatchdog->requestExitAndWait();
3801 mAudioWatchdog.clear();
3802 }
3803#endif
3804 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003805 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003806 delete mAudioMixer;
3807}
3808
3809
3810uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3811{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003812 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003813 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3814 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3815 }
3816 return latency;
3817}
3818
3819
3820void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3821{
3822 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3823}
3824
Eric Laurentbfb1b832013-01-07 09:53:42 -08003825ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003826{
3827 // FIXME we should only do one push per cycle; confirm this is true
3828 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003829 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003830 FastMixerStateQueue *sq = mFastMixer->sq();
3831 FastMixerState *state = sq->begin();
3832 if (state->mCommand != FastMixerState::MIX_WRITE &&
3833 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3834 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07003835
3836 // FIXME workaround for first HAL write being CPU bound on some devices
3837 ATRACE_BEGIN("write");
3838 mOutput->write((char *)mSinkBuffer, 0);
3839 ATRACE_END();
3840
Eric Laurent81784c32012-11-19 14:55:58 -08003841 int32_t old = android_atomic_inc(&mFastMixerFutex);
3842 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003843 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003844 }
3845#ifdef AUDIO_WATCHDOG
3846 if (mAudioWatchdog != 0) {
3847 mAudioWatchdog->resume();
3848 }
3849#endif
3850 }
3851 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003852#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003853 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003854 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003855#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003856 sq->end();
3857 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3858 if (kUseFastMixer == FastMixer_Dynamic) {
3859 mNormalSink = mPipeSink;
3860 }
3861 } else {
3862 sq->end(false /*didModify*/);
3863 }
3864 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003865 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003866}
3867
3868void AudioFlinger::MixerThread::threadLoop_standby()
3869{
3870 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003871 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003872 FastMixerStateQueue *sq = mFastMixer->sq();
3873 FastMixerState *state = sq->begin();
3874 if (!(state->mCommand & FastMixerState::IDLE)) {
3875 state->mCommand = FastMixerState::COLD_IDLE;
3876 state->mColdFutexAddr = &mFastMixerFutex;
3877 state->mColdGen++;
3878 mFastMixerFutex = 0;
3879 sq->end();
3880 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3881 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3882 if (kUseFastMixer == FastMixer_Dynamic) {
3883 mNormalSink = mOutputSink;
3884 }
3885#ifdef AUDIO_WATCHDOG
3886 if (mAudioWatchdog != 0) {
3887 mAudioWatchdog->pause();
3888 }
3889#endif
3890 } else {
3891 sq->end(false /*didModify*/);
3892 }
3893 }
3894 PlaybackThread::threadLoop_standby();
3895}
3896
Eric Laurentbfb1b832013-01-07 09:53:42 -08003897bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3898{
3899 return false;
3900}
3901
3902bool AudioFlinger::PlaybackThread::shouldStandby_l()
3903{
3904 return !mStandby;
3905}
3906
3907bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3908{
3909 Mutex::Autolock _l(mLock);
3910 return waitingAsyncCallback_l();
3911}
3912
Eric Laurent81784c32012-11-19 14:55:58 -08003913// shared by MIXER and DIRECT, overridden by DUPLICATING
3914void AudioFlinger::PlaybackThread::threadLoop_standby()
3915{
3916 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08003917 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003918 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003919 // discard any pending drain or write ack by incrementing sequence
3920 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3921 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003922 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003923 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3924 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003925 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003926 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003927}
3928
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003929void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3930{
3931 ALOGV("signal playback thread");
3932 broadcast_l();
3933}
3934
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003935void AudioFlinger::PlaybackThread::onAsyncError()
3936{
3937 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
3938 invalidateTracks((audio_stream_type_t)i);
3939 }
3940}
3941
Eric Laurent81784c32012-11-19 14:55:58 -08003942void AudioFlinger::MixerThread::threadLoop_mix()
3943{
Eric Laurent81784c32012-11-19 14:55:58 -08003944 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08003945 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08003946 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003947 // increase sleep time progressively when application underrun condition clears.
3948 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3949 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3950 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003951 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003952 sleepTimeShift--;
3953 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003954 mSleepTimeUs = 0;
3955 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08003956 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003957
Eric Laurent81784c32012-11-19 14:55:58 -08003958}
3959
3960void AudioFlinger::MixerThread::threadLoop_sleepTime()
3961{
3962 // If no tracks are ready, sleep once for the duration of an output
3963 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003964 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003965 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003966 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
3967 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
3968 mSleepTimeUs = kMinThreadSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003969 }
3970 // reduce sleep time in case of consecutive application underruns to avoid
3971 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3972 // duration we would end up writing less data than needed by the audio HAL if
3973 // the condition persists.
3974 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3975 sleepTimeShift++;
3976 }
3977 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003978 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003979 }
3980 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003981 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3982 // before effects processing or output.
3983 if (mMixerBufferValid) {
3984 memset(mMixerBuffer, 0, mMixerBufferSize);
3985 } else {
3986 memset(mSinkBuffer, 0, mSinkBufferSize);
3987 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003988 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003989 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3990 "anticipated start");
3991 }
3992 // TODO add standby time extension fct of effect tail
3993}
3994
3995// prepareTracks_l() must be called with ThreadBase::mLock held
3996AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3997 Vector< sp<Track> > *tracksToRemove)
3998{
3999
4000 mixer_state mixerStatus = MIXER_IDLE;
4001 // find out which tracks need to be processed
4002 size_t count = mActiveTracks.size();
4003 size_t mixedTracks = 0;
4004 size_t tracksWithEffect = 0;
4005 // counts only _active_ fast tracks
4006 size_t fastTracks = 0;
4007 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
4008
4009 float masterVolume = mMasterVolume;
4010 bool masterMute = mMasterMute;
4011
4012 if (masterMute) {
4013 masterVolume = 0;
4014 }
4015 // Delegate master volume control to effect in output mix effect chain if needed
4016 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4017 if (chain != 0) {
4018 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
4019 chain->setVolume_l(&v, &v);
4020 masterVolume = (float)((v + (1 << 23)) >> 24);
4021 chain.clear();
4022 }
4023
4024 // prepare a new state to push
4025 FastMixerStateQueue *sq = NULL;
4026 FastMixerState *state = NULL;
4027 bool didModify = false;
4028 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004029 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004030 sq = mFastMixer->sq();
4031 state = sq->begin();
4032 }
4033
Andy Hung69aed5f2014-02-25 17:24:40 -08004034 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08004035 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08004036
Eric Laurent81784c32012-11-19 14:55:58 -08004037 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07004038 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08004039 if (t == 0) {
4040 continue;
4041 }
4042
4043 // this const just means the local variable doesn't change
4044 Track* const track = t.get();
4045
4046 // process fast tracks
4047 if (track->isFastTrack()) {
4048
4049 // It's theoretically possible (though unlikely) for a fast track to be created
4050 // and then removed within the same normal mix cycle. This is not a problem, as
4051 // the track never becomes active so it's fast mixer slot is never touched.
4052 // The converse, of removing an (active) track and then creating a new track
4053 // at the identical fast mixer slot within the same normal mix cycle,
4054 // is impossible because the slot isn't marked available until the end of each cycle.
4055 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07004056 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08004057 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
4058 FastTrack *fastTrack = &state->mFastTracks[j];
4059
4060 // Determine whether the track is currently in underrun condition,
4061 // and whether it had a recent underrun.
4062 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
4063 FastTrackUnderruns underruns = ftDump->mUnderruns;
4064 uint32_t recentFull = (underruns.mBitFields.mFull -
4065 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
4066 uint32_t recentPartial = (underruns.mBitFields.mPartial -
4067 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
4068 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
4069 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
4070 uint32_t recentUnderruns = recentPartial + recentEmpty;
4071 track->mObservedUnderruns = underruns;
4072 // don't count underruns that occur while stopping or pausing
4073 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07004074 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
4075 recentUnderruns > 0) {
4076 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
4077 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Phil Burk2812d9e2016-01-04 10:34:30 -08004078 } else {
4079 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Eric Laurent81784c32012-11-19 14:55:58 -08004080 }
4081
4082 // This is similar to the state machine for normal tracks,
4083 // with a few modifications for fast tracks.
4084 bool isActive = true;
4085 switch (track->mState) {
4086 case TrackBase::STOPPING_1:
4087 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08004088 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004089 track->mState = TrackBase::STOPPING_2;
4090 }
4091 break;
4092 case TrackBase::PAUSING:
4093 // ramp down is not yet implemented
4094 track->setPaused();
4095 break;
4096 case TrackBase::RESUMING:
4097 // ramp up is not yet implemented
4098 track->mState = TrackBase::ACTIVE;
4099 break;
4100 case TrackBase::ACTIVE:
4101 if (recentFull > 0 || recentPartial > 0) {
4102 // track has provided at least some frames recently: reset retry count
4103 track->mRetryCount = kMaxTrackRetries;
4104 }
4105 if (recentUnderruns == 0) {
4106 // no recent underruns: stay active
4107 break;
4108 }
4109 // there has recently been an underrun of some kind
4110 if (track->sharedBuffer() == 0) {
4111 // were any of the recent underruns "empty" (no frames available)?
4112 if (recentEmpty == 0) {
4113 // no, then ignore the partial underruns as they are allowed indefinitely
4114 break;
4115 }
4116 // there has recently been an "empty" underrun: decrement the retry counter
4117 if (--(track->mRetryCount) > 0) {
4118 break;
4119 }
4120 // indicate to client process that the track was disabled because of underrun;
4121 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004122 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004123 // remove from active list, but state remains ACTIVE [confusing but true]
4124 isActive = false;
4125 break;
4126 }
4127 // fall through
4128 case TrackBase::STOPPING_2:
4129 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08004130 case TrackBase::STOPPED:
4131 case TrackBase::FLUSHED: // flush() while active
4132 // Check for presentation complete if track is inactive
4133 // We have consumed all the buffers of this track.
4134 // This would be incomplete if we auto-paused on underrun
4135 {
4136 size_t audioHALFrames =
4137 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004138 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004139 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
4140 // track stays in active list until presentation is complete
4141 break;
4142 }
4143 }
4144 if (track->isStopping_2()) {
4145 track->mState = TrackBase::STOPPED;
4146 }
4147 if (track->isStopped()) {
4148 // Can't reset directly, as fast mixer is still polling this track
4149 // track->reset();
4150 // So instead mark this track as needing to be reset after push with ack
4151 resetMask |= 1 << i;
4152 }
4153 isActive = false;
4154 break;
4155 case TrackBase::IDLE:
4156 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08004157 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08004158 }
4159
4160 if (isActive) {
4161 // was it previously inactive?
4162 if (!(state->mTrackMask & (1 << j))) {
4163 ExtendedAudioBufferProvider *eabp = track;
4164 VolumeProvider *vp = track;
4165 fastTrack->mBufferProvider = eabp;
4166 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08004167 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07004168 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08004169 fastTrack->mGeneration++;
4170 state->mTrackMask |= 1 << j;
4171 didModify = true;
4172 // no acknowledgement required for newly active tracks
4173 }
4174 // cache the combined master volume and stream type volume for fast mixer; this
4175 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08004176 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08004177 ++fastTracks;
4178 } else {
4179 // was it previously active?
4180 if (state->mTrackMask & (1 << j)) {
4181 fastTrack->mBufferProvider = NULL;
4182 fastTrack->mGeneration++;
4183 state->mTrackMask &= ~(1 << j);
4184 didModify = true;
4185 // If any fast tracks were removed, we must wait for acknowledgement
4186 // because we're about to decrement the last sp<> on those tracks.
4187 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4188 } else {
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08004189 LOG_ALWAYS_FATAL("fast track %d should have been active; "
4190 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
4191 j, track->mState, state->mTrackMask, recentUnderruns,
4192 track->sharedBuffer() != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004193 }
4194 tracksToRemove->add(track);
4195 // Avoids a misleading display in dumpsys
4196 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
4197 }
4198 continue;
4199 }
4200
4201 { // local variable scope to avoid goto warning
4202
4203 audio_track_cblk_t* cblk = track->cblk();
4204
4205 // The first time a track is added we wait
4206 // for all its buffers to be filled before processing it
4207 int name = track->name();
4208 // make sure that we have enough frames to mix one full buffer.
4209 // enforce this condition only once to enable draining the buffer in case the client
4210 // app does not call stop() and relies on underrun to stop:
4211 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
4212 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004213 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07004214 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004215 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004216
4217 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004218 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004219 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
4220 // add frames already consumed but not yet released by the resampler
4221 // because mAudioTrackServerProxy->framesReady() will include these frames
4222 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
4223
Eric Laurent81784c32012-11-19 14:55:58 -08004224 uint32_t minFrames = 1;
4225 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
4226 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004227 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08004228 }
Eric Laurent13e4c962013-12-20 17:36:01 -08004229
4230 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07004231 if (ATRACE_ENABLED()) {
4232 // I wish we had formatted trace names
4233 char traceName[16];
4234 strcpy(traceName, "nRdy");
4235 int name = track->name();
4236 if (AudioMixer::TRACK0 <= name &&
4237 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
4238 name -= AudioMixer::TRACK0;
4239 traceName[4] = (name / 10) + '0';
4240 traceName[5] = (name % 10) + '0';
4241 } else {
4242 traceName[4] = '?';
4243 traceName[5] = '?';
4244 }
4245 traceName[6] = '\0';
4246 ATRACE_INT(traceName, framesReady);
4247 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004248 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08004249 !track->isPaused() && !track->isTerminated())
4250 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004251 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004252
4253 mixedTracks++;
4254
Andy Hung69aed5f2014-02-25 17:24:40 -08004255 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
4256 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08004257 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08004258 if (track->mainBuffer() != mSinkBuffer &&
4259 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004260 if (mEffectBufferEnabled) {
4261 mEffectBufferValid = true; // Later can set directly.
4262 }
Eric Laurent81784c32012-11-19 14:55:58 -08004263 chain = getEffectChain_l(track->sessionId());
4264 // Delegate volume control to effect in track effect chain if needed
4265 if (chain != 0) {
4266 tracksWithEffect++;
4267 } else {
4268 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
4269 "session %d",
4270 name, track->sessionId());
4271 }
4272 }
4273
4274
4275 int param = AudioMixer::VOLUME;
4276 if (track->mFillingUpStatus == Track::FS_FILLED) {
4277 // no ramp for the first volume setting
4278 track->mFillingUpStatus = Track::FS_ACTIVE;
4279 if (track->mState == TrackBase::RESUMING) {
4280 track->mState = TrackBase::ACTIVE;
4281 param = AudioMixer::RAMP_VOLUME;
4282 }
4283 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004284 // FIXME should not make a decision based on mServer
4285 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004286 // If the track is stopped before the first frame was mixed,
4287 // do not apply ramp
4288 param = AudioMixer::RAMP_VOLUME;
4289 }
4290
4291 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07004292 uint32_t vl, vr; // in U8.24 integer format
4293 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08004294 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07004295 vl = vr = 0;
4296 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08004297 if (track->isPausing()) {
4298 track->setPaused();
4299 }
4300 } else {
4301
4302 // read original volumes with volume control
4303 float typeVolume = mStreamTypes[track->streamType()].volume;
4304 float v = masterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07004305 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004306 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07004307 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
4308 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08004309 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07004310 if (vlf > GAIN_FLOAT_UNITY) {
4311 ALOGV("Track left volume out of range: %.3g", vlf);
4312 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004313 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07004314 if (vrf > GAIN_FLOAT_UNITY) {
4315 ALOGV("Track right volume out of range: %.3g", vrf);
4316 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004317 }
4318 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07004319 vlf *= v;
4320 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08004321 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07004322 // then derive vl and vr as U8.24 versions for the effect chain
4323 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
4324 vl = (uint32_t) (scaleto8_24 * vlf);
4325 vr = (uint32_t) (scaleto8_24 * vrf);
4326 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08004327 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08004328 // send level comes from shared memory and so may be corrupt
4329 if (sendLevel > MAX_GAIN_INT) {
4330 ALOGV("Track send level out of range: %04X", sendLevel);
4331 sendLevel = MAX_GAIN_INT;
4332 }
Andy Hung6be49402014-05-30 10:42:03 -07004333 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4334 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08004335 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004336
Eric Laurent81784c32012-11-19 14:55:58 -08004337 // Delegate volume control to effect in track effect chain if needed
4338 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4339 // Do not ramp volume if volume is controlled by effect
4340 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08004341 // Update remaining floating point volume levels
4342 vlf = (float)vl / (1 << 24);
4343 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004344 track->mHasVolumeController = true;
4345 } else {
4346 // force no volume ramp when volume controller was just disabled or removed
4347 // from effect chain to avoid volume spike
4348 if (track->mHasVolumeController) {
4349 param = AudioMixer::VOLUME;
4350 }
4351 track->mHasVolumeController = false;
4352 }
4353
Eric Laurent81784c32012-11-19 14:55:58 -08004354 // XXX: these things DON'T need to be done each time
4355 mAudioMixer->setBufferProvider(name, track);
4356 mAudioMixer->enable(name);
4357
Andy Hung6be49402014-05-30 10:42:03 -07004358 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
4359 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
4360 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004361 mAudioMixer->setParameter(
4362 name,
4363 AudioMixer::TRACK,
4364 AudioMixer::FORMAT, (void *)track->format());
4365 mAudioMixer->setParameter(
4366 name,
4367 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004368 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004369 mAudioMixer->setParameter(
4370 name,
4371 AudioMixer::TRACK,
4372 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004373 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004374 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004375 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004376 if (reqSampleRate == 0) {
4377 reqSampleRate = mSampleRate;
4378 } else if (reqSampleRate > maxSampleRate) {
4379 reqSampleRate = maxSampleRate;
4380 }
Eric Laurent81784c32012-11-19 14:55:58 -08004381 mAudioMixer->setParameter(
4382 name,
4383 AudioMixer::RESAMPLE,
4384 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004385 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004386
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004387 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004388 mAudioMixer->setParameter(
4389 name,
4390 AudioMixer::TIMESTRETCH,
4391 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004392 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004393
Andy Hung69aed5f2014-02-25 17:24:40 -08004394 /*
4395 * Select the appropriate output buffer for the track.
4396 *
Andy Hung98ef9782014-03-04 14:46:50 -08004397 * Tracks with effects go into their own effects chain buffer
4398 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004399 *
4400 * Other tracks can use mMixerBuffer for higher precision
4401 * channel accumulation. If this buffer is enabled
4402 * (mMixerBufferEnabled true), then selected tracks will accumulate
4403 * into it.
4404 *
4405 */
4406 if (mMixerBufferEnabled
4407 && (track->mainBuffer() == mSinkBuffer
4408 || track->mainBuffer() == mMixerBuffer)) {
4409 mAudioMixer->setParameter(
4410 name,
4411 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004412 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004413 mAudioMixer->setParameter(
4414 name,
4415 AudioMixer::TRACK,
4416 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4417 // TODO: override track->mainBuffer()?
4418 mMixerBufferValid = true;
4419 } else {
4420 mAudioMixer->setParameter(
4421 name,
4422 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004423 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004424 mAudioMixer->setParameter(
4425 name,
4426 AudioMixer::TRACK,
4427 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4428 }
Eric Laurent81784c32012-11-19 14:55:58 -08004429 mAudioMixer->setParameter(
4430 name,
4431 AudioMixer::TRACK,
4432 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4433
4434 // reset retry count
4435 track->mRetryCount = kMaxTrackRetries;
4436
4437 // If one track is ready, set the mixer ready if:
4438 // - the mixer was not ready during previous round OR
4439 // - no other track is not ready
4440 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4441 mixerStatus != MIXER_TRACKS_ENABLED) {
4442 mixerStatus = MIXER_TRACKS_READY;
4443 }
4444 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004445 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hung08fb1742015-05-31 23:22:10 -07004446 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)",
4447 track, framesReady, desiredFrames);
Glenn Kasten82aaf942013-07-17 16:05:07 -07004448 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08004449 } else {
4450 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004451 }
Phil Burk2812d9e2016-01-04 10:34:30 -08004452
Eric Laurent81784c32012-11-19 14:55:58 -08004453 // clear effect chain input buffer if an active track underruns to avoid sending
4454 // previous audio buffer again to effects
4455 chain = getEffectChain_l(track->sessionId());
4456 if (chain != 0) {
4457 chain->clearInputBuffer();
4458 }
4459
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004460 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004461 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4462 track->isStopped() || track->isPaused()) {
4463 // We have consumed all the buffers of this track.
4464 // Remove it from the list of active tracks.
4465 // TODO: use actual buffer filling status instead of latency when available from
4466 // audio HAL
4467 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004468 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004469 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4470 if (track->isStopped()) {
4471 track->reset();
4472 }
4473 tracksToRemove->add(track);
4474 }
4475 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004476 // No buffers for this track. Give it a few chances to
4477 // fill a buffer, then remove it from active list.
4478 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004479 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004480 tracksToRemove->add(track);
4481 // indicate to client process that the track was disabled because of underrun;
4482 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004483 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004484 // If one track is not ready, mark the mixer also not ready if:
4485 // - the mixer was ready during previous round OR
4486 // - no other track is ready
4487 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4488 mixerStatus != MIXER_TRACKS_READY) {
4489 mixerStatus = MIXER_TRACKS_ENABLED;
4490 }
4491 }
4492 mAudioMixer->disable(name);
4493 }
4494
4495 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08004496
4497 }
4498
4499 // Push the new FastMixer state if necessary
4500 bool pauseAudioWatchdog = false;
4501 if (didModify) {
4502 state->mFastTracksGen++;
4503 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4504 if (kUseFastMixer == FastMixer_Dynamic &&
4505 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4506 state->mCommand = FastMixerState::COLD_IDLE;
4507 state->mColdFutexAddr = &mFastMixerFutex;
4508 state->mColdGen++;
4509 mFastMixerFutex = 0;
4510 if (kUseFastMixer == FastMixer_Dynamic) {
4511 mNormalSink = mOutputSink;
4512 }
4513 // If we go into cold idle, need to wait for acknowledgement
4514 // so that fast mixer stops doing I/O.
4515 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4516 pauseAudioWatchdog = true;
4517 }
Eric Laurent81784c32012-11-19 14:55:58 -08004518 }
4519 if (sq != NULL) {
4520 sq->end(didModify);
4521 sq->push(block);
4522 }
4523#ifdef AUDIO_WATCHDOG
4524 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4525 mAudioWatchdog->pause();
4526 }
4527#endif
4528
4529 // Now perform the deferred reset on fast tracks that have stopped
4530 while (resetMask != 0) {
4531 size_t i = __builtin_ctz(resetMask);
4532 ALOG_ASSERT(i < count);
4533 resetMask &= ~(1 << i);
4534 sp<Track> t = mActiveTracks[i].promote();
4535 if (t == 0) {
4536 continue;
4537 }
4538 Track* track = t.get();
4539 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4540 track->reset();
4541 }
4542
4543 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004544 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004545
Eric Laurent97d547d2014-09-02 14:45:53 -07004546 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4547 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004548 }
4549
4550 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004551 // as long as there are effects we should clear the effects buffer, to avoid
4552 // passing a non-clean buffer to the effect chain
4553 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004554 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004555 // sink or mix buffer must be cleared if all tracks are connected to an
4556 // effect chain as in this case the mixer will not write to the sink or mix buffer
4557 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004558 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4559 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004560 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004561 if (mMixerBufferValid) {
4562 memset(mMixerBuffer, 0, mMixerBufferSize);
4563 // TODO: In testing, mSinkBuffer below need not be cleared because
4564 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4565 // after mixing.
4566 //
4567 // To enforce this guarantee:
4568 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4569 // (mixedTracks == 0 && fastTracks > 0))
4570 // must imply MIXER_TRACKS_READY.
4571 // Later, we may clear buffers regardless, and skip much of this logic.
4572 }
Andy Hung98ef9782014-03-04 14:46:50 -08004573 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004574 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004575 }
4576
4577 // if any fast tracks, then status is ready
4578 mMixerStatusIgnoringFastTracks = mixerStatus;
4579 if (fastTracks > 0) {
4580 mixerStatus = MIXER_TRACKS_READY;
4581 }
4582 return mixerStatus;
4583}
4584
4585// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07004586int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
Glenn Kastend848eb42016-03-08 13:42:11 -08004587 audio_format_t format, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08004588{
Andy Hunge8a1ced2014-05-09 15:02:21 -07004589 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08004590}
4591
4592// deleteTrackName_l() must be called with ThreadBase::mLock held
4593void AudioFlinger::MixerThread::deleteTrackName_l(int name)
4594{
4595 ALOGV("remove track (%d) and delete from mixer", name);
4596 mAudioMixer->deleteTrackName(name);
4597}
4598
Eric Laurent10351942014-05-08 18:49:52 -07004599// checkForNewParameter_l() must be called with ThreadBase::mLock held
4600bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4601 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004602{
Eric Laurent81784c32012-11-19 14:55:58 -08004603 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08004604 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004605
Eric Laurent10351942014-05-08 18:49:52 -07004606 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004607
Glenn Kastenc05b8d72016-03-24 09:48:17 -07004608 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004609
Eric Laurent10351942014-05-08 18:49:52 -07004610 AudioParameter param = AudioParameter(keyValuePair);
4611 int value;
4612 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4613 reconfig = true;
4614 }
4615 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004616 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004617 status = BAD_VALUE;
4618 } else {
4619 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004620 reconfig = true;
4621 }
Eric Laurent10351942014-05-08 18:49:52 -07004622 }
4623 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004624 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004625 status = BAD_VALUE;
4626 } else {
4627 // no need to save value, since it's constant
4628 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004629 }
Eric Laurent10351942014-05-08 18:49:52 -07004630 }
4631 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4632 // do not accept frame count changes if tracks are open as the track buffer
4633 // size depends on frame count and correct behavior would not be guaranteed
4634 // if frame count is changed after track creation
4635 if (!mTracks.isEmpty()) {
4636 status = INVALID_OPERATION;
4637 } else {
4638 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004639 }
Eric Laurent10351942014-05-08 18:49:52 -07004640 }
4641 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004642#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004643 // when changing the audio output device, call addBatteryData to notify
4644 // the change
4645 if (mOutDevice != value) {
4646 uint32_t params = 0;
4647 // check whether speaker is on
4648 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4649 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004650 }
Eric Laurent10351942014-05-08 18:49:52 -07004651
4652 audio_devices_t deviceWithoutSpeaker
4653 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4654 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07004655 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07004656 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4657 }
4658
4659 if (params != 0) {
4660 addBatteryData(params);
4661 }
4662 }
Eric Laurent81784c32012-11-19 14:55:58 -08004663#endif
4664
Eric Laurent10351942014-05-08 18:49:52 -07004665 // forward device change to effects that have requested to be
4666 // aware of attached audio device.
4667 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08004668 a2dpDeviceChanged =
4669 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07004670 mOutDevice = value;
4671 for (size_t i = 0; i < mEffectChains.size(); i++) {
4672 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004673 }
4674 }
Eric Laurent10351942014-05-08 18:49:52 -07004675 }
Eric Laurent81784c32012-11-19 14:55:58 -08004676
Eric Laurent10351942014-05-08 18:49:52 -07004677 if (status == NO_ERROR) {
4678 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4679 keyValuePair.string());
4680 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004681 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004682 mStandby = true;
4683 mBytesWritten = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004684 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Eric Laurent10351942014-05-08 18:49:52 -07004685 keyValuePair.string());
Eric Laurent81784c32012-11-19 14:55:58 -08004686 }
Eric Laurent10351942014-05-08 18:49:52 -07004687 if (status == NO_ERROR && reconfig) {
4688 readOutputParameters_l();
4689 delete mAudioMixer;
4690 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4691 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004692 int name = getTrackName_l(mTracks[i]->mChannelMask,
4693 mTracks[i]->mFormat, mTracks[i]->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07004694 if (name < 0) {
4695 break;
4696 }
4697 mTracks[i]->mName = name;
4698 }
Eric Laurent73e26b62015-04-27 16:55:58 -07004699 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004700 }
Eric Laurent81784c32012-11-19 14:55:58 -08004701 }
4702
Eric Laurent42537be2016-01-08 17:16:42 -08004703 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08004704}
4705
4706
4707void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4708{
Eric Laurent81784c32012-11-19 14:55:58 -08004709 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07004710 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Elliott Hughes87cebad2014-05-22 10:14:43 -07004711 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Andy Hung2ddee192015-12-18 17:34:44 -08004712 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent81784c32012-11-19 14:55:58 -08004713
4714 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten2f90c512015-12-02 11:40:09 -08004715 // while we are dumping it. It may be inconsistent, but it won't mutate!
4716 // This is a large object so we place it on the heap.
4717 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
4718 const FastMixerDumpState *copy = new FastMixerDumpState(mFastMixerDumpState);
4719 copy->dump(fd);
4720 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08004721
4722#ifdef STATE_QUEUE_DUMP
4723 // Similar for state queue
4724 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4725 observerCopy.dump(fd);
4726 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4727 mutatorCopy.dump(fd);
4728#endif
4729
Glenn Kasten46909e72013-02-26 09:20:22 -08004730#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004731 // Write the tee output to a .wav file
4732 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08004733#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004734
4735#ifdef AUDIO_WATCHDOG
4736 if (mAudioWatchdog != 0) {
4737 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4738 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4739 wdCopy.dump(fd);
4740 }
4741#endif
4742}
4743
4744uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4745{
4746 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4747}
4748
4749uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4750{
4751 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4752}
4753
4754void AudioFlinger::MixerThread::cacheParameters_l()
4755{
4756 PlaybackThread::cacheParameters_l();
4757
4758 // FIXME: Relaxed timing because of a certain device that can't meet latency
4759 // Should be reduced to 2x after the vendor fixes the driver issue
4760 // increase threshold again due to low power audio mode. The way this warning
4761 // threshold is calculated and its usefulness should be reconsidered anyway.
4762 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4763}
4764
4765// ----------------------------------------------------------------------------
4766
4767AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07004768 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady)
4769 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08004770 // mLeftVolFloat, mRightVolFloat
4771{
4772}
4773
Eric Laurentbfb1b832013-01-07 09:53:42 -08004774AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4775 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurente93cc032016-05-05 10:15:10 -07004776 ThreadBase::type_t type, bool systemReady)
4777 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004778 // mLeftVolFloat, mRightVolFloat
4779{
4780}
4781
Eric Laurent81784c32012-11-19 14:55:58 -08004782AudioFlinger::DirectOutputThread::~DirectOutputThread()
4783{
4784}
4785
Eric Laurentbfb1b832013-01-07 09:53:42 -08004786void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
4787{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004788 float left, right;
4789
4790 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4791 left = right = 0;
4792 } else {
4793 float typeVolume = mStreamTypes[track->streamType()].volume;
4794 float v = mMasterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07004795 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004796 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4797 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4798 if (left > GAIN_FLOAT_UNITY) {
4799 left = GAIN_FLOAT_UNITY;
4800 }
4801 left *= v;
4802 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4803 if (right > GAIN_FLOAT_UNITY) {
4804 right = GAIN_FLOAT_UNITY;
4805 }
4806 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004807 }
4808
4809 if (lastTrack) {
4810 if (left != mLeftVolFloat || right != mRightVolFloat) {
4811 mLeftVolFloat = left;
4812 mRightVolFloat = right;
4813
4814 // Convert volumes from float to 8.24
4815 uint32_t vl = (uint32_t)(left * (1 << 24));
4816 uint32_t vr = (uint32_t)(right * (1 << 24));
4817
4818 // Delegate volume control to effect in track effect chain if needed
4819 // only one effect chain can be present on DirectOutputThread, so if
4820 // there is one, the track is connected to it
4821 if (!mEffectChains.isEmpty()) {
4822 mEffectChains[0]->setVolume_l(&vl, &vr);
4823 left = (float)vl / (1 << 24);
4824 right = (float)vr / (1 << 24);
4825 }
4826 if (mOutput->stream->set_volume) {
4827 mOutput->stream->set_volume(mOutput->stream, left, right);
4828 }
4829 }
4830 }
4831}
4832
Phil Burk43b4dcc2015-06-09 16:53:44 -07004833void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
4834{
4835 sp<Track> previousTrack = mPreviousTrack.promote();
4836 sp<Track> latestTrack = mLatestActiveTrack.promote();
4837
Eric Laurent0f0631e2015-07-06 18:01:25 -07004838 if (previousTrack != 0 && latestTrack != 0) {
4839 if (mType == DIRECT) {
4840 if (previousTrack.get() != latestTrack.get()) {
4841 mFlushPending = true;
4842 }
4843 } else /* mType == OFFLOAD */ {
4844 if (previousTrack->sessionId() != latestTrack->sessionId()) {
4845 mFlushPending = true;
4846 }
4847 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004848 }
4849 PlaybackThread::onAddNewTrack_l();
4850}
Eric Laurentbfb1b832013-01-07 09:53:42 -08004851
Eric Laurent81784c32012-11-19 14:55:58 -08004852AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4853 Vector< sp<Track> > *tracksToRemove
4854)
4855{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004856 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004857 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004858 bool doHwPause = false;
4859 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004860
4861 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07004862 for (size_t i = 0; i < count; i++) {
4863 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08004864 // The track died recently
4865 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004866 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08004867 }
4868
Phil Burk43b4dcc2015-06-09 16:53:44 -07004869 if (t->isInvalid()) {
4870 ALOGW("An invalidated track shouldn't be in active list");
4871 tracksToRemove->add(t);
4872 continue;
4873 }
4874
Eric Laurent81784c32012-11-19 14:55:58 -08004875 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004876#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08004877 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004878#endif
Eric Laurentfd477972013-10-25 18:10:40 -07004879 // Only consider last track started for volume and mixer state control.
4880 // In theory an older track could underrun and restart after the new one starts
4881 // but as we only care about the transition phase between two tracks on a
4882 // direct output, it is not a problem to ignore the underrun case.
4883 sp<Track> l = mLatestActiveTrack.promote();
4884 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004885
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004886 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004887 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004888 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004889 doHwPause = true;
4890 mHwPaused = true;
4891 }
4892 tracksToRemove->add(track);
4893 } else if (track->isFlushPending()) {
4894 track->flushAck();
4895 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004896 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004897 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004898 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004899 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07004900 if (last) {
4901 mLeftVolFloat = mRightVolFloat = -1.0;
4902 if (mHwPaused) {
4903 doHwResume = true;
4904 mHwPaused = false;
4905 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004906 }
4907 }
4908
Eric Laurent81784c32012-11-19 14:55:58 -08004909 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004910 // for all its buffers to be filled before processing it.
4911 // Allow draining the buffer in case the client
4912 // app does not call stop() and relies on underrun to stop:
4913 // hence the test on (track->mRetryCount > 1).
4914 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07004915 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08004916 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004917 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08004918 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004919 minFrames = mNormalFrameCount;
4920 } else {
4921 minFrames = 1;
4922 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004923
Eric Laurentab5cdba2014-06-09 17:22:27 -07004924 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4925 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004926 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004927 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004928
4929 if (track->mFillingUpStatus == Track::FS_FILLED) {
4930 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07004931 if (last) {
4932 // make sure processVolume_l() will apply new volume even if 0
4933 mLeftVolFloat = mRightVolFloat = -1.0;
4934 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004935 if (!mHwSupportsPause) {
4936 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004937 }
4938 }
4939
4940 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004941 processVolume_l(track, last);
4942 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004943 sp<Track> previousTrack = mPreviousTrack.promote();
4944 if (previousTrack != 0) {
4945 if (track != previousTrack.get()) {
4946 // Flush any data still being written from last track
4947 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07004948 // Invalidate previous track to force a seek when resuming.
4949 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004950 }
4951 }
4952 mPreviousTrack = track;
4953
Eric Laurentd595b7c2013-04-03 17:27:56 -07004954 // reset retry count
4955 track->mRetryCount = kMaxTrackRetriesDirect;
4956 mActiveTrack = t;
4957 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07004958 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004959 doHwResume = true;
4960 mHwPaused = false;
4961 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004962 }
Eric Laurent81784c32012-11-19 14:55:58 -08004963 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004964 // clear effect chain input buffer if the last active track started underruns
4965 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004966 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004967 mEffectChains[0]->clearInputBuffer();
4968 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004969 if (track->isStopping_1()) {
4970 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07004971 if (last && mHwPaused) {
4972 doHwResume = true;
4973 mHwPaused = false;
4974 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004975 }
4976 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4977 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004978 // We have consumed all the buffers of this track.
4979 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004980 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08004981 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004982 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4983 } else {
4984 audioHALFrames = 0;
4985 }
4986
Andy Hung818e7a32016-02-16 18:08:07 -08004987 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004988 if (mStandby || !last ||
4989 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004990 if (track->isStopping_2()) {
4991 track->mState = TrackBase::STOPPED;
4992 }
Eric Laurent81784c32012-11-19 14:55:58 -08004993 if (track->isStopped()) {
4994 track->reset();
4995 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004996 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004997 }
4998 } else {
4999 // No buffers for this track. Give it a few chances to
5000 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07005001 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08005002 if (--(track->mRetryCount) <= 0) {
5003 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07005004 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005005 // indicate to client process that the track was disabled because of underrun;
5006 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005007 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005008 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07005009 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
5010 "minFrames = %u, mFormat = %#x",
5011 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08005012 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07005013 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005014 doHwPause = true;
5015 mHwPaused = true;
5016 }
Eric Laurent81784c32012-11-19 14:55:58 -08005017 }
5018 }
5019 }
5020 }
5021
Eric Laurentd1f69b02014-12-15 14:33:13 -08005022 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07005023 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005024 for (size_t i = 0; i < mTracks.size(); i++) {
5025 if (mTracks[i]->isFlushPending()) {
5026 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005027 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005028 }
5029 }
5030 }
5031
5032 // make sure the pause/flush/resume sequence is executed in the right order.
5033 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5034 // before flush and then resume HW. This can happen in case of pause/flush/resume
5035 // if resume is received before pause is executed.
5036 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07005037 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005038 mOutput->stream->pause(mOutput->stream);
5039 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005040 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005041 flushHw_l();
5042 }
5043 if (mHwSupportsPause && !mStandby && doHwResume) {
5044 mOutput->stream->resume(mOutput->stream);
5045 }
Eric Laurent81784c32012-11-19 14:55:58 -08005046 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005047 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005048
5049 return mixerStatus;
5050}
5051
5052void AudioFlinger::DirectOutputThread::threadLoop_mix()
5053{
Eric Laurent81784c32012-11-19 14:55:58 -08005054 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08005055 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005056 // output audio to hardware
5057 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07005058 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005059 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08005060 status_t status = mActiveTrack->getNextBuffer(&buffer);
5061 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08005062 // no need to pad with 0 for compressed audio
5063 if (audio_has_proportional_frames(mFormat)) {
5064 memset(curBuf, 0, frameCount * mFrameSize);
5065 }
Eric Laurent81784c32012-11-19 14:55:58 -08005066 break;
5067 }
5068 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
5069 frameCount -= buffer.frameCount;
5070 curBuf += buffer.frameCount * mFrameSize;
5071 mActiveTrack->releaseBuffer(&buffer);
5072 }
Andy Hung2098f272014-02-27 14:00:06 -08005073 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005074 mSleepTimeUs = 0;
5075 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005076 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005077}
5078
5079void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
5080{
Eric Laurentd1f69b02014-12-15 14:33:13 -08005081 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005082 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005083 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005084 return;
5085 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005086 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005087 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurente93cc032016-05-05 10:15:10 -07005088 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005089 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005090 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005091 }
Phil Burkfdb3c072016-02-09 10:47:02 -08005092 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08005093 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005094 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005095 }
5096}
5097
Eric Laurentd1f69b02014-12-15 14:33:13 -08005098void AudioFlinger::DirectOutputThread::threadLoop_exit()
5099{
5100 {
5101 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005102 for (size_t i = 0; i < mTracks.size(); i++) {
5103 if (mTracks[i]->isFlushPending()) {
5104 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005105 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005106 }
5107 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005108 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005109 flushHw_l();
5110 }
5111 }
5112 PlaybackThread::threadLoop_exit();
5113}
5114
5115// must be called with thread mutex locked
5116bool AudioFlinger::DirectOutputThread::shouldStandby_l()
5117{
5118 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07005119 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005120
vivek mehta9cd7ad12016-03-17 00:18:29 -07005121 if ((mType == DIRECT) && audio_is_linear_pcm(mFormat) && !usesHwAvSync()) {
5122 return !mStandby;
5123 }
5124
Eric Laurentd1f69b02014-12-15 14:33:13 -08005125 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
5126 // after a timeout and we will enter standby then.
5127 if (mTracks.size() > 0) {
5128 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07005129 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
5130 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005131 }
5132
Eric Laurent5cff4032015-05-26 13:49:58 -07005133 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08005134}
5135
Eric Laurent81784c32012-11-19 14:55:58 -08005136// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005137int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Glenn Kastend848eb42016-03-08 13:42:11 -08005138 audio_format_t format __unused, audio_session_t sessionId __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005139{
5140 return 0;
5141}
5142
5143// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005144void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005145{
5146}
5147
Eric Laurent10351942014-05-08 18:49:52 -07005148// checkForNewParameter_l() must be called with ThreadBase::mLock held
5149bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
5150 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005151{
5152 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005153 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005154
Eric Laurent10351942014-05-08 18:49:52 -07005155 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005156
Eric Laurent10351942014-05-08 18:49:52 -07005157 AudioParameter param = AudioParameter(keyValuePair);
5158 int value;
5159 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5160 // forward device change to effects that have requested to be
5161 // aware of attached audio device.
5162 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005163 a2dpDeviceChanged =
5164 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005165 mOutDevice = value;
5166 for (size_t i = 0; i < mEffectChains.size(); i++) {
5167 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07005168 }
5169 }
Eric Laurent81784c32012-11-19 14:55:58 -08005170 }
Eric Laurent10351942014-05-08 18:49:52 -07005171 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5172 // do not accept frame count changes if tracks are open as the track buffer
5173 // size depends on frame count and correct behavior would not be garantied
5174 // if frame count is changed after track creation
5175 if (!mTracks.isEmpty()) {
5176 status = INVALID_OPERATION;
5177 } else {
5178 reconfig = true;
5179 }
5180 }
5181 if (status == NO_ERROR) {
5182 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
5183 keyValuePair.string());
5184 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005185 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005186 mStandby = true;
5187 mBytesWritten = 0;
5188 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
5189 keyValuePair.string());
5190 }
5191 if (status == NO_ERROR && reconfig) {
5192 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07005193 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005194 }
5195 }
5196
Eric Laurent42537be2016-01-08 17:16:42 -08005197 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005198}
5199
5200uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
5201{
5202 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005203 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005204 time = PlaybackThread::activeSleepTimeUs();
5205 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005206 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005207 }
5208 return time;
5209}
5210
5211uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
5212{
5213 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005214 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005215 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
5216 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005217 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005218 }
5219 return time;
5220}
5221
5222uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
5223{
5224 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005225 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005226 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
5227 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005228 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005229 }
5230 return time;
5231}
5232
5233void AudioFlinger::DirectOutputThread::cacheParameters_l()
5234{
5235 PlaybackThread::cacheParameters_l();
5236
5237 // use shorter standby delay as on normal output to release
5238 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07005239 // no delay on outputs with HW A/V sync
5240 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005241 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08005242 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005243 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07005244 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005245 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07005246 }
Eric Laurent81784c32012-11-19 14:55:58 -08005247}
5248
Eric Laurente659ef42014-09-29 13:06:46 -07005249void AudioFlinger::DirectOutputThread::flushHw_l()
5250{
Phil Burk062e67a2015-02-11 13:40:50 -08005251 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08005252 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005253 mFlushPending = false;
Eric Laurente659ef42014-09-29 13:06:46 -07005254}
5255
Eric Laurent81784c32012-11-19 14:55:58 -08005256// ----------------------------------------------------------------------------
5257
Eric Laurentbfb1b832013-01-07 09:53:42 -08005258AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07005259 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005260 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07005261 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07005262 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005263 mDrainSequence(0),
5264 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005265{
5266}
5267
5268AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
5269{
5270}
5271
5272void AudioFlinger::AsyncCallbackThread::onFirstRef()
5273{
5274 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
5275}
5276
5277bool AudioFlinger::AsyncCallbackThread::threadLoop()
5278{
5279 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005280 uint32_t writeAckSequence;
5281 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005282 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005283
5284 {
5285 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005286 while (!((mWriteAckSequence & 1) ||
5287 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005288 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005289 exitPending())) {
5290 mWaitWorkCV.wait(mLock);
5291 }
5292
Eric Laurentbfb1b832013-01-07 09:53:42 -08005293 if (exitPending()) {
5294 break;
5295 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005296 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
5297 mWriteAckSequence, mDrainSequence);
5298 writeAckSequence = mWriteAckSequence;
5299 mWriteAckSequence &= ~1;
5300 drainSequence = mDrainSequence;
5301 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005302 asyncError = mAsyncError;
5303 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005304 }
5305 {
Eric Laurent4de95592013-09-26 15:28:21 -07005306 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
5307 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005308 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005309 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005310 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005311 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005312 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005313 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005314 if (asyncError) {
5315 playbackThread->onAsyncError();
5316 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005317 }
5318 }
5319 }
5320 return false;
5321}
5322
5323void AudioFlinger::AsyncCallbackThread::exit()
5324{
5325 ALOGV("AsyncCallbackThread::exit");
5326 Mutex::Autolock _l(mLock);
5327 requestExit();
5328 mWaitWorkCV.broadcast();
5329}
5330
Eric Laurent3b4529e2013-09-05 18:09:19 -07005331void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005332{
5333 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005334 // bit 0 is cleared
5335 mWriteAckSequence = sequence << 1;
5336}
5337
5338void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5339{
5340 Mutex::Autolock _l(mLock);
5341 // ignore unexpected callbacks
5342 if (mWriteAckSequence & 2) {
5343 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005344 mWaitWorkCV.signal();
5345 }
5346}
5347
Eric Laurent3b4529e2013-09-05 18:09:19 -07005348void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005349{
5350 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005351 // bit 0 is cleared
5352 mDrainSequence = sequence << 1;
5353}
5354
5355void AudioFlinger::AsyncCallbackThread::resetDraining()
5356{
5357 Mutex::Autolock _l(mLock);
5358 // ignore unexpected callbacks
5359 if (mDrainSequence & 2) {
5360 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005361 mWaitWorkCV.signal();
5362 }
5363}
5364
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005365void AudioFlinger::AsyncCallbackThread::setAsyncError()
5366{
5367 Mutex::Autolock _l(mLock);
5368 mAsyncError = true;
5369 mWaitWorkCV.signal();
5370}
5371
Eric Laurentbfb1b832013-01-07 09:53:42 -08005372
5373// ----------------------------------------------------------------------------
5374AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07005375 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
5376 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07005377 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
5378 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005379{
Eric Laurentfd477972013-10-25 18:10:40 -07005380 //FIXME: mStandby should be set to true by ThreadBase constructor
5381 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07005382 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005383}
5384
Eric Laurentbfb1b832013-01-07 09:53:42 -08005385void AudioFlinger::OffloadThread::threadLoop_exit()
5386{
5387 if (mFlushPending || mHwPaused) {
5388 // If a flush is pending or track was paused, just discard buffered data
5389 flushHw_l();
5390 } else {
5391 mMixerStatus = MIXER_DRAIN_ALL;
5392 threadLoop_drain();
5393 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005394 if (mUseAsyncWrite) {
5395 ALOG_ASSERT(mCallbackThread != 0);
5396 mCallbackThread->exit();
5397 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005398 PlaybackThread::threadLoop_exit();
5399}
5400
5401AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5402 Vector< sp<Track> > *tracksToRemove
5403)
5404{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005405 size_t count = mActiveTracks.size();
5406
5407 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005408 bool doHwPause = false;
5409 bool doHwResume = false;
5410
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005411 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07005412
Eric Laurentbfb1b832013-01-07 09:53:42 -08005413 // find out which tracks need to be processed
5414 for (size_t i = 0; i < count; i++) {
5415 sp<Track> t = mActiveTracks[i].promote();
5416 // The track died recently
5417 if (t == 0) {
5418 continue;
5419 }
5420 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005421#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08005422 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005423#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005424 // Only consider last track started for volume and mixer state control.
5425 // In theory an older track could underrun and restart after the new one starts
5426 // but as we only care about the transition phase between two tracks on a
5427 // direct output, it is not a problem to ignore the underrun case.
5428 sp<Track> l = mLatestActiveTrack.promote();
5429 bool last = l.get() == track;
5430
Haynes Mathew George7844f672014-01-15 12:32:55 -08005431 if (track->isInvalid()) {
5432 ALOGW("An invalidated track shouldn't be in active list");
5433 tracksToRemove->add(track);
5434 continue;
5435 }
5436
5437 if (track->mState == TrackBase::IDLE) {
5438 ALOGW("An idle track shouldn't be in active list");
5439 continue;
5440 }
5441
Eric Laurentbfb1b832013-01-07 09:53:42 -08005442 if (track->isPausing()) {
5443 track->setPaused();
5444 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005445 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005446 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005447 mHwPaused = true;
5448 }
5449 // If we were part way through writing the mixbuffer to
5450 // the HAL we must save this until we resume
5451 // BUG - this will be wrong if a different track is made active,
5452 // in that case we want to discard the pending data in the
5453 // mixbuffer and tell the client to present it again when the
5454 // track is resumed
5455 mPausedWriteLength = mCurrentWriteLength;
5456 mPausedBytesRemaining = mBytesRemaining;
5457 mBytesRemaining = 0; // stop writing
5458 }
5459 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005460 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005461 if (track->isStopping_1()) {
5462 track->mRetryCount = kMaxTrackStopRetriesOffload;
5463 } else {
5464 track->mRetryCount = kMaxTrackRetriesOffload;
5465 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08005466 track->flushAck();
5467 if (last) {
5468 mFlushPending = true;
5469 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005470 } else if (track->isResumePending()){
5471 track->resumeAck();
5472 if (last) {
5473 if (mPausedBytesRemaining) {
5474 // Need to continue write that was interrupted
5475 mCurrentWriteLength = mPausedWriteLength;
5476 mBytesRemaining = mPausedBytesRemaining;
5477 mPausedBytesRemaining = 0;
5478 }
5479 if (mHwPaused) {
5480 doHwResume = true;
5481 mHwPaused = false;
5482 // threadLoop_mix() will handle the case that we need to
5483 // resume an interrupted write
5484 }
5485 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005486 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005487
Eric Laurent3df841a2016-07-15 15:15:40 -07005488 mLeftVolFloat = mRightVolFloat = -1.0;
5489
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005490 // Do not handle new data in this iteration even if track->framesReady()
5491 mixerStatus = MIXER_TRACKS_ENABLED;
5492 }
5493 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005494 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005495 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005496 if (track->mFillingUpStatus == Track::FS_FILLED) {
5497 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005498 if (last) {
5499 // make sure processVolume_l() will apply new volume even if 0
5500 mLeftVolFloat = mRightVolFloat = -1.0;
5501 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005502 }
5503
5504 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005505 sp<Track> previousTrack = mPreviousTrack.promote();
5506 if (previousTrack != 0) {
5507 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005508 // Flush any data still being written from last track
5509 mBytesRemaining = 0;
5510 if (mPausedBytesRemaining) {
5511 // Last track was paused so we also need to flush saved
5512 // mixbuffer state and invalidate track so that it will
5513 // re-submit that unwritten data when it is next resumed
5514 mPausedBytesRemaining = 0;
5515 // Invalidate is a bit drastic - would be more efficient
5516 // to have a flag to tell client that some of the
5517 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005518 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005519 }
5520 // flush data already sent to the DSP if changing audio session as audio
5521 // comes from a different source. Also invalidate previous track to force a
5522 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005523 if (previousTrack->sessionId() != track->sessionId()) {
5524 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005525 }
5526 }
5527 }
5528 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005529 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07005530 if (track->isStopping_1()) {
5531 track->mRetryCount = kMaxTrackStopRetriesOffload;
5532 } else {
5533 track->mRetryCount = kMaxTrackRetriesOffload;
5534 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005535 mActiveTrack = t;
5536 mixerStatus = MIXER_TRACKS_READY;
5537 }
5538 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005539 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005540 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005541 if (--(track->mRetryCount) <= 0) {
5542 // Hardware buffer can hold a large amount of audio so we must
5543 // wait for all current track's data to drain before we say
5544 // that the track is stopped.
5545 if (mBytesRemaining == 0) {
5546 // Only start draining when all data in mixbuffer
5547 // has been written
5548 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5549 track->mState = TrackBase::STOPPING_2; // so presentation completes after
5550 // drain do not drain if no data was ever sent to HAL (mStandby == true)
5551 if (last && !mStandby) {
5552 // do not modify drain sequence if we are already draining. This happens
5553 // when resuming from pause after drain.
5554 if ((mDrainSequence & 1) == 0) {
5555 mSleepTimeUs = 0;
5556 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
5557 mixerStatus = MIXER_DRAIN_TRACK;
5558 mDrainSequence += 2;
5559 }
5560 if (mHwPaused) {
5561 // It is possible to move from PAUSED to STOPPING_1 without
5562 // a resume so we must ensure hardware is running
5563 doHwResume = true;
5564 mHwPaused = false;
5565 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005566 }
5567 }
Eric Laurente93cc032016-05-05 10:15:10 -07005568 } else if (last) {
5569 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
5570 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005571 }
5572 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005573 // Drain has completed or we are in standby, signal presentation complete
5574 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005575 track->mState = TrackBase::STOPPED;
5576 size_t audioHALFrames =
5577 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005578 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005579 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005580 track->presentationComplete(framesWritten, audioHALFrames);
5581 track->reset();
5582 tracksToRemove->add(track);
5583 }
5584 } else {
5585 // No buffers for this track. Give it a few chances to
5586 // fill a buffer, then remove it from active list.
5587 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07005588 bool running = false;
5589 if (mOutput->stream->get_presentation_position != nullptr) {
5590 uint64_t position = 0;
5591 struct timespec unused;
5592 // The running check restarts the retry counter at least once.
5593 int ret = mOutput->stream->get_presentation_position(
5594 mOutput->stream, &position, &unused);
5595 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
5596 running = true;
5597 mOffloadUnderrunPosition = position;
5598 }
5599 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
5600 (long long)position, (long long)mOffloadUnderrunPosition);
5601 }
5602 if (running) { // still running, give us more time.
5603 track->mRetryCount = kMaxTrackRetriesOffload;
5604 } else {
5605 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5606 track->name());
5607 tracksToRemove->add(track);
5608 // indicate to client process that the track was disabled because of underrun;
5609 // it will then automatically call start() when data is available
5610 track->disable();
5611 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005612 } else if (last){
5613 mixerStatus = MIXER_TRACKS_ENABLED;
5614 }
5615 }
5616 }
5617 // compute volume for this track
5618 processVolume_l(track, last);
5619 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005620
Eric Laurentea0fade2013-10-04 16:23:48 -07005621 // make sure the pause/flush/resume sequence is executed in the right order.
5622 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5623 // before flush and then resume HW. This can happen in case of pause/flush/resume
5624 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07005625 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07005626 mOutput->stream->pause(mOutput->stream);
5627 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005628 if (mFlushPending) {
5629 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005630 }
Eric Laurentfd477972013-10-25 18:10:40 -07005631 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07005632 mOutput->stream->resume(mOutput->stream);
5633 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005634
Eric Laurentbfb1b832013-01-07 09:53:42 -08005635 // remove all the tracks that need to be...
5636 removeTracks_l(*tracksToRemove);
5637
5638 return mixerStatus;
5639}
5640
Eric Laurentbfb1b832013-01-07 09:53:42 -08005641// must be called with thread mutex locked
5642bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5643{
Eric Laurent3b4529e2013-09-05 18:09:19 -07005644 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5645 mWriteAckSequence, mDrainSequence);
5646 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005647 return true;
5648 }
5649 return false;
5650}
5651
Eric Laurentbfb1b832013-01-07 09:53:42 -08005652bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5653{
5654 Mutex::Autolock _l(mLock);
5655 return waitingAsyncCallback_l();
5656}
5657
5658void AudioFlinger::OffloadThread::flushHw_l()
5659{
Eric Laurente659ef42014-09-29 13:06:46 -07005660 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005661 // Flush anything still waiting in the mixbuffer
5662 mCurrentWriteLength = 0;
5663 mBytesRemaining = 0;
5664 mPausedWriteLength = 0;
5665 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07005666 // reset bytes written count to reflect that DSP buffers are empty after flush.
5667 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07005668 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08005669
Eric Laurentbfb1b832013-01-07 09:53:42 -08005670 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005671 // discard any pending drain or write ack by incrementing sequence
5672 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5673 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005674 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005675 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5676 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005677 }
5678}
5679
Haynes Mathew George05317d22016-05-03 16:34:26 -07005680void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
5681{
5682 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07005683 if (PlaybackThread::invalidateTracks_l(streamType)) {
5684 mFlushPending = true;
5685 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07005686}
5687
Eric Laurentbfb1b832013-01-07 09:53:42 -08005688// ----------------------------------------------------------------------------
5689
Eric Laurent81784c32012-11-19 14:55:58 -08005690AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005691 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005692 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07005693 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08005694 mWaitTimeMs(UINT_MAX)
5695{
5696 addOutputTrack(mainThread);
5697}
5698
5699AudioFlinger::DuplicatingThread::~DuplicatingThread()
5700{
5701 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5702 mOutputTracks[i]->destroy();
5703 }
5704}
5705
5706void AudioFlinger::DuplicatingThread::threadLoop_mix()
5707{
5708 // mix buffers...
5709 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08005710 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08005711 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005712 if (mMixerBufferValid) {
5713 memset(mMixerBuffer, 0, mMixerBufferSize);
5714 } else {
5715 memset(mSinkBuffer, 0, mSinkBufferSize);
5716 }
Eric Laurent81784c32012-11-19 14:55:58 -08005717 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005718 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005719 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005720 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005721 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005722}
5723
5724void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5725{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005726 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005727 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005728 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005729 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005730 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005731 }
5732 } else if (mBytesWritten != 0) {
5733 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5734 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005735 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005736 } else {
5737 // flush remaining overflow buffers in output tracks
5738 writeFrames = 0;
5739 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005740 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005741 }
5742}
5743
Eric Laurentbfb1b832013-01-07 09:53:42 -08005744ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005745{
5746 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005747 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005748 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005749 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005750 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005751}
5752
5753void AudioFlinger::DuplicatingThread::threadLoop_standby()
5754{
5755 // DuplicatingThread implements standby by stopping all tracks
5756 for (size_t i = 0; i < outputTracks.size(); i++) {
5757 outputTracks[i]->stop();
5758 }
5759}
5760
5761void AudioFlinger::DuplicatingThread::saveOutputTracks()
5762{
5763 outputTracks = mOutputTracks;
5764}
5765
5766void AudioFlinger::DuplicatingThread::clearOutputTracks()
5767{
5768 outputTracks.clear();
5769}
5770
5771void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5772{
5773 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005774 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5775 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5776 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5777 const size_t frameCount =
5778 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5779 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5780 // from different OutputTracks and their associated MixerThreads (e.g. one may
5781 // nearly empty and the other may be dropping data).
5782
5783 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005784 this,
5785 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005786 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005787 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005788 frameCount,
5789 IPCThreadState::self()->getCallingUid());
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07005790 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
5791 if (status != NO_ERROR) {
5792 ALOGE("addOutputTrack() initCheck failed %d", status);
5793 return;
Eric Laurent81784c32012-11-19 14:55:58 -08005794 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07005795 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
5796 mOutputTracks.add(outputTrack);
5797 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
5798 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005799}
5800
5801void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5802{
5803 Mutex::Autolock _l(mLock);
5804 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5805 if (mOutputTracks[i]->thread() == thread) {
5806 mOutputTracks[i]->destroy();
5807 mOutputTracks.removeAt(i);
5808 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07005809 if (thread->getOutput() == mOutput) {
5810 mOutput = NULL;
5811 }
Eric Laurent81784c32012-11-19 14:55:58 -08005812 return;
5813 }
5814 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07005815 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005816}
5817
5818// caller must hold mLock
5819void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5820{
5821 mWaitTimeMs = UINT_MAX;
5822 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5823 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5824 if (strong != 0) {
5825 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5826 if (waitTimeMs < mWaitTimeMs) {
5827 mWaitTimeMs = waitTimeMs;
5828 }
5829 }
5830 }
5831}
5832
5833
5834bool AudioFlinger::DuplicatingThread::outputsReady(
5835 const SortedVector< sp<OutputTrack> > &outputTracks)
5836{
5837 for (size_t i = 0; i < outputTracks.size(); i++) {
5838 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5839 if (thread == 0) {
5840 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5841 outputTracks[i].get());
5842 return false;
5843 }
5844 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5845 // see note at standby() declaration
5846 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5847 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5848 thread.get());
5849 return false;
5850 }
5851 }
5852 return true;
5853}
5854
5855uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5856{
5857 return (mWaitTimeMs * 1000) / 2;
5858}
5859
5860void AudioFlinger::DuplicatingThread::cacheParameters_l()
5861{
5862 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5863 updateWaitTime_l();
5864
5865 MixerThread::cacheParameters_l();
5866}
5867
5868// ----------------------------------------------------------------------------
5869// Record
5870// ----------------------------------------------------------------------------
5871
5872AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5873 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005874 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005875 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07005876 audio_devices_t inDevice,
5877 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08005878#ifdef TEE_SINK
5879 , const sp<NBAIO_Sink>& teeSink
5880#endif
5881 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07005882 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005883 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07005884 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005885 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005886#ifdef TEE_SINK
5887 , mTeeSink(teeSink)
5888#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005889 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5890 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005891 // mFastCapture below
5892 , mFastCaptureFutex(0)
5893 // mInputSource
5894 // mPipeSink
5895 // mPipeSource
5896 , mPipeFramesP2(0)
5897 // mPipeMemory
5898 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005899 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005900{
Glenn Kastend7dca052015-03-05 16:05:54 -08005901 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5902 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08005903
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005904 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005905
5906 // create an NBAIO source for the HAL input stream, and negotiate
5907 mInputSource = new AudioStreamInSource(input->stream);
5908 size_t numCounterOffers = 0;
5909 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005910#if !LOG_NDEBUG
5911 ssize_t index =
5912#else
5913 (void)
5914#endif
5915 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005916 ALOG_ASSERT(index == 0);
5917
5918 // initialize fast capture depending on configuration
5919 bool initFastCapture;
5920 switch (kUseFastCapture) {
5921 case FastCapture_Never:
5922 initFastCapture = false;
5923 break;
5924 case FastCapture_Always:
5925 initFastCapture = true;
5926 break;
5927 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07005928 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005929 break;
5930 // case FastCapture_Dynamic:
5931 }
5932
5933 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07005934 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005935 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07005936 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
5937 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005938 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5939 void *pipeBuffer;
5940 const sp<MemoryDealer> roHeap(readOnlyHeap());
5941 sp<IMemory> pipeMemory;
5942 if ((roHeap == 0) ||
5943 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5944 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5945 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5946 goto failed;
5947 }
5948 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5949 memset(pipeBuffer, 0, pipeSize);
5950 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5951 const NBAIO_Format offers[1] = {format};
5952 size_t numCounterOffers = 0;
5953 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5954 ALOG_ASSERT(index == 0);
5955 mPipeSink = pipe;
5956 PipeReader *pipeReader = new PipeReader(*pipe);
5957 numCounterOffers = 0;
5958 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5959 ALOG_ASSERT(index == 0);
5960 mPipeSource = pipeReader;
5961 mPipeFramesP2 = pipeFramesP2;
5962 mPipeMemory = pipeMemory;
5963
5964 // create fast capture
5965 mFastCapture = new FastCapture();
5966 FastCaptureStateQueue *sq = mFastCapture->sq();
5967#ifdef STATE_QUEUE_DUMP
5968 // FIXME
5969#endif
5970 FastCaptureState *state = sq->begin();
5971 state->mCblk = NULL;
5972 state->mInputSource = mInputSource.get();
5973 state->mInputSourceGen++;
5974 state->mPipeSink = pipe;
5975 state->mPipeSinkGen++;
5976 state->mFrameCount = mFrameCount;
5977 state->mCommand = FastCaptureState::COLD_IDLE;
5978 // already done in constructor initialization list
5979 //mFastCaptureFutex = 0;
5980 state->mColdFutexAddr = &mFastCaptureFutex;
5981 state->mColdGen++;
5982 state->mDumpState = &mFastCaptureDumpState;
5983#ifdef TEE_SINK
5984 // FIXME
5985#endif
5986 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
5987 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
5988 sq->end();
5989 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5990
5991 // start the fast capture
5992 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
5993 pid_t tid = mFastCapture->getTid();
Glenn Kasten8379b722016-03-18 14:54:17 -07005994 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005995#ifdef AUDIO_WATCHDOG
5996 // FIXME
5997#endif
5998
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005999 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006000 }
6001failed: ;
6002
6003 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08006004}
6005
Eric Laurent81784c32012-11-19 14:55:58 -08006006AudioFlinger::RecordThread::~RecordThread()
6007{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006008 if (mFastCapture != 0) {
6009 FastCaptureStateQueue *sq = mFastCapture->sq();
6010 FastCaptureState *state = sq->begin();
6011 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6012 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6013 if (old == -1) {
6014 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6015 }
6016 }
6017 state->mCommand = FastCaptureState::EXIT;
6018 sq->end();
6019 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6020 mFastCapture->join();
6021 mFastCapture.clear();
6022 }
6023 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07006024 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07006025 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08006026}
6027
6028void AudioFlinger::RecordThread::onFirstRef()
6029{
Glenn Kastend7dca052015-03-05 16:05:54 -08006030 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08006031}
6032
Eric Laurent81784c32012-11-19 14:55:58 -08006033bool AudioFlinger::RecordThread::threadLoop()
6034{
Eric Laurent81784c32012-11-19 14:55:58 -08006035 nsecs_t lastWarning = 0;
6036
6037 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006038
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006039reacquire_wakelock:
6040 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08006041 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006042 {
6043 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006044 size_t size = mActiveTracks.size();
6045 activeTracksGen = mActiveTracksGen;
6046 if (size > 0) {
6047 // FIXME an arbitrary choice
6048 activeTrack = mActiveTracks[0];
6049 acquireWakeLock_l(activeTrack->uid());
6050 if (size > 1) {
6051 SortedVector<int> tmp;
6052 for (size_t i = 0; i < size; i++) {
6053 tmp.add(mActiveTracks[i]->uid());
6054 }
6055 updateWakeLockUids_l(tmp);
6056 }
6057 } else {
6058 acquireWakeLock_l(-1);
6059 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006060 }
6061
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006062 // used to request a deferred sleep, to be executed later while mutex is unlocked
6063 uint32_t sleepUs = 0;
6064
6065 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006066 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006067 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07006068
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006069 // activeTracks accumulates a copy of a subset of mActiveTracks
6070 Vector< sp<RecordTrack> > activeTracks;
6071
Glenn Kasten735f45f2014-08-18 15:51:59 -07006072 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006073 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07006074
Glenn Kasten735f45f2014-08-18 15:51:59 -07006075 // reference to a fast track which is about to be removed
6076 sp<RecordTrack> fastTrackToRemove;
6077
Eric Laurent81784c32012-11-19 14:55:58 -08006078 { // scope for mLock
6079 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08006080
Eric Laurent021cf962014-05-13 10:18:14 -07006081 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006082
Eric Laurent000a4192014-01-29 15:17:32 -08006083 // check exitPending here because checkForNewParameters_l() and
6084 // checkForNewParameters_l() can temporarily release mLock
6085 if (exitPending()) {
6086 break;
6087 }
6088
Eric Laurent5c25d562016-07-13 17:17:45 -07006089 // sleep with mutex unlocked
6090 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07006091 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07006092 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
6093 ATRACE_END();
6094 sleepUs = 0;
6095 continue;
6096 }
6097
Glenn Kasten2b806402013-11-20 16:37:38 -08006098 // if no active track(s), then standby and release wakelock
6099 size_t size = mActiveTracks.size();
6100 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07006101 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006102 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08006103 releaseWakeLock_l();
6104 ALOGV("RecordThread: loop stopping");
6105 // go to sleep
6106 mWaitWorkCV.wait(mLock);
6107 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006108 goto reacquire_wakelock;
6109 }
6110
Glenn Kasten2b806402013-11-20 16:37:38 -08006111 if (mActiveTracksGen != activeTracksGen) {
6112 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006113 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08006114 for (size_t i = 0; i < size; i++) {
6115 tmp.add(mActiveTracks[i]->uid());
6116 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006117 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08006118 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006119
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006120 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07006121 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006122 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07006123
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006124 activeTrack = mActiveTracks[i];
6125 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07006126 if (activeTrack->isFastTrack()) {
6127 ALOG_ASSERT(fastTrackToRemove == 0);
6128 fastTrackToRemove = activeTrack;
6129 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006130 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08006131 mActiveTracks.remove(activeTrack);
6132 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006133 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07006134 continue;
6135 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006136
6137 TrackBase::track_state activeTrackState = activeTrack->mState;
6138 switch (activeTrackState) {
6139
6140 case TrackBase::PAUSING:
6141 mActiveTracks.remove(activeTrack);
6142 mActiveTracksGen++;
6143 doBroadcast = true;
6144 size--;
6145 continue;
6146
6147 case TrackBase::STARTING_1:
6148 sleepUs = 10000;
6149 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07006150 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006151 continue;
6152
6153 case TrackBase::STARTING_2:
6154 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006155 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07006156 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07006157 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006158 break;
6159
6160 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07006161 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006162 break;
6163
6164 case TrackBase::IDLE:
6165 i++;
6166 continue;
6167
6168 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08006169 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07006170 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006171
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006172 activeTracks.add(activeTrack);
6173 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07006174
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006175 if (activeTrack->isFastTrack()) {
6176 ALOG_ASSERT(!mFastTrackAvail);
6177 ALOG_ASSERT(fastTrack == 0);
6178 fastTrack = activeTrack;
6179 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006180 }
Eric Laurent5c25d562016-07-13 17:17:45 -07006181
6182 if (allStopped) {
6183 standbyIfNotAlreadyInStandby();
6184 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006185 if (doBroadcast) {
6186 mStartStopCond.broadcast();
6187 }
6188
6189 // sleep if there are no active tracks to process
6190 if (activeTracks.size() == 0) {
6191 if (sleepUs == 0) {
6192 sleepUs = kRecordThreadSleepUs;
6193 }
6194 continue;
6195 }
6196 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07006197
Eric Laurent81784c32012-11-19 14:55:58 -08006198 lockEffectChains_l(effectChains);
6199 }
6200
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006201 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07006202
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006203 size_t size = effectChains.size();
6204 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006205 // thread mutex is not locked, but effect chain is locked
6206 effectChains[i]->process_l();
6207 }
6208
Glenn Kasten735f45f2014-08-18 15:51:59 -07006209 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006210 if (mFastCapture != 0) {
6211 FastCaptureStateQueue *sq = mFastCapture->sq();
6212 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07006213 bool didModify = false;
6214 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006215 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
6216 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
6217 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6218 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6219 if (old == -1) {
6220 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6221 }
6222 }
6223 state->mCommand = FastCaptureState::READ_WRITE;
6224#if 0 // FIXME
6225 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08006226 FastThreadDumpState::kSamplingNforLowRamDevice :
6227 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006228#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07006229 didModify = true;
6230 }
6231 audio_track_cblk_t *cblkOld = state->mCblk;
6232 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
6233 if (cblkNew != cblkOld) {
6234 state->mCblk = cblkNew;
6235 // block until acked if removing a fast track
6236 if (cblkOld != NULL) {
6237 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
6238 }
6239 didModify = true;
6240 }
6241 sq->end(didModify);
6242 if (didModify) {
6243 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006244#if 0
6245 if (kUseFastCapture == FastCapture_Dynamic) {
6246 mNormalSource = mPipeSource;
6247 }
6248#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006249 }
6250 }
6251
Glenn Kasten735f45f2014-08-18 15:51:59 -07006252 // now run the fast track destructor with thread mutex unlocked
6253 fastTrackToRemove.clear();
6254
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006255 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
6256 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
6257 // slow, then this RecordThread will overrun by not calling HAL read often enough.
6258 // If destination is non-contiguous, first read past the nominal end of buffer, then
6259 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006260
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006261 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006262 ssize_t framesRead;
6263
6264 // If an NBAIO source is present, use it to read the normal capture's data
6265 if (mPipeSource != 0) {
6266 size_t framesToRead = mBufferSize / mFrameSize;
Glenn Kasten1b291842016-07-18 14:55:21 -07006267 framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hung57446612015-04-19 23:56:46 -07006268 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
Glenn Kastend79072e2016-01-06 08:41:20 -08006269 framesToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07006270 // since pipe is non-blocking, simulate blocking input by waiting for 1/2 of
6271 // buffer size or at least for 20ms.
6272 size_t sleepFrames = max(
6273 min(mPipeFramesP2, mRsmpInFramesP2) / 2, FMS_20 * mSampleRate / 1000);
6274 if (framesRead <= (ssize_t) sleepFrames) {
6275 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
6276 }
6277 if (framesRead < 0) {
6278 status_t status = (status_t) framesRead;
6279 switch (status) {
6280 case OVERRUN:
6281 ALOGW("overrun on read from pipe");
6282 framesRead = 0;
6283 break;
6284 case NEGOTIATE:
6285 ALOGE("re-negotiation is needed");
6286 framesRead = -1; // Will cause an attempt to recover.
6287 break;
6288 default:
6289 ALOGE("unknown error %d on read from pipe", status);
6290 break;
6291 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006292 }
6293 // otherwise use the HAL / AudioStreamIn directly
6294 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07006295 ATRACE_BEGIN("read");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006296 ssize_t bytesRead = mInput->stream->read(mInput->stream,
Andy Hung57446612015-04-19 23:56:46 -07006297 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize);
Glenn Kastenec6a7032016-03-14 07:40:23 -07006298 ATRACE_END();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006299 if (bytesRead < 0) {
6300 framesRead = bytesRead;
6301 } else {
6302 framesRead = bytesRead / mFrameSize;
6303 }
6304 }
6305
Andy Hung3f0c9022016-01-15 17:49:46 -08006306 // Update server timestamp with server stats
6307 // systemTime() is optional if the hardware supports timestamps.
6308 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
6309 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6310
6311 // Update server timestamp with kernel stats
Andy Hung69ce44d2016-07-18 12:14:25 -07006312 if (mInput->stream->get_capture_position != nullptr
6313 && mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08006314 int64_t position, time;
6315 int ret = mInput->stream->get_capture_position(mInput->stream, &position, &time);
6316 if (ret == NO_ERROR) {
6317 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
6318 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
6319 // Note: In general record buffers should tend to be empty in
6320 // a properly running pipeline.
6321 //
6322 // Also, it is not advantageous to call get_presentation_position during the read
6323 // as the read obtains a lock, preventing the timestamp call from executing.
6324 }
6325 }
6326 // Use this to track timestamp information
6327 // ALOGD("%s", mTimestamp.toString().c_str());
6328
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006329 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006330 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006331 // Force input into standby so that it tries to recover at next read attempt
6332 inputStandBy();
6333 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006334 }
6335 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006336 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006337 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006338 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006339
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006340 if (mTeeSink != 0) {
Andy Hung57446612015-04-19 23:56:46 -07006341 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006342 }
6343 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006344 {
6345 size_t part1 = mRsmpInFramesP2 - rear;
6346 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07006347 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006348 (framesRead - part1) * mFrameSize);
6349 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006350 }
6351 rear = mRsmpInRear += framesRead;
6352
6353 size = activeTracks.size();
6354 // loop over each active track
6355 for (size_t i = 0; i < size; i++) {
6356 activeTrack = activeTracks[i];
6357
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006358 // skip fast tracks, as those are handled directly by FastCapture
6359 if (activeTrack->isFastTrack()) {
6360 continue;
6361 }
6362
Andy Hung73c02e42015-03-29 01:13:58 -07006363 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07006364 // TODO: Update the activeTrack buffer converter in case of reconfigure.
6365
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006366 enum {
6367 OVERRUN_UNKNOWN,
6368 OVERRUN_TRUE,
6369 OVERRUN_FALSE
6370 } overrun = OVERRUN_UNKNOWN;
6371
6372 // loop over getNextBuffer to handle circular sink
6373 for (;;) {
6374
6375 activeTrack->mSink.frameCount = ~0;
6376 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
6377 size_t framesOut = activeTrack->mSink.frameCount;
6378 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
6379
Andy Hung73c02e42015-03-29 01:13:58 -07006380 // check available frames and handle overrun conditions
6381 // if the record track isn't draining fast enough.
6382 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006383 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07006384 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
6385 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006386 overrun = OVERRUN_TRUE;
6387 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006388 if (framesOut == 0 || framesIn == 0) {
6389 break;
6390 }
6391
Andy Hung6770c6f2015-04-07 13:43:36 -07006392 // Don't allow framesOut to be larger than what is possible with resampling
6393 // from framesIn.
6394 // This isn't strictly necessary but helps limit buffer resizing in
6395 // RecordBufferConverter. TODO: remove when no longer needed.
6396 framesOut = min(framesOut,
6397 destinationFramesPossible(
6398 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07006399 // process frames from the RecordThread buffer provider to the RecordTrack buffer
6400 framesOut = activeTrack->mRecordBufferConverter->convert(
6401 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006402
6403 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
6404 overrun = OVERRUN_FALSE;
6405 }
6406
6407 if (activeTrack->mFramesToDrop == 0) {
6408 if (framesOut > 0) {
6409 activeTrack->mSink.frameCount = framesOut;
6410 activeTrack->releaseBuffer(&activeTrack->mSink);
6411 }
6412 } else {
6413 // FIXME could do a partial drop of framesOut
6414 if (activeTrack->mFramesToDrop > 0) {
6415 activeTrack->mFramesToDrop -= framesOut;
6416 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006417 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006418 }
6419 } else {
6420 activeTrack->mFramesToDrop += framesOut;
6421 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
6422 activeTrack->mSyncStartEvent->isCancelled()) {
6423 ALOGW("Synced record %s, session %d, trigger session %d",
6424 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
6425 activeTrack->sessionId(),
6426 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08006427 activeTrack->mSyncStartEvent->triggerSession() :
6428 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006429 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006430 }
6431 }
6432 }
6433
6434 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006435 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006436 }
6437 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006438
6439 switch (overrun) {
6440 case OVERRUN_TRUE:
6441 // client isn't retrieving buffers fast enough
6442 if (!activeTrack->setOverflow()) {
6443 nsecs_t now = systemTime();
6444 // FIXME should lastWarning per track?
6445 if ((now - lastWarning) > kWarningThrottleNs) {
6446 ALOGW("RecordThread: buffer overflow");
6447 lastWarning = now;
6448 }
6449 }
6450 break;
6451 case OVERRUN_FALSE:
6452 activeTrack->clearOverflow();
6453 break;
6454 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006455 break;
6456 }
6457
Andy Hung3f0c9022016-01-15 17:49:46 -08006458 // update frame information and push timestamp out
6459 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08006460 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08006461 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
6462 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006463 }
6464
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006465unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08006466 // enable changes in effect chain
6467 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006468 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08006469 }
6470
Glenn Kasten93e471f2013-08-19 08:40:07 -07006471 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08006472
6473 {
6474 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07006475 for (size_t i = 0; i < mTracks.size(); i++) {
6476 sp<RecordTrack> track = mTracks[i];
6477 track->invalidate();
6478 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006479 mActiveTracks.clear();
6480 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08006481 mStartStopCond.broadcast();
6482 }
6483
6484 releaseWakeLock();
6485
6486 ALOGV("RecordThread %p exiting", this);
6487 return false;
6488}
6489
Glenn Kasten93e471f2013-08-19 08:40:07 -07006490void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08006491{
6492 if (!mStandby) {
6493 inputStandBy();
6494 mStandby = true;
6495 }
6496}
6497
6498void AudioFlinger::RecordThread::inputStandBy()
6499{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006500 // Idle the fast capture if it's currently running
6501 if (mFastCapture != 0) {
6502 FastCaptureStateQueue *sq = mFastCapture->sq();
6503 FastCaptureState *state = sq->begin();
6504 if (!(state->mCommand & FastCaptureState::IDLE)) {
6505 state->mCommand = FastCaptureState::COLD_IDLE;
6506 state->mColdFutexAddr = &mFastCaptureFutex;
6507 state->mColdGen++;
6508 mFastCaptureFutex = 0;
6509 sq->end();
6510 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
6511 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
6512#if 0
6513 if (kUseFastCapture == FastCapture_Dynamic) {
6514 // FIXME
6515 }
6516#endif
6517#ifdef AUDIO_WATCHDOG
6518 // FIXME
6519#endif
6520 } else {
6521 sq->end(false /*didModify*/);
6522 }
6523 }
Eric Laurent81784c32012-11-19 14:55:58 -08006524 mInput->stream->common.standby(&mInput->stream->common);
Andy Hungad6d52d2016-07-18 13:42:03 -07006525
6526 // If going into standby, flush the pipe source.
6527 if (mPipeSource.get() != nullptr) {
6528 const ssize_t flushed = mPipeSource->flush();
6529 if (flushed > 0) {
6530 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
6531 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
6532 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6533 }
6534 }
Eric Laurent81784c32012-11-19 14:55:58 -08006535}
6536
Glenn Kasten05997e22014-03-13 15:08:33 -07006537// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07006538sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08006539 const sp<AudioFlinger::Client>& client,
6540 uint32_t sampleRate,
6541 audio_format_t format,
6542 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08006543 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08006544 audio_session_t sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07006545 size_t *notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006546 int uid,
Eric Laurent05067782016-06-01 18:27:28 -07006547 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08006548 pid_t tid,
6549 status_t *status)
6550{
Glenn Kasten74935e42013-12-19 08:56:45 -08006551 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08006552 sp<RecordTrack> track;
6553 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07006554 audio_input_flags_t inputFlags = mInput->flags;
6555
6556 // special case for FAST flag considered OK if fast capture is present
6557 if (hasFastCapture()) {
6558 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
6559 }
6560
6561 // Check if requested flags are compatible with output stream flags
6562 if ((*flags & inputFlags) != *flags) {
6563 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
6564 " input flags (%08x)",
6565 *flags, inputFlags);
6566 *flags = (audio_input_flags_t)(*flags & inputFlags);
6567 }
Eric Laurent81784c32012-11-19 14:55:58 -08006568
Glenn Kasten90e58b12013-07-31 16:16:02 -07006569 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07006570 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006571 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07006572 // we formerly checked for a callback handler (non-0 tid),
6573 // but that is no longer required for TRANSFER_OBTAIN mode
6574 //
Glenn Kasten74105912014-07-03 12:28:53 -07006575 // frame count is not specified, or is exactly the pipe depth
6576 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006577 // PCM data
6578 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006579 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006580 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006581 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006582 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006583 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07006584 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006585 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006586 hasFastCapture() &&
6587 // there are sufficient fast track slots available
6588 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07006589 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07006590 // check compatibility with audio effects.
6591 Mutex::Autolock _l(mLock);
6592 // Do not accept FAST flag if the session has software effects
6593 sp<EffectChain> chain = getEffectChain_l(sessionId);
6594 if (chain != 0) {
Eric Laurent122f7e72016-06-29 11:53:29 -07006595 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_RAW) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07006596 "AUDIO_INPUT_FLAG_RAW denied: effect present on session");
6597 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_RAW);
6598 if (chain->hasSoftwareEffect()) {
6599 ALOGV("AUDIO_INPUT_FLAG_FAST denied: software effect present on session");
6600 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
6601 }
6602 }
Eric Laurent122f7e72016-06-29 11:53:29 -07006603 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07006604 "AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
6605 frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006606 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006607 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
Glenn Kasten74105912014-07-03 12:28:53 -07006608 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006609 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07006610 frameCount, mFrameCount, mPipeFramesP2,
6611 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
6612 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07006613 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07006614 }
6615 }
6616
6617 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07006618 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07006619 // fast track: frame count is exactly the pipe depth
6620 frameCount = mPipeFramesP2;
6621 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
6622 *notificationFrames = mFrameCount;
6623 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006624 // not fast track: max notification period is resampled equivalent of one HAL buffer time
6625 // or 20 ms if there is a fast capture
6626 // TODO This could be a roundupRatio inline, and const
6627 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
6628 * sampleRate + mSampleRate - 1) / mSampleRate;
6629 // minimum number of notification periods is at least kMinNotifications,
6630 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
6631 static const size_t kMinNotifications = 3;
6632 static const uint32_t kMinMs = 30;
6633 // TODO This could be a roundupRatio inline
6634 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
6635 // TODO This could be a roundupRatio inline
6636 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
6637 maxNotificationFrames;
6638 const size_t minFrameCount = maxNotificationFrames *
6639 max(kMinNotifications, minNotificationsByMs);
6640 frameCount = max(frameCount, minFrameCount);
6641 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
6642 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07006643 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07006644 }
Glenn Kasten74935e42013-12-19 08:56:45 -08006645 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07006646
Glenn Kasten15e57982013-09-24 11:52:37 -07006647 lStatus = initCheck();
6648 if (lStatus != NO_ERROR) {
6649 ALOGE("createRecordTrack_l() audio driver not initialized");
6650 goto Exit;
6651 }
Eric Laurent81784c32012-11-19 14:55:58 -08006652
6653 { // scope for mLock
6654 Mutex::Autolock _l(mLock);
6655
6656 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07006657 format, channelMask, frameCount, NULL, sessionId, uid,
6658 *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08006659
Glenn Kasten03003332013-08-06 15:40:54 -07006660 lStatus = track->initCheck();
6661 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07006662 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08006663 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08006664 goto Exit;
6665 }
6666 mTracks.add(track);
6667
6668 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6669 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6670 mAudioFlinger->btNrecIsOff();
6671 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6672 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006673
Eric Laurent05067782016-06-01 18:27:28 -07006674 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006675 pid_t callingPid = IPCThreadState::self()->getCallingPid();
6676 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
6677 // so ask activity manager to do this on our behalf
6678 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
6679 }
Eric Laurent81784c32012-11-19 14:55:58 -08006680 }
Glenn Kasten05997e22014-03-13 15:08:33 -07006681
Eric Laurent81784c32012-11-19 14:55:58 -08006682 lStatus = NO_ERROR;
6683
6684Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07006685 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08006686 return track;
6687}
6688
6689status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6690 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08006691 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08006692{
6693 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6694 sp<ThreadBase> strongMe = this;
6695 status_t status = NO_ERROR;
6696
6697 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006698 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006699 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006700 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08006701 triggerSession,
6702 recordTrack->sessionId(),
6703 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006704 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08006705 // Sync event can be cancelled by the trigger session if the track is not in a
6706 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006707 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006708 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006709 } else {
6710 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006711 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006712 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08006713 }
6714 }
6715
6716 {
Glenn Kasten47c20702013-08-13 15:37:35 -07006717 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08006718 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006719 if (mActiveTracks.indexOf(recordTrack) >= 0) {
6720 if (recordTrack->mState == TrackBase::PAUSING) {
6721 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006722 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006723 } else {
6724 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08006725 }
6726 return status;
6727 }
6728
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006729 // TODO consider other ways of handling this, such as changing the state to :STARTING and
6730 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6731 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006732 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08006733 mActiveTracks.add(recordTrack);
6734 mActiveTracksGen++;
Eric Laurent83b88082014-06-20 18:31:16 -07006735 status_t status = NO_ERROR;
6736 if (recordTrack->isExternalTrack()) {
6737 mLock.unlock();
Glenn Kastend848eb42016-03-08 13:42:11 -08006738 status = AudioSystem::startInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006739 mLock.lock();
6740 // FIXME should verify that recordTrack is still in mActiveTracks
6741 if (status != NO_ERROR) {
6742 mActiveTracks.remove(recordTrack);
6743 mActiveTracksGen++;
6744 recordTrack->clearSyncStartEvent();
6745 ALOGV("RecordThread::start error %d", status);
6746 return status;
6747 }
Eric Laurent81784c32012-11-19 14:55:58 -08006748 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006749 // Catch up with current buffer indices if thread is already running.
6750 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
6751 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6752 // see previously buffered data before it called start(), but with greater risk of overrun.
6753
Andy Hung73c02e42015-03-29 01:13:58 -07006754 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07006755 // clear any converter state as new data will be discontinuous
6756 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006757 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08006758 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08006759 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08006760 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006761 ALOGV("Record failed to start");
6762 status = BAD_VALUE;
6763 goto startError;
6764 }
Eric Laurent81784c32012-11-19 14:55:58 -08006765 return status;
6766 }
Glenn Kasten7c027242012-12-26 14:43:16 -08006767
Eric Laurent81784c32012-11-19 14:55:58 -08006768startError:
Eric Laurent83b88082014-06-20 18:31:16 -07006769 if (recordTrack->isExternalTrack()) {
Glenn Kastend848eb42016-03-08 13:42:11 -08006770 AudioSystem::stopInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006771 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006772 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006773 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08006774 return status;
6775}
6776
Eric Laurent81784c32012-11-19 14:55:58 -08006777void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6778{
6779 sp<SyncEvent> strongEvent = event.promote();
6780
6781 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08006782 sp<RefBase> ptr = strongEvent->cookie().promote();
6783 if (ptr != 0) {
6784 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6785 recordTrack->handleSyncStartEvent(strongEvent);
6786 }
Eric Laurent81784c32012-11-19 14:55:58 -08006787 }
6788}
6789
Glenn Kastena8356f62013-07-25 14:37:52 -07006790bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08006791 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07006792 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006793 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08006794 return false;
6795 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006796 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006797 recordTrack->mState = TrackBase::PAUSING;
Eric Laurent5c25d562016-07-13 17:17:45 -07006798 // signal thread to stop
6799 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08006800 // do not wait for mStartStopCond if exiting
6801 if (exitPending()) {
6802 return true;
6803 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006804 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08006805 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006806 // if we have been restarted, recordTrack is in mActiveTracks here
6807 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006808 ALOGV("Record stopped OK");
6809 return true;
6810 }
6811 return false;
6812}
6813
Glenn Kasten0f11b512014-01-31 16:18:54 -08006814bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08006815{
6816 return false;
6817}
6818
Glenn Kasten0f11b512014-01-31 16:18:54 -08006819status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006820{
6821#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6822 if (!isValidSyncEvent(event)) {
6823 return BAD_VALUE;
6824 }
6825
Glenn Kastend848eb42016-03-08 13:42:11 -08006826 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08006827 status_t ret = NAME_NOT_FOUND;
6828
6829 Mutex::Autolock _l(mLock);
6830
6831 for (size_t i = 0; i < mTracks.size(); i++) {
6832 sp<RecordTrack> track = mTracks[i];
6833 if (eventSession == track->sessionId()) {
6834 (void) track->setSyncEvent(event);
6835 ret = NO_ERROR;
6836 }
6837 }
6838 return ret;
6839#else
6840 return BAD_VALUE;
6841#endif
6842}
6843
6844// destroyTrack_l() must be called with ThreadBase::mLock held
6845void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6846{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006847 track->terminate();
6848 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006849 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006850 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006851 removeTrack_l(track);
6852 }
6853}
6854
6855void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6856{
6857 mTracks.remove(track);
6858 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006859 if (track->isFastTrack()) {
6860 ALOG_ASSERT(!mFastTrackAvail);
6861 mFastTrackAvail = true;
6862 }
Eric Laurent81784c32012-11-19 14:55:58 -08006863}
6864
6865void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6866{
6867 dumpInternals(fd, args);
6868 dumpTracks(fd, args);
6869 dumpEffectChains(fd, args);
6870}
6871
6872void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6873{
Elliott Hughes87cebad2014-05-22 10:14:43 -07006874 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08006875
Glenn Kasten44182c22015-03-05 17:12:23 -08006876 dumpBase(fd, args);
6877
6878 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006879 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006880 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006881 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006882 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08006883
Glenn Kasten2f90c512015-12-02 11:40:09 -08006884 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
6885 // while we are dumping it. It may be inconsistent, but it won't mutate!
6886 // This is a large object so we place it on the heap.
6887 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
6888 const FastCaptureDumpState *copy = new FastCaptureDumpState(mFastCaptureDumpState);
6889 copy->dump(fd);
6890 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08006891}
6892
Glenn Kasten0f11b512014-01-31 16:18:54 -08006893void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006894{
6895 const size_t SIZE = 256;
6896 char buffer[SIZE];
6897 String8 result;
6898
Marco Nelissenb2208842014-02-07 14:00:50 -08006899 size_t numtracks = mTracks.size();
6900 size_t numactive = mActiveTracks.size();
6901 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006902 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006903 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006904 dprintf(fd, " of which %zu are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006905 RecordTrack::appendDumpHeader(result);
6906 for (size_t i = 0; i < numtracks ; ++i) {
6907 sp<RecordTrack> track = mTracks[i];
6908 if (track != 0) {
6909 bool active = mActiveTracks.indexOf(track) >= 0;
6910 if (active) {
6911 numactiveseen++;
6912 }
6913 track->dump(buffer, SIZE, active);
6914 result.append(buffer);
6915 }
Eric Laurent81784c32012-11-19 14:55:58 -08006916 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006917 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006918 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006919 }
6920
Marco Nelissenb2208842014-02-07 14:00:50 -08006921 if (numactiveseen != numactive) {
6922 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6923 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006924 result.append(buffer);
6925 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006926 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006927 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006928 if (mTracks.indexOf(track) < 0) {
6929 track->dump(buffer, SIZE, true);
6930 result.append(buffer);
6931 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006932 }
Eric Laurent81784c32012-11-19 14:55:58 -08006933
6934 }
6935 write(fd, result.string(), result.size());
6936}
6937
Andy Hung73c02e42015-03-29 01:13:58 -07006938
6939void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
6940{
6941 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6942 RecordThread *recordThread = (RecordThread *) threadBase.get();
6943 mRsmpInFront = recordThread->mRsmpInRear;
6944 mRsmpInUnrel = 0;
6945}
6946
6947void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
6948 size_t *framesAvailable, bool *hasOverrun)
6949{
6950 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6951 RecordThread *recordThread = (RecordThread *) threadBase.get();
6952 const int32_t rear = recordThread->mRsmpInRear;
6953 const int32_t front = mRsmpInFront;
6954 const ssize_t filled = rear - front;
6955
6956 size_t framesIn;
6957 bool overrun = false;
6958 if (filled < 0) {
6959 // should not happen, but treat like a massive overrun and re-sync
6960 framesIn = 0;
6961 mRsmpInFront = rear;
6962 overrun = true;
6963 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
6964 framesIn = (size_t) filled;
6965 } else {
6966 // client is not keeping up with server, but give it latest data
6967 framesIn = recordThread->mRsmpInFrames;
6968 mRsmpInFront = /* front = */ rear - framesIn;
6969 overrun = true;
6970 }
6971 if (framesAvailable != NULL) {
6972 *framesAvailable = framesIn;
6973 }
6974 if (hasOverrun != NULL) {
6975 *hasOverrun = overrun;
6976 }
6977}
6978
Eric Laurent81784c32012-11-19 14:55:58 -08006979// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006980status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08006981 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006982{
Andy Hung73c02e42015-03-29 01:13:58 -07006983 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006984 if (threadBase == 0) {
6985 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006986 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006987 return NOT_ENOUGH_DATA;
6988 }
6989 RecordThread *recordThread = (RecordThread *) threadBase.get();
6990 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07006991 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07006992 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006993 // FIXME should not be P2 (don't want to increase latency)
6994 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006995 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07006996 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006997 front &= recordThread->mRsmpInFramesP2 - 1;
6998 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07006999 if (part1 > (size_t) filled) {
7000 part1 = filled;
7001 }
7002 size_t ask = buffer->frameCount;
7003 ALOG_ASSERT(ask > 0);
7004 if (part1 > ask) {
7005 part1 = ask;
7006 }
7007 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07007008 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07007009 buffer->raw = NULL;
7010 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07007011 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07007012 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08007013 }
7014
Andy Hung57446612015-04-19 23:56:46 -07007015 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07007016 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07007017 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08007018 return NO_ERROR;
7019}
7020
7021// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007022void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
7023 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08007024{
Glenn Kasten85948432013-08-19 12:09:05 -07007025 size_t stepCount = buffer->frameCount;
7026 if (stepCount == 0) {
7027 return;
7028 }
Andy Hung73c02e42015-03-29 01:13:58 -07007029 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
7030 mRsmpInUnrel -= stepCount;
7031 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07007032 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08007033 buffer->frameCount = 0;
7034}
7035
Andy Hung97a893e2015-03-29 01:03:07 -07007036AudioFlinger::RecordThread::RecordBufferConverter::RecordBufferConverter(
7037 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
7038 uint32_t srcSampleRate,
7039 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
7040 uint32_t dstSampleRate) :
7041 mSrcChannelMask(AUDIO_CHANNEL_INVALID), // updateParameters will set following vars
7042 // mSrcFormat
7043 // mSrcSampleRate
7044 // mDstChannelMask
7045 // mDstFormat
7046 // mDstSampleRate
7047 // mSrcChannelCount
7048 // mDstChannelCount
7049 // mDstFrameSize
7050 mBuf(NULL), mBufFrames(0), mBufFrameSize(0),
Andy Hungd330ee42015-04-20 13:23:41 -07007051 mResampler(NULL),
7052 mIsLegacyDownmix(false),
7053 mIsLegacyUpmix(false),
7054 mRequiresFloat(false),
7055 mInputConverterProvider(NULL)
Andy Hung97a893e2015-03-29 01:03:07 -07007056{
7057 (void)updateParameters(srcChannelMask, srcFormat, srcSampleRate,
7058 dstChannelMask, dstFormat, dstSampleRate);
7059}
7060
7061AudioFlinger::RecordThread::RecordBufferConverter::~RecordBufferConverter() {
7062 free(mBuf);
7063 delete mResampler;
Andy Hungd330ee42015-04-20 13:23:41 -07007064 delete mInputConverterProvider;
Andy Hung97a893e2015-03-29 01:03:07 -07007065}
7066
7067size_t AudioFlinger::RecordThread::RecordBufferConverter::convert(void *dst,
7068 AudioBufferProvider *provider, size_t frames)
7069{
Andy Hungd330ee42015-04-20 13:23:41 -07007070 if (mInputConverterProvider != NULL) {
7071 mInputConverterProvider->setBufferProvider(provider);
7072 provider = mInputConverterProvider;
7073 }
7074
7075 if (mResampler == NULL) {
Andy Hung97a893e2015-03-29 01:03:07 -07007076 ALOGVV("NO RESAMPLING sampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
7077 mSrcSampleRate, mSrcFormat, mDstFormat);
7078
7079 AudioBufferProvider::Buffer buffer;
7080 for (size_t i = frames; i > 0; ) {
7081 buffer.frameCount = i;
Glenn Kastend79072e2016-01-06 08:41:20 -08007082 status_t status = provider->getNextBuffer(&buffer);
Andy Hung97a893e2015-03-29 01:03:07 -07007083 if (status != OK || buffer.frameCount == 0) {
7084 frames -= i; // cannot fill request.
7085 break;
7086 }
Andy Hungd330ee42015-04-20 13:23:41 -07007087 // format convert to destination buffer
7088 convertNoResampler(dst, buffer.raw, buffer.frameCount);
Andy Hung97a893e2015-03-29 01:03:07 -07007089
7090 dst = (int8_t*)dst + buffer.frameCount * mDstFrameSize;
7091 i -= buffer.frameCount;
7092 provider->releaseBuffer(&buffer);
7093 }
7094 } else {
7095 ALOGVV("RESAMPLING mSrcSampleRate:%u mDstSampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
7096 mSrcSampleRate, mDstSampleRate, mSrcFormat, mDstFormat);
7097
Andy Hungd330ee42015-04-20 13:23:41 -07007098 // reallocate buffer if needed
7099 if (mBufFrameSize != 0 && mBufFrames < frames) {
7100 free(mBuf);
7101 mBufFrames = frames;
7102 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
7103 }
Andy Hung97a893e2015-03-29 01:03:07 -07007104 // resampler accumulates, but we only have one source track
Andy Hungd330ee42015-04-20 13:23:41 -07007105 memset(mBuf, 0, frames * mBufFrameSize);
7106 frames = mResampler->resample((int32_t*)mBuf, frames, provider);
7107 // format convert to destination buffer
7108 convertResampler(dst, mBuf, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07007109 }
7110 return frames;
7111}
7112
7113status_t AudioFlinger::RecordThread::RecordBufferConverter::updateParameters(
7114 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
7115 uint32_t srcSampleRate,
7116 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
7117 uint32_t dstSampleRate)
7118{
7119 // quick evaluation if there is any change.
7120 if (mSrcFormat == srcFormat
7121 && mSrcChannelMask == srcChannelMask
7122 && mSrcSampleRate == srcSampleRate
7123 && mDstFormat == dstFormat
7124 && mDstChannelMask == dstChannelMask
7125 && mDstSampleRate == dstSampleRate) {
7126 return NO_ERROR;
7127 }
7128
Andy Hungdb4c0312015-05-06 08:46:52 -07007129 ALOGV("RecordBufferConverter updateParameters srcMask:%#x dstMask:%#x"
7130 " srcFormat:%#x dstFormat:%#x srcRate:%u dstRate:%u",
7131 srcChannelMask, dstChannelMask, srcFormat, dstFormat, srcSampleRate, dstSampleRate);
Andy Hung97a893e2015-03-29 01:03:07 -07007132 const bool valid =
7133 audio_is_input_channel(srcChannelMask)
7134 && audio_is_input_channel(dstChannelMask)
7135 && audio_is_valid_format(srcFormat) && audio_is_linear_pcm(srcFormat)
7136 && audio_is_valid_format(dstFormat) && audio_is_linear_pcm(dstFormat)
7137 && (srcSampleRate <= dstSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX)
7138 ; // no upsampling checks for now
7139 if (!valid) {
7140 return BAD_VALUE;
7141 }
7142
7143 mSrcFormat = srcFormat;
7144 mSrcChannelMask = srcChannelMask;
7145 mSrcSampleRate = srcSampleRate;
7146 mDstFormat = dstFormat;
7147 mDstChannelMask = dstChannelMask;
7148 mDstSampleRate = dstSampleRate;
7149
7150 // compute derived parameters
7151 mSrcChannelCount = audio_channel_count_from_in_mask(srcChannelMask);
7152 mDstChannelCount = audio_channel_count_from_in_mask(dstChannelMask);
7153 mDstFrameSize = mDstChannelCount * audio_bytes_per_sample(mDstFormat);
7154
Andy Hungd330ee42015-04-20 13:23:41 -07007155 // do we need to resample?
7156 delete mResampler;
7157 mResampler = NULL;
7158 if (mSrcSampleRate != mDstSampleRate) {
7159 mResampler = AudioResampler::create(AUDIO_FORMAT_PCM_FLOAT,
7160 mSrcChannelCount, mDstSampleRate);
7161 mResampler->setSampleRate(mSrcSampleRate);
7162 mResampler->setVolume(AudioMixer::UNITY_GAIN_FLOAT, AudioMixer::UNITY_GAIN_FLOAT);
7163 }
7164
7165 // are we running legacy channel conversion modes?
7166 mIsLegacyDownmix = (mSrcChannelMask == AUDIO_CHANNEL_IN_STEREO
7167 || mSrcChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK)
7168 && mDstChannelMask == AUDIO_CHANNEL_IN_MONO;
7169 mIsLegacyUpmix = mSrcChannelMask == AUDIO_CHANNEL_IN_MONO
7170 && (mDstChannelMask == AUDIO_CHANNEL_IN_STEREO
7171 || mDstChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK);
7172
7173 // do we need to process in float?
7174 mRequiresFloat = mResampler != NULL || mIsLegacyDownmix || mIsLegacyUpmix;
7175
7176 // do we need a staging buffer to convert for destination (we can still optimize this)?
7177 // we use mBufFrameSize > 0 to indicate both frame size as well as buffer necessity
7178 if (mResampler != NULL) {
7179 mBufFrameSize = max(mSrcChannelCount, FCC_2)
7180 * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
Andy Hunga97630b2015-07-22 23:27:24 -07007181 } else if (mIsLegacyUpmix || mIsLegacyDownmix) { // legacy modes always float
Andy Hungd330ee42015-04-20 13:23:41 -07007182 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
7183 } else if (mSrcChannelMask != mDstChannelMask && mDstFormat != mSrcFormat) {
Andy Hung97a893e2015-03-29 01:03:07 -07007184 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(mSrcFormat);
7185 } else {
7186 mBufFrameSize = 0;
7187 }
7188 mBufFrames = 0; // force the buffer to be resized.
7189
Andy Hungd330ee42015-04-20 13:23:41 -07007190 // do we need an input converter buffer provider to give us float?
7191 delete mInputConverterProvider;
7192 mInputConverterProvider = NULL;
7193 if (mRequiresFloat && mSrcFormat != AUDIO_FORMAT_PCM_FLOAT) {
7194 mInputConverterProvider = new ReformatBufferProvider(
7195 audio_channel_count_from_in_mask(mSrcChannelMask),
7196 mSrcFormat,
7197 AUDIO_FORMAT_PCM_FLOAT,
7198 256 /* provider buffer frame count */);
7199 }
7200
7201 // do we need a remixer to do channel mask conversion
7202 if (!mIsLegacyDownmix && !mIsLegacyUpmix && mSrcChannelMask != mDstChannelMask) {
7203 (void) memcpy_by_index_array_initialization_from_channel_mask(
7204 mIdxAry, ARRAY_SIZE(mIdxAry), mDstChannelMask, mSrcChannelMask);
Andy Hung97a893e2015-03-29 01:03:07 -07007205 }
7206 return NO_ERROR;
7207}
7208
Andy Hungd330ee42015-04-20 13:23:41 -07007209void AudioFlinger::RecordThread::RecordBufferConverter::convertNoResampler(
7210 void *dst, const void *src, size_t frames)
Andy Hung97a893e2015-03-29 01:03:07 -07007211{
Andy Hungd330ee42015-04-20 13:23:41 -07007212 // src is native type unless there is legacy upmix or downmix, whereupon it is float.
Andy Hung97a893e2015-03-29 01:03:07 -07007213 if (mBufFrameSize != 0 && mBufFrames < frames) {
7214 free(mBuf);
7215 mBufFrames = frames;
7216 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
7217 }
Andy Hungd330ee42015-04-20 13:23:41 -07007218 // do we need to do legacy upmix and downmix?
7219 if (mIsLegacyUpmix || mIsLegacyDownmix) {
Andy Hung97a893e2015-03-29 01:03:07 -07007220 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07007221 if (mIsLegacyUpmix) {
7222 upmix_to_stereo_float_from_mono_float((float *)dstBuf,
7223 (const float *)src, frames);
7224 } else /*mIsLegacyDownmix */ {
7225 downmix_to_mono_float_from_stereo_float((float *)dstBuf,
7226 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07007227 }
Andy Hungd330ee42015-04-20 13:23:41 -07007228 if (mBuf != NULL) {
7229 memcpy_by_audio_format(dst, mDstFormat, mBuf, AUDIO_FORMAT_PCM_FLOAT,
7230 frames * mDstChannelCount);
7231 }
7232 return;
7233 }
7234 // do we need to do channel mask conversion?
7235 if (mSrcChannelMask != mDstChannelMask) {
Andy Hung97a893e2015-03-29 01:03:07 -07007236 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07007237 memcpy_by_index_array(dstBuf, mDstChannelCount,
7238 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mSrcFormat), frames);
7239 if (dstBuf == dst) {
7240 return; // format is the same
7241 }
7242 }
7243 // convert to destination buffer
7244 const void *convertBuf = mBuf != NULL ? mBuf : src;
7245 memcpy_by_audio_format(dst, mDstFormat, convertBuf, mSrcFormat,
7246 frames * mDstChannelCount);
7247}
7248
7249void AudioFlinger::RecordThread::RecordBufferConverter::convertResampler(
7250 void *dst, /*not-a-const*/ void *src, size_t frames)
7251{
7252 // src buffer format is ALWAYS float when entering this routine
7253 if (mIsLegacyUpmix) {
7254 ; // mono to stereo already handled by resampler
7255 } else if (mIsLegacyDownmix
7256 || (mSrcChannelMask == mDstChannelMask && mSrcChannelCount == 1)) {
7257 // the resampler outputs stereo for mono input channel (a feature?)
7258 // must convert to mono
7259 downmix_to_mono_float_from_stereo_float((float *)src,
7260 (const float *)src, frames);
7261 } else if (mSrcChannelMask != mDstChannelMask) {
7262 // convert to mono channel again for channel mask conversion (could be skipped
7263 // with further optimization).
Andy Hung97a893e2015-03-29 01:03:07 -07007264 if (mSrcChannelCount == 1) {
Andy Hungd330ee42015-04-20 13:23:41 -07007265 downmix_to_mono_float_from_stereo_float((float *)src,
7266 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07007267 }
Andy Hungd330ee42015-04-20 13:23:41 -07007268 // convert to destination format (in place, OK as float is larger than other types)
7269 if (mDstFormat != AUDIO_FORMAT_PCM_FLOAT) {
7270 memcpy_by_audio_format(src, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
7271 frames * mSrcChannelCount);
7272 }
7273 // channel convert and save to dst
7274 memcpy_by_index_array(dst, mDstChannelCount,
7275 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mDstFormat), frames);
7276 return;
Andy Hung97a893e2015-03-29 01:03:07 -07007277 }
Andy Hungd330ee42015-04-20 13:23:41 -07007278 // convert to destination format and save to dst
7279 memcpy_by_audio_format(dst, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
7280 frames * mDstChannelCount);
Andy Hung97a893e2015-03-29 01:03:07 -07007281}
7282
Eric Laurent10351942014-05-08 18:49:52 -07007283bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
7284 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007285{
7286 bool reconfig = false;
7287
Eric Laurent10351942014-05-08 18:49:52 -07007288 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007289
Eric Laurent10351942014-05-08 18:49:52 -07007290 audio_format_t reqFormat = mFormat;
7291 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07007292 // 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 -07007293 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
7294
7295 AudioParameter param = AudioParameter(keyValuePair);
7296 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07007297
7298 // scope for AutoPark extends to end of method
7299 AutoPark<FastCapture> park(mFastCapture);
7300
Eric Laurent10351942014-05-08 18:49:52 -07007301 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
7302 // channel count change can be requested. Do we mandate the first client defines the
7303 // HAL sampling rate and channel count or do we allow changes on the fly?
7304 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
7305 samplingRate = value;
7306 reconfig = true;
7307 }
7308 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07007309 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07007310 status = BAD_VALUE;
7311 } else {
7312 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08007313 reconfig = true;
7314 }
Eric Laurent10351942014-05-08 18:49:52 -07007315 }
7316 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
7317 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07007318 if (!audio_is_input_channel(mask) ||
7319 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007320 status = BAD_VALUE;
7321 } else {
7322 channelMask = mask;
7323 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007324 }
Eric Laurent10351942014-05-08 18:49:52 -07007325 }
7326 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7327 // do not accept frame count changes if tracks are open as the track buffer
7328 // size depends on frame count and correct behavior would not be guaranteed
7329 // if frame count is changed after track creation
7330 if (mActiveTracks.size() > 0) {
7331 status = INVALID_OPERATION;
7332 } else {
7333 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007334 }
Eric Laurent10351942014-05-08 18:49:52 -07007335 }
7336 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7337 // forward device change to effects that have requested to be
7338 // aware of attached audio device.
7339 for (size_t i = 0; i < mEffectChains.size(); i++) {
7340 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08007341 }
Eric Laurent81784c32012-11-19 14:55:58 -08007342
Eric Laurent10351942014-05-08 18:49:52 -07007343 // store input device and output device but do not forward output device to audio HAL.
7344 // Note that status is ignored by the caller for output device
7345 // (see AudioFlinger::setParameters()
7346 if (audio_is_output_devices(value)) {
7347 mOutDevice = value;
7348 status = BAD_VALUE;
7349 } else {
7350 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07007351 if (value != AUDIO_DEVICE_NONE) {
7352 mPrevInDevice = value;
7353 }
Eric Laurent10351942014-05-08 18:49:52 -07007354 // disable AEC and NS if the device is a BT SCO headset supporting those
7355 // pre processings
7356 if (mTracks.size() > 0) {
7357 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7358 mAudioFlinger->btNrecIsOff();
7359 for (size_t i = 0; i < mTracks.size(); i++) {
7360 sp<RecordTrack> track = mTracks[i];
7361 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7362 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08007363 }
7364 }
7365 }
Eric Laurent10351942014-05-08 18:49:52 -07007366 }
7367 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
7368 mAudioSource != (audio_source_t)value) {
7369 // forward device change to effects that have requested to be
7370 // aware of attached audio device.
7371 for (size_t i = 0; i < mEffectChains.size(); i++) {
7372 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08007373 }
Eric Laurent10351942014-05-08 18:49:52 -07007374 mAudioSource = (audio_source_t)value;
7375 }
Glenn Kastene198c362013-08-13 09:13:36 -07007376
Eric Laurent10351942014-05-08 18:49:52 -07007377 if (status == NO_ERROR) {
7378 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7379 keyValuePair.string());
7380 if (status == INVALID_OPERATION) {
7381 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08007382 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7383 keyValuePair.string());
Eric Laurent10351942014-05-08 18:49:52 -07007384 }
7385 if (reconfig) {
7386 if (status == BAD_VALUE &&
Andy Hung97a893e2015-03-29 01:03:07 -07007387 audio_is_linear_pcm(mInput->stream->common.get_format(&mInput->stream->common)) &&
7388 audio_is_linear_pcm(reqFormat) &&
Eric Laurent10351942014-05-08 18:49:52 -07007389 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
Andy Hung97a893e2015-03-29 01:03:07 -07007390 <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate)) &&
Andy Hunge5412692014-05-16 11:25:07 -07007391 audio_channel_count_from_in_mask(
Andy Hungd1abb8f2015-05-05 23:42:34 -07007392 mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007393 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007394 }
Eric Laurent10351942014-05-08 18:49:52 -07007395 if (status == NO_ERROR) {
7396 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007397 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08007398 }
7399 }
Eric Laurent81784c32012-11-19 14:55:58 -08007400 }
Eric Laurent10351942014-05-08 18:49:52 -07007401
Eric Laurent81784c32012-11-19 14:55:58 -08007402 return reconfig;
7403}
7404
7405String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
7406{
Eric Laurent81784c32012-11-19 14:55:58 -08007407 Mutex::Autolock _l(mLock);
7408 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07007409 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08007410 }
7411
Glenn Kastend8ea6992013-07-16 14:17:15 -07007412 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
7413 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08007414 free(s);
7415 return out_s8;
7416}
7417
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007418void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007419 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7420
7421 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08007422
7423 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007424 case AUDIO_INPUT_OPENED:
7425 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07007426 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07007427 desc->mChannelMask = mChannelMask;
7428 desc->mSamplingRate = mSampleRate;
7429 desc->mFormat = mFormat;
7430 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07007431 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07007432 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007433 break;
7434
Eric Laurent73e26b62015-04-27 16:55:58 -07007435 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08007436 default:
7437 break;
7438 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007439 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08007440}
7441
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007442void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007443{
Eric Laurent81784c32012-11-19 14:55:58 -08007444 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
7445 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Andy Hunge5412692014-05-16 11:25:07 -07007446 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Andy Hungd330ee42015-04-20 13:23:41 -07007447 if (mChannelCount > FCC_8) {
7448 ALOGE("HAL channel count %d > %d", mChannelCount, FCC_8);
7449 }
Andy Hung463be252014-07-10 16:56:07 -07007450 mHALFormat = mInput->stream->common.get_format(&mInput->stream->common);
7451 mFormat = mHALFormat;
Andy Hungd330ee42015-04-20 13:23:41 -07007452 if (!audio_is_linear_pcm(mFormat)) {
7453 ALOGE("HAL format %#x is not linear pcm", mFormat);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07007454 }
Eric Laurent665470b2014-07-03 16:37:08 -07007455 mFrameSize = audio_stream_in_frame_size(mInput->stream);
Glenn Kasten548efc92012-11-29 08:48:51 -08007456 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
7457 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007458 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08007459 // 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 -07007460 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08007461 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007462 // A larger value should allow more old data to be read after a track calls start(),
7463 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07007464 //
7465 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08007466 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07007467 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07007468 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07007469 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007470
7471 // TODO optimize audio capture buffer sizes ...
7472 // Here we calculate the size of the sliding buffer used as a source
7473 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
7474 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
7475 // be better to have it derived from the pipe depth in the long term.
7476 // The current value is higher than necessary. However it should not add to latency.
7477
Glenn Kasten85948432013-08-19 12:09:05 -07007478 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Glenn Kasten1b291842016-07-18 14:55:21 -07007479 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
7480 (void)posix_memalign(&mRsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
7481 memset(mRsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize); // if posix_memalign fails, will segv here.
Eric Laurent81784c32012-11-19 14:55:58 -08007482
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007483 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
7484 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08007485}
7486
Glenn Kasten5f972c02014-01-13 09:59:31 -08007487uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08007488{
7489 Mutex::Autolock _l(mLock);
7490 if (initCheck() != NO_ERROR) {
7491 return 0;
7492 }
7493
7494 return mInput->stream->get_input_frames_lost(mInput->stream);
7495}
7496
Eric Laurent4c415062016-06-17 16:14:16 -07007497// hasAudioSession_l() must be called with ThreadBase::mLock held
7498uint32_t AudioFlinger::RecordThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08007499{
Eric Laurent81784c32012-11-19 14:55:58 -08007500 uint32_t result = 0;
7501 if (getEffectChain_l(sessionId) != 0) {
7502 result = EFFECT_SESSION;
7503 }
7504
7505 for (size_t i = 0; i < mTracks.size(); ++i) {
7506 if (sessionId == mTracks[i]->sessionId()) {
7507 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07007508 if (mTracks[i]->isFastTrack()) {
7509 result |= FAST_SESSION;
7510 }
Eric Laurent81784c32012-11-19 14:55:58 -08007511 break;
7512 }
7513 }
7514
7515 return result;
7516}
7517
Glenn Kastend848eb42016-03-08 13:42:11 -08007518KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08007519{
Glenn Kastend848eb42016-03-08 13:42:11 -08007520 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08007521 Mutex::Autolock _l(mLock);
7522 for (size_t j = 0; j < mTracks.size(); ++j) {
7523 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08007524 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08007525 if (ids.indexOfKey(sessionId) < 0) {
7526 ids.add(sessionId, true);
7527 }
7528 }
7529 return ids;
7530}
7531
7532AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7533{
7534 Mutex::Autolock _l(mLock);
7535 AudioStreamIn *input = mInput;
7536 mInput = NULL;
7537 return input;
7538}
7539
7540// this method must always be called either with ThreadBase mLock held or inside the thread loop
7541audio_stream_t* AudioFlinger::RecordThread::stream() const
7542{
7543 if (mInput == NULL) {
7544 return NULL;
7545 }
7546 return &mInput->stream->common;
7547}
7548
7549status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7550{
7551 // only one chain per input thread
7552 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07007553 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08007554 return INVALID_OPERATION;
7555 }
7556 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07007557 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08007558 chain->setInBuffer(NULL);
7559 chain->setOutBuffer(NULL);
7560
7561 checkSuspendOnAddEffectChain_l(chain);
7562
Eric Laurent1b928682014-10-02 19:41:47 -07007563 // make sure enabled pre processing effects state is communicated to the HAL as we
7564 // just moved them to a new input stream.
7565 chain->syncHalEffectsState();
7566
Eric Laurent81784c32012-11-19 14:55:58 -08007567 mEffectChains.add(chain);
7568
7569 return NO_ERROR;
7570}
7571
7572size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7573{
7574 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7575 ALOGW_IF(mEffectChains.size() != 1,
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007576 "removeEffectChain_l() %p invalid chain size %zu on thread %p",
Eric Laurent81784c32012-11-19 14:55:58 -08007577 chain.get(), mEffectChains.size(), this);
7578 if (mEffectChains.size() == 1) {
7579 mEffectChains.removeAt(0);
7580 }
7581 return 0;
7582}
7583
Eric Laurent1c333e22014-05-20 10:48:17 -07007584status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7585 audio_patch_handle_t *handle)
7586{
7587 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007588
7589 // store new device and send to effects
7590 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07007591 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07007592 for (size_t i = 0; i < mEffectChains.size(); i++) {
7593 mEffectChains[i]->setDevice_l(mInDevice);
7594 }
7595
7596 // disable AEC and NS if the device is a BT SCO headset supporting those
7597 // pre processings
7598 if (mTracks.size() > 0) {
7599 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7600 mAudioFlinger->btNrecIsOff();
7601 for (size_t i = 0; i < mTracks.size(); i++) {
7602 sp<RecordTrack> track = mTracks[i];
7603 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7604 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
7605 }
7606 }
7607
7608 // store new source and send to effects
7609 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7610 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07007611 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07007612 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07007613 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007614 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007615
Eric Laurent054d9d32015-04-24 08:48:48 -07007616 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007617 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7618 status = hwDevice->createAudioPatch(patch->num_sources,
7619 patch->sources,
7620 patch->num_sinks,
7621 patch->sinks,
7622 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007623 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007624 char *address;
7625 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7626 address = audio_device_address_to_parameter(
7627 patch->sources[0].ext.device.type,
7628 patch->sources[0].ext.device.address);
7629 } else {
7630 address = (char *)calloc(1, 1);
7631 }
7632 AudioParameter param = AudioParameter(String8(address));
7633 free(address);
7634 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING),
7635 (int)patch->sources[0].ext.device.type);
7636 param.addInt(String8(AUDIO_PARAMETER_STREAM_INPUT_SOURCE),
7637 (int)patch->sinks[0].ext.mix.usecase.source);
7638 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7639 param.toString().string());
7640 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07007641 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007642
Eric Laurente8726fe2015-06-26 09:39:24 -07007643 if (mInDevice != mPrevInDevice) {
7644 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7645 mPrevInDevice = mInDevice;
7646 }
Eric Laurent296fb132015-05-01 11:38:42 -07007647
Eric Laurent1c333e22014-05-20 10:48:17 -07007648 return status;
7649}
7650
7651status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7652{
7653 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007654
7655 mInDevice = AUDIO_DEVICE_NONE;
7656
Eric Laurent1c333e22014-05-20 10:48:17 -07007657 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007658 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7659 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007660 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007661 AudioParameter param;
7662 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
7663 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7664 param.toString().string());
Eric Laurent1c333e22014-05-20 10:48:17 -07007665 }
7666 return status;
7667}
7668
Eric Laurent83b88082014-06-20 18:31:16 -07007669void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
7670{
7671 Mutex::Autolock _l(mLock);
7672 mTracks.add(record);
7673}
7674
7675void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
7676{
7677 Mutex::Autolock _l(mLock);
7678 destroyTrack_l(record);
7679}
7680
7681void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
7682{
7683 ThreadBase::getAudioPortConfig(config);
7684 config->role = AUDIO_PORT_ROLE_SINK;
7685 config->ext.mix.hw_module = mInput->audioHwDev->handle();
7686 config->ext.mix.usecase.source = mAudioSource;
7687}
Eric Laurent1c333e22014-05-20 10:48:17 -07007688
Glenn Kasten63238ef2015-03-02 15:50:29 -08007689} // namespace android