blob: 02e8522f4439b30997e5642674e1ab81ecd68785 [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>
Eric Laurent81784c32012-11-19 14:55:58 -080036#include <audio_effects/effect_ns.h>
37#include <audio_effects/effect_aec.h>
Andy Hung2ddee192015-12-18 17:34:44 -080038#include <audio_utils/conversion.h>
Eric Laurent81784c32012-11-19 14:55:58 -080039#include <audio_utils/primitives.h>
Andy Hung98ef9782014-03-04 14:46:50 -080040#include <audio_utils/format.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070041#include <audio_utils/minifloat.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070042#include <system/audio.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 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001281
1282 // always allow effects without processing load or latency
1283 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1284 return NO_ERROR;
1285 }
1286
Eric Laurent4c415062016-06-17 16:14:16 -07001287 audio_input_flags_t flags = mInput->flags;
1288 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1289 if (flags & AUDIO_INPUT_FLAG_RAW) {
1290 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1291 desc->name, mThreadName);
1292 return BAD_VALUE;
1293 }
1294 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1295 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1296 desc->name, mThreadName);
1297 return BAD_VALUE;
1298 }
1299 }
1300 return NO_ERROR;
1301}
1302
1303// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1304status_t AudioFlinger::PlaybackThread::checkEffectCompatibility_l(
1305 const effect_descriptor_t *desc, audio_session_t sessionId)
1306{
1307 // no preprocessing on playback threads
1308 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
1309 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback"
1310 " thread %s", desc->name, mThreadName);
1311 return BAD_VALUE;
1312 }
1313
1314 switch (mType) {
1315 case MIXER: {
1316 // Reject any effect on mixer multichannel sinks.
1317 // TODO: fix both format and multichannel issues with effects.
1318 if (mChannelCount != FCC_2) {
1319 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d) on MIXER"
1320 " thread %s", desc->name, mChannelCount, mThreadName);
1321 return BAD_VALUE;
1322 }
1323 audio_output_flags_t flags = mOutput->flags;
1324 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1325 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1326 // global effects are applied only to non fast tracks if they are SW
1327 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1328 break;
1329 }
1330 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1331 // only post processing on output stage session
1332 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1333 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1334 " on output stage session", desc->name);
1335 return BAD_VALUE;
1336 }
1337 } else {
1338 // no restriction on effects applied on non fast tracks
1339 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1340 break;
1341 }
1342 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001343
1344 // always allow effects without processing load or latency
1345 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1346 break;
1347 }
Eric Laurent4c415062016-06-17 16:14:16 -07001348 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
1349 ALOGW("checkEffectCompatibility_l(): effect %s on playback thread in raw mode",
1350 desc->name);
1351 return BAD_VALUE;
1352 }
1353 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1354 ALOGW("checkEffectCompatibility_l(): non HW effect %s on playback thread"
1355 " in fast mode", desc->name);
1356 return BAD_VALUE;
1357 }
1358 }
1359 } break;
1360 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001361 // nothing actionable on offload threads, if the effect:
1362 // - is offloadable: the effect can be created
1363 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1364 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001365 break;
1366 case DIRECT:
1367 // Reject any effect on Direct output threads for now, since the format of
1368 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1369 ALOGW("checkEffectCompatibility_l(): effect %s on DIRECT output thread %s",
1370 desc->name, mThreadName);
1371 return BAD_VALUE;
1372 case DUPLICATING:
1373 // Reject any effect on mixer multichannel sinks.
1374 // TODO: fix both format and multichannel issues with effects.
1375 if (mChannelCount != FCC_2) {
1376 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d)"
1377 " on DUPLICATING thread %s", desc->name, mChannelCount, mThreadName);
1378 return BAD_VALUE;
1379 }
1380 if ((sessionId == AUDIO_SESSION_OUTPUT_STAGE) || (sessionId == AUDIO_SESSION_OUTPUT_MIX)) {
1381 ALOGW("checkEffectCompatibility_l(): global effect %s on DUPLICATING"
1382 " thread %s", desc->name, mThreadName);
1383 return BAD_VALUE;
1384 }
1385 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
1386 ALOGW("checkEffectCompatibility_l(): post processing effect %s on"
1387 " DUPLICATING thread %s", desc->name, mThreadName);
1388 return BAD_VALUE;
1389 }
1390 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1391 ALOGW("checkEffectCompatibility_l(): HW tunneled effect %s on"
1392 " DUPLICATING thread %s", desc->name, mThreadName);
1393 return BAD_VALUE;
1394 }
1395 break;
1396 default:
1397 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1398 }
1399
1400 return NO_ERROR;
1401}
1402
Eric Laurent81784c32012-11-19 14:55:58 -08001403// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1404sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1405 const sp<AudioFlinger::Client>& client,
1406 const sp<IEffectClient>& effectClient,
1407 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001408 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001409 effect_descriptor_t *desc,
1410 int *enabled,
Glenn Kasten9156ef32013-08-06 15:39:08 -07001411 status_t *status)
Eric Laurent81784c32012-11-19 14:55:58 -08001412{
1413 sp<EffectModule> effect;
1414 sp<EffectHandle> handle;
1415 status_t lStatus;
1416 sp<EffectChain> chain;
1417 bool chainCreated = false;
1418 bool effectCreated = false;
1419 bool effectRegistered = false;
1420
1421 lStatus = initCheck();
1422 if (lStatus != NO_ERROR) {
1423 ALOGW("createEffect_l() Audio driver not initialized.");
1424 goto Exit;
1425 }
1426
Eric Laurent81784c32012-11-19 14:55:58 -08001427 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1428
1429 { // scope for mLock
1430 Mutex::Autolock _l(mLock);
1431
Eric Laurent4c415062016-06-17 16:14:16 -07001432 lStatus = checkEffectCompatibility_l(desc, sessionId);
1433 if (lStatus != NO_ERROR) {
1434 goto Exit;
1435 }
1436
Eric Laurent81784c32012-11-19 14:55:58 -08001437 // check for existing effect chain with the requested audio session
1438 chain = getEffectChain_l(sessionId);
1439 if (chain == 0) {
1440 // create a new chain for this session
1441 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1442 chain = new EffectChain(this, sessionId);
1443 addEffectChain_l(chain);
1444 chain->setStrategy(getStrategyForSession_l(sessionId));
1445 chainCreated = true;
1446 } else {
1447 effect = chain->getEffectFromDesc_l(desc);
1448 }
1449
1450 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1451
1452 if (effect == 0) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08001453 audio_unique_id_t id = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001454 // Check CPU and memory usage
1455 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
1456 if (lStatus != NO_ERROR) {
1457 goto Exit;
1458 }
1459 effectRegistered = true;
1460 // create a new effect module if none present in the chain
1461 effect = new EffectModule(this, chain, desc, id, sessionId);
1462 lStatus = effect->status();
1463 if (lStatus != NO_ERROR) {
1464 goto Exit;
1465 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001466 effect->setOffloaded(mType == OFFLOAD, mId);
1467
Eric Laurent81784c32012-11-19 14:55:58 -08001468 lStatus = chain->addEffect_l(effect);
1469 if (lStatus != NO_ERROR) {
1470 goto Exit;
1471 }
1472 effectCreated = true;
1473
1474 effect->setDevice(mOutDevice);
1475 effect->setDevice(mInDevice);
1476 effect->setMode(mAudioFlinger->getMode());
1477 effect->setAudioSource(mAudioSource);
1478 }
1479 // create effect handle and connect it to effect module
1480 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001481 lStatus = handle->initCheck();
1482 if (lStatus == OK) {
1483 lStatus = effect->addHandle(handle.get());
1484 }
Eric Laurent81784c32012-11-19 14:55:58 -08001485 if (enabled != NULL) {
1486 *enabled = (int)effect->isEnabled();
1487 }
1488 }
1489
1490Exit:
1491 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1492 Mutex::Autolock _l(mLock);
1493 if (effectCreated) {
1494 chain->removeEffect_l(effect);
1495 }
1496 if (effectRegistered) {
1497 AudioSystem::unregisterEffect(effect->id());
1498 }
1499 if (chainCreated) {
1500 removeEffectChain_l(chain);
1501 }
1502 handle.clear();
1503 }
1504
Glenn Kasten9156ef32013-08-06 15:39:08 -07001505 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001506 return handle;
1507}
1508
Glenn Kastend848eb42016-03-08 13:42:11 -08001509sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1510 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001511{
1512 Mutex::Autolock _l(mLock);
1513 return getEffect_l(sessionId, effectId);
1514}
1515
Glenn Kastend848eb42016-03-08 13:42:11 -08001516sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1517 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001518{
1519 sp<EffectChain> chain = getEffectChain_l(sessionId);
1520 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1521}
1522
1523// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1524// PlaybackThread::mLock held
1525status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1526{
1527 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001528 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001529 sp<EffectChain> chain = getEffectChain_l(sessionId);
1530 bool chainCreated = false;
1531
Eric Laurent5baf2af2013-09-12 17:37:00 -07001532 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1533 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1534 this, effect->desc().name, effect->desc().flags);
1535
Eric Laurent81784c32012-11-19 14:55:58 -08001536 if (chain == 0) {
1537 // create a new chain for this session
1538 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1539 chain = new EffectChain(this, sessionId);
1540 addEffectChain_l(chain);
1541 chain->setStrategy(getStrategyForSession_l(sessionId));
1542 chainCreated = true;
1543 }
1544 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1545
1546 if (chain->getEffectFromId_l(effect->id()) != 0) {
1547 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1548 this, effect->desc().name, chain.get());
1549 return BAD_VALUE;
1550 }
1551
Eric Laurent5baf2af2013-09-12 17:37:00 -07001552 effect->setOffloaded(mType == OFFLOAD, mId);
1553
Eric Laurent81784c32012-11-19 14:55:58 -08001554 status_t status = chain->addEffect_l(effect);
1555 if (status != NO_ERROR) {
1556 if (chainCreated) {
1557 removeEffectChain_l(chain);
1558 }
1559 return status;
1560 }
1561
1562 effect->setDevice(mOutDevice);
1563 effect->setDevice(mInDevice);
1564 effect->setMode(mAudioFlinger->getMode());
1565 effect->setAudioSource(mAudioSource);
1566 return NO_ERROR;
1567}
1568
1569void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
1570
1571 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
1572 effect_descriptor_t desc = effect->desc();
1573 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1574 detachAuxEffect_l(effect->id());
1575 }
1576
1577 sp<EffectChain> chain = effect->chain().promote();
1578 if (chain != 0) {
1579 // remove effect chain if removing last effect
1580 if (chain->removeEffect_l(effect) == 0) {
1581 removeEffectChain_l(chain);
1582 }
1583 } else {
1584 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1585 }
1586}
1587
1588void AudioFlinger::ThreadBase::lockEffectChains_l(
1589 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1590{
1591 effectChains = mEffectChains;
1592 for (size_t i = 0; i < mEffectChains.size(); i++) {
1593 mEffectChains[i]->lock();
1594 }
1595}
1596
1597void AudioFlinger::ThreadBase::unlockEffectChains(
1598 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1599{
1600 for (size_t i = 0; i < effectChains.size(); i++) {
1601 effectChains[i]->unlock();
1602 }
1603}
1604
Glenn Kastend848eb42016-03-08 13:42:11 -08001605sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001606{
1607 Mutex::Autolock _l(mLock);
1608 return getEffectChain_l(sessionId);
1609}
1610
Glenn Kastend848eb42016-03-08 13:42:11 -08001611sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1612 const
Eric Laurent81784c32012-11-19 14:55:58 -08001613{
1614 size_t size = mEffectChains.size();
1615 for (size_t i = 0; i < size; i++) {
1616 if (mEffectChains[i]->sessionId() == sessionId) {
1617 return mEffectChains[i];
1618 }
1619 }
1620 return 0;
1621}
1622
1623void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1624{
1625 Mutex::Autolock _l(mLock);
1626 size_t size = mEffectChains.size();
1627 for (size_t i = 0; i < size; i++) {
1628 mEffectChains[i]->setMode_l(mode);
1629 }
1630}
1631
Eric Laurent83b88082014-06-20 18:31:16 -07001632void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1633{
1634 config->type = AUDIO_PORT_TYPE_MIX;
1635 config->ext.mix.handle = mId;
1636 config->sample_rate = mSampleRate;
1637 config->format = mFormat;
1638 config->channel_mask = mChannelMask;
1639 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1640 AUDIO_PORT_CONFIG_FORMAT;
1641}
1642
Eric Laurent72e3f392015-05-20 14:43:50 -07001643void AudioFlinger::ThreadBase::systemReady()
1644{
1645 Mutex::Autolock _l(mLock);
1646 if (mSystemReady) {
1647 return;
1648 }
1649 mSystemReady = true;
1650
1651 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1652 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1653 }
1654 mPendingConfigEvents.clear();
1655}
1656
Eric Laurent83b88082014-06-20 18:31:16 -07001657
Eric Laurent81784c32012-11-19 14:55:58 -08001658// ----------------------------------------------------------------------------
1659// Playback
1660// ----------------------------------------------------------------------------
1661
1662AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1663 AudioStreamOut* output,
1664 audio_io_handle_t id,
1665 audio_devices_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07001666 type_t type,
Eric Laurente93cc032016-05-05 10:15:10 -07001667 bool systemReady)
Eric Laurent72e3f392015-05-20 14:43:50 -07001668 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001669 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001670 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001671 mMixerBuffer(NULL),
1672 mMixerBufferSize(0),
1673 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1674 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001675 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001676 mEffectBuffer(NULL),
1677 mEffectBufferSize(0),
1678 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1679 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001680 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001681 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07001682 mSuspendedFrames(0),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001683 mActiveTracksGeneration(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001684 // mStreamTypes[] initialized in constructor body
1685 mOutput(output),
Andy Hung69488c42016-05-16 18:43:33 -07001686 mLastWriteTime(-1), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001687 mMixerStatus(MIXER_IDLE),
1688 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001689 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001690 mBytesRemaining(0),
1691 mCurrentWriteLength(0),
1692 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001693 mWriteAckSequence(0),
1694 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001695 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001696 mScreenState(AudioFlinger::mScreenState),
1697 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001698 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Andy Hunge10393e2015-06-12 13:59:33 -07001699 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001700{
Glenn Kastend7dca052015-03-05 16:05:54 -08001701 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1702 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001703
1704 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1705 // it would be safer to explicitly pass initial masterVolume/masterMute as
1706 // parameter.
1707 //
1708 // If the HAL we are using has support for master volume or master mute,
1709 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1710 // and the mute set to false).
1711 mMasterVolume = audioFlinger->masterVolume_l();
1712 mMasterMute = audioFlinger->masterMute_l();
1713 if (mOutput && mOutput->audioHwDev) {
1714 if (mOutput->audioHwDev->canSetMasterVolume()) {
1715 mMasterVolume = 1.0;
1716 }
1717
1718 if (mOutput->audioHwDev->canSetMasterMute()) {
1719 mMasterMute = false;
1720 }
1721 }
1722
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001723 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001724
Eric Laurent223fd5c2014-11-11 13:43:36 -08001725 // ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001726 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001727 stream = (audio_stream_type_t) (stream + 1)) {
1728 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1729 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1730 }
Eric Laurent81784c32012-11-19 14:55:58 -08001731}
1732
1733AudioFlinger::PlaybackThread::~PlaybackThread()
1734{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001735 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001736 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001737 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001738 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001739}
1740
1741void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1742{
1743 dumpInternals(fd, args);
1744 dumpTracks(fd, args);
1745 dumpEffectChains(fd, args);
1746}
1747
Glenn Kasten0f11b512014-01-31 16:18:54 -08001748void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001749{
1750 const size_t SIZE = 256;
1751 char buffer[SIZE];
1752 String8 result;
1753
Marco Nelissenb2208842014-02-07 14:00:50 -08001754 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001755 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1756 const stream_type_t *st = &mStreamTypes[i];
1757 if (i > 0) {
1758 result.appendFormat(", ");
1759 }
1760 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1761 if (st->mute) {
1762 result.append("M");
1763 }
1764 }
1765 result.append("\n");
1766 write(fd, result.string(), result.length());
1767 result.clear();
1768
Eric Laurent81784c32012-11-19 14:55:58 -08001769 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1770 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001771 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001772 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001773
1774 size_t numtracks = mTracks.size();
1775 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001776 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001777 size_t numactiveseen = 0;
1778 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001779 dprintf(fd, " of which %zu are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001780 Track::appendDumpHeader(result);
1781 for (size_t i = 0; i < numtracks; ++i) {
1782 sp<Track> track = mTracks[i];
1783 if (track != 0) {
1784 bool active = mActiveTracks.indexOf(track) >= 0;
1785 if (active) {
1786 numactiveseen++;
1787 }
1788 track->dump(buffer, SIZE, active);
1789 result.append(buffer);
1790 }
1791 }
1792 } else {
1793 result.append("\n");
1794 }
1795 if (numactiveseen != numactive) {
1796 // some tracks in the active list were not in the tracks list
1797 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1798 " not in the track list\n");
1799 result.append(buffer);
1800 Track::appendDumpHeader(result);
1801 for (size_t i = 0; i < numactive; ++i) {
1802 sp<Track> track = mActiveTracks[i].promote();
1803 if (track != 0 && mTracks.indexOf(track) < 0) {
1804 track->dump(buffer, SIZE, true);
1805 result.append(buffer);
1806 }
1807 }
1808 }
1809
1810 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001811}
1812
1813void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1814{
Glenn Kasten97b7b752014-09-28 13:04:24 -07001815 dprintf(fd, "\nOutput thread %p type %d (%s):\n", this, type(), threadTypeToString(type()));
Glenn Kasten44182c22015-03-05 17:12:23 -08001816
1817 dumpBase(fd, args);
1818
Elliott Hughes87cebad2014-05-22 10:14:43 -07001819 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001820 dprintf(fd, " Last write occurred (msecs): %llu\n",
1821 (unsigned long long) ns2ms(systemTime() - mLastWriteTime));
Elliott Hughes87cebad2014-05-22 10:14:43 -07001822 dprintf(fd, " Total writes: %d\n", mNumWrites);
1823 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1824 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1825 dprintf(fd, " Suspend count: %d\n", mSuspended);
1826 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1827 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1828 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1829 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08001830 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001831 AudioStreamOut *output = mOutput;
1832 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
1833 String8 flagsAsString = outputFlagsToString(flags);
1834 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n", output, flags, flagsAsString.string());
Andy Hungb54c8542016-09-21 12:55:15 -07001835 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
1836 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
1837 if (mPipeSink.get() != nullptr) {
1838 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
1839 }
1840 if (output != nullptr) {
1841 dprintf(fd, " Hal stream dump:\n");
1842 (void)output->stream->dump(fd);
1843 }
Eric Laurent81784c32012-11-19 14:55:58 -08001844}
1845
1846// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001847
1848void AudioFlinger::PlaybackThread::onFirstRef()
1849{
Glenn Kastend7dca052015-03-05 16:05:54 -08001850 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001851}
1852
1853// ThreadBase virtuals
1854void AudioFlinger::PlaybackThread::preExit()
1855{
1856 ALOGV(" preExit()");
1857 // FIXME this is using hard-coded strings but in the future, this functionality will be
1858 // converted to use audio HAL extensions required to support tunneling
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001859 status_t result = mOutput->stream->setParameters(String8("exiting=1"));
1860 ALOGE_IF(result != OK, "Error when setting parameters on exit: %d", result);
Eric Laurent81784c32012-11-19 14:55:58 -08001861}
1862
1863// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1864sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1865 const sp<AudioFlinger::Client>& client,
1866 audio_stream_type_t streamType,
1867 uint32_t sampleRate,
1868 audio_format_t format,
1869 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001870 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001871 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08001872 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07001873 audio_output_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08001874 pid_t tid,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001875 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -08001876 status_t *status)
1877{
Glenn Kasten74935e42013-12-19 08:56:45 -08001878 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001879 sp<Track> track;
1880 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07001881 audio_output_flags_t outputFlags = mOutput->flags;
1882
1883 // special case for FAST flag considered OK if fast mixer is present
1884 if (hasFastMixer()) {
1885 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
1886 }
1887
1888 // Check if requested flags are compatible with output stream flags
1889 if ((*flags & outputFlags) != *flags) {
1890 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
1891 *flags, outputFlags);
1892 *flags = (audio_output_flags_t)(*flags & outputFlags);
1893 }
Eric Laurent81784c32012-11-19 14:55:58 -08001894
Eric Laurent81784c32012-11-19 14:55:58 -08001895 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07001896 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08001897 if (
Eric Laurent81784c32012-11-19 14:55:58 -08001898 // PCM data
1899 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001900 // TODO: extract as a data library function that checks that a computationally
1901 // expensive downmixer is not required: isFastOutputChannelConversion()
Andy Hung9a592762014-07-21 21:56:01 -07001902 (channelMask == mChannelMask ||
Andy Hung1f439e12015-05-19 12:57:41 -07001903 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1904 (channelMask == AUDIO_CHANNEL_OUT_MONO
1905 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001906 // hardware sample rate
1907 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001908 // normal mixer has an associated fast mixer
1909 hasFastMixer() &&
1910 // there are sufficient fast track slots available
1911 (mFastTrackAvailMask != 0)
1912 // FIXME test that MixerThread for this fast track has a capable output HAL
1913 // FIXME add a permission test also?
1914 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07001915 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
1916 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001917 // read the fast track multiplier property the first time it is needed
1918 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1919 if (ok != 0) {
1920 ALOGE("%s pthread_once failed: %d", __func__, ok);
1921 }
Andy Hunge0a269a2016-03-23 15:13:42 -07001922 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08001923 }
Eric Laurent4c415062016-06-17 16:14:16 -07001924
1925 // check compatibility with audio effects.
1926 { // scope for mLock
1927 Mutex::Autolock _l(mLock);
1928 // do not accept RAW flag if post processing are present. Note that post processing on
1929 // a fast mixer are necessarily hardware
1930 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE);
1931 if (chain != 0) {
Eric Laurent122f7e72016-06-29 11:53:29 -07001932 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_RAW) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07001933 "AUDIO_OUTPUT_FLAG_RAW denied: post processing effect present");
1934 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_RAW);
1935 }
1936 // Do not accept FAST flag if software global effects are present
1937 chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
1938 if (chain != 0) {
Eric Laurent122f7e72016-06-29 11:53:29 -07001939 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_RAW) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07001940 "AUDIO_OUTPUT_FLAG_RAW denied: global effect present");
1941 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_RAW);
1942 if (chain->hasSoftwareEffect()) {
1943 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: software global effect present");
1944 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
1945 }
1946 }
1947 // Do not accept FAST flag if the session has software effects
1948 chain = getEffectChain_l(sessionId);
1949 if (chain != 0) {
Eric Laurent122f7e72016-06-29 11:53:29 -07001950 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_RAW) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07001951 "AUDIO_OUTPUT_FLAG_RAW denied: effect present on session");
1952 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_RAW);
1953 if (chain->hasSoftwareEffect()) {
1954 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: software effect present on session");
1955 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
1956 }
1957 }
1958 }
Eric Laurent122f7e72016-06-29 11:53:29 -07001959 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07001960 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
1961 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08001962 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001963 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
1964 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07001965 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001966 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08001967 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001968 audio_is_linear_pcm(format),
1969 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07001970 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08001971 }
1972 }
1973 // For normal PCM streaming tracks, update minimum frame count.
1974 // For compatibility with AudioTrack calculation, buffer depth is forced
1975 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1976 // This is probably too conservative, but legacy application code may depend on it.
1977 // If you change this calculation, also review the start threshold which is related.
Eric Laurent05067782016-06-01 18:27:28 -07001978 if (!(*flags & AUDIO_OUTPUT_FLAG_FAST)
Phil Burkfdb3c072016-02-09 10:47:02 -08001979 && audio_has_proportional_frames(format) && sharedBuffer == 0) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001980 // this must match AudioTrack.cpp calculateMinFrameCount().
1981 // TODO: Move to a common library
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001982 uint32_t latencyMs = 0;
1983 lStatus = mOutput->stream->getLatency(&latencyMs);
1984 if (lStatus != OK) {
1985 ALOGE("Error when retrieving output stream latency: %d", lStatus);
1986 goto Exit;
1987 }
Eric Laurent81784c32012-11-19 14:55:58 -08001988 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1989 if (minBufCount < 2) {
1990 minBufCount = 2;
1991 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07001992 // For normal mixing tracks, if speed is > 1.0f (normal), AudioTrack
1993 // or the client should compute and pass in a larger buffer request.
Andy Hung0e48d252015-01-26 11:43:15 -08001994 size_t minFrameCount =
Andy Hung8edb8dc2015-03-26 19:13:55 -07001995 minBufCount * sourceFramesNeededWithTimestretch(
1996 sampleRate, mNormalFrameCount,
1997 mSampleRate, AUDIO_TIMESTRETCH_SPEED_NORMAL /*speed*/);
Andy Hung0e48d252015-01-26 11:43:15 -08001998 if (frameCount < minFrameCount) { // including frameCount == 0
Eric Laurent81784c32012-11-19 14:55:58 -08001999 frameCount = minFrameCount;
2000 }
Eric Laurent81784c32012-11-19 14:55:58 -08002001 }
Glenn Kasten74935e42013-12-19 08:56:45 -08002002 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002003
Glenn Kastenc3df8382014-03-13 15:05:25 -07002004 switch (mType) {
2005
2006 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002007 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002008 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002009 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2010 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002011 sampleRate, format, channelMask, mOutput, mFormat);
2012 lStatus = BAD_VALUE;
2013 goto Exit;
2014 }
2015 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002016 break;
2017
2018 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002019 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002020 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2021 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002022 sampleRate, format, channelMask, mOutput, mFormat);
2023 lStatus = BAD_VALUE;
2024 goto Exit;
2025 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002026 break;
2027
2028 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002029 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002030 ALOGE("createTrack_l() Bad parameter: format %#x \""
2031 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002032 format, mOutput, mFormat);
2033 lStatus = BAD_VALUE;
2034 goto Exit;
2035 }
Andy Hungcd044842014-08-07 11:04:34 -07002036 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002037 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2038 lStatus = BAD_VALUE;
2039 goto Exit;
2040 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002041 break;
2042
Eric Laurent81784c32012-11-19 14:55:58 -08002043 }
2044
2045 lStatus = initCheck();
2046 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002047 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002048 goto Exit;
2049 }
2050
2051 { // scope for mLock
2052 Mutex::Autolock _l(mLock);
2053
2054 // all tracks in same audio session must share the same routing strategy otherwise
2055 // conflicts will happen when tracks are moved from one output to another by audio policy
2056 // manager
2057 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
2058 for (size_t i = 0; i < mTracks.size(); ++i) {
2059 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002060 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002061 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
2062 if (sessionId == t->sessionId() && strategy != actual) {
2063 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2064 strategy, actual);
2065 lStatus = BAD_VALUE;
2066 goto Exit;
2067 }
2068 }
2069 }
2070
Glenn Kastend79072e2016-01-06 08:41:20 -08002071 track = new Track(this, client, streamType, sampleRate, format,
2072 channelMask, frameCount, NULL, sharedBuffer,
2073 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT);
Glenn Kasten03003332013-08-06 15:40:54 -07002074
Glenn Kasten03003332013-08-06 15:40:54 -07002075 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2076 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002077 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002078 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002079 goto Exit;
2080 }
2081 mTracks.add(track);
2082
2083 sp<EffectChain> chain = getEffectChain_l(sessionId);
2084 if (chain != 0) {
2085 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2086 track->setMainBuffer(chain->inBuffer());
2087 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
2088 chain->incTrackCnt();
2089 }
2090
Eric Laurent05067782016-06-01 18:27:28 -07002091 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002092 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2093 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2094 // so ask activity manager to do this on our behalf
2095 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
2096 }
2097 }
2098
2099 lStatus = NO_ERROR;
2100
2101Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002102 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002103 return track;
2104}
2105
2106uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2107{
2108 return latency;
2109}
2110
2111uint32_t AudioFlinger::PlaybackThread::latency() const
2112{
2113 Mutex::Autolock _l(mLock);
2114 return latency_l();
2115}
2116uint32_t AudioFlinger::PlaybackThread::latency_l() const
2117{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002118 uint32_t latency;
2119 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2120 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002121 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002122 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002123}
2124
2125void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2126{
2127 Mutex::Autolock _l(mLock);
2128 // Don't apply master volume in SW if our HAL can do it for us.
2129 if (mOutput && mOutput->audioHwDev &&
2130 mOutput->audioHwDev->canSetMasterVolume()) {
2131 mMasterVolume = 1.0;
2132 } else {
2133 mMasterVolume = value;
2134 }
2135}
2136
2137void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2138{
2139 Mutex::Autolock _l(mLock);
2140 // Don't apply master mute in SW if our HAL can do it for us.
2141 if (mOutput && mOutput->audioHwDev &&
2142 mOutput->audioHwDev->canSetMasterMute()) {
2143 mMasterMute = false;
2144 } else {
2145 mMasterMute = muted;
2146 }
2147}
2148
2149void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2150{
2151 Mutex::Autolock _l(mLock);
2152 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002153 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002154}
2155
2156void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2157{
2158 Mutex::Autolock _l(mLock);
2159 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002160 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002161}
2162
2163float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2164{
2165 Mutex::Autolock _l(mLock);
2166 return mStreamTypes[stream].volume;
2167}
2168
2169// addTrack_l() must be called with ThreadBase::mLock held
2170status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2171{
2172 status_t status = ALREADY_EXISTS;
2173
Eric Laurent81784c32012-11-19 14:55:58 -08002174 if (mActiveTracks.indexOf(track) < 0) {
2175 // the track is newly added, make sure it fills up all its
2176 // buffers before playing. This is to ensure the client will
2177 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002178 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002179 TrackBase::track_state state = track->mState;
2180 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002181 status = AudioSystem::startOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002182 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002183 mLock.lock();
2184 // abort track was stopped/paused while we released the lock
2185 if (state != track->mState) {
2186 if (status == NO_ERROR) {
2187 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002188 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002189 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002190 mLock.lock();
2191 }
2192 return INVALID_OPERATION;
2193 }
2194 // abort if start is rejected by audio policy manager
2195 if (status != NO_ERROR) {
2196 return PERMISSION_DENIED;
2197 }
2198#ifdef ADD_BATTERY_DATA
2199 // to track the speaker usage
2200 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2201#endif
2202 }
2203
Eric Laurent51716182016-02-29 18:00:56 -08002204 // set retry count for buffer fill
2205 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002206 if (track->isStopping_1()) {
2207 track->mRetryCount = kMaxTrackStopRetriesOffload;
2208 } else {
2209 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2210 }
2211 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002212 } else {
2213 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002214 track->mFillingUpStatus =
2215 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002216 }
2217
Eric Laurent81784c32012-11-19 14:55:58 -08002218 track->mResetDone = false;
2219 track->mPresentationCompleteFrames = 0;
2220 mActiveTracks.add(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002221 mWakeLockUids.add(track->uid());
2222 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07002223 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07002224 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2225 if (chain != 0) {
2226 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2227 track->sessionId());
2228 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002229 }
2230
2231 status = NO_ERROR;
2232 }
2233
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002234 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002235 return status;
2236}
2237
Eric Laurentbfb1b832013-01-07 09:53:42 -08002238bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002239{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002240 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002241 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002242 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2243 track->mState = TrackBase::STOPPED;
2244 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002245 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002246 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002247 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002248 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002249
2250 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002251}
2252
2253void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2254{
2255 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
2256 mTracks.remove(track);
2257 deleteTrackName_l(track->name());
2258 // redundant as track is about to be destroyed, for dumpsys only
2259 track->mName = -1;
2260 if (track->isFastTrack()) {
2261 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002262 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002263 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2264 mFastTrackAvailMask |= 1 << index;
2265 // redundant as track is about to be destroyed, for dumpsys only
2266 track->mFastIndex = -1;
2267 }
2268 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2269 if (chain != 0) {
2270 chain->decTrackCnt();
2271 }
2272}
2273
Eric Laurentede6c3b2013-09-19 14:37:46 -07002274void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002275{
2276 // Thread could be blocked waiting for async
2277 // so signal it to handle state changes immediately
2278 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
2279 // be lost so we also flag to prevent it blocking on mWaitWorkCV
2280 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002281 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002282}
2283
Eric Laurent81784c32012-11-19 14:55:58 -08002284String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2285{
Eric Laurent81784c32012-11-19 14:55:58 -08002286 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002287 String8 out_s8;
2288 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2289 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002290 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002291 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002292}
2293
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002294void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002295 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2296 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002297
Eric Laurent73e26b62015-04-27 16:55:58 -07002298 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002299
2300 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002301 case AUDIO_OUTPUT_OPENED:
2302 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002303 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002304 desc->mChannelMask = mChannelMask;
2305 desc->mSamplingRate = mSampleRate;
2306 desc->mFormat = mFormat;
2307 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002308 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002309 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002310 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002311 break;
2312
Eric Laurent73e26b62015-04-27 16:55:58 -07002313 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002314 default:
2315 break;
2316 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002317 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002318}
2319
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002320void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002321{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002322 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002323}
2324
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002325void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002326{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002327 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002328}
2329
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002330void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002331{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002332 mCallbackThread->setAsyncError();
2333}
2334
Eric Laurent3b4529e2013-09-05 18:09:19 -07002335void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002336{
2337 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002338 // reject out of sequence requests
2339 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2340 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002341 mWaitWorkCV.signal();
2342 }
2343}
2344
Eric Laurent3b4529e2013-09-05 18:09:19 -07002345void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002346{
2347 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002348 // reject out of sequence requests
2349 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
2350 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002351 mWaitWorkCV.signal();
2352 }
2353}
2354
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002355void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002356{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002357 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002358 mSampleRate = mOutput->getSampleRate();
2359 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002360 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002361 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002362 }
Andy Hung9a592762014-07-21 21:56:01 -07002363 if ((mType == MIXER || mType == DUPLICATING)
2364 && !isValidPcmSinkChannelMask(mChannelMask)) {
2365 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2366 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002367 }
Andy Hunge5412692014-05-16 11:25:07 -07002368 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002369
2370 // Get actual HAL format.
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002371 status_t result = mOutput->stream->getFormat(&mHALFormat);
2372 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002373 // Get format from the shim, which will be different than the HAL format
2374 // if playing compressed audio over HDMI passthrough.
2375 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002376 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002377 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002378 }
Andy Hung6146c082014-03-18 11:56:15 -07002379 if ((mType == MIXER || mType == DUPLICATING)
2380 && !isValidPcmSinkFormat(mFormat)) {
2381 LOG_FATAL("HAL format %#x not supported for mixed output",
2382 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002383 }
Phil Burk062e67a2015-02-11 13:40:50 -08002384 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002385 result = mOutput->stream->getBufferSize(&mBufferSize);
2386 LOG_ALWAYS_FATAL_IF(result != OK,
2387 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07002388 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002389 if (mFrameCount & 15) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002390 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002391 mFrameCount);
2392 }
2393
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002394 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
2395 if (mOutput->stream->setCallback(this) == OK) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002396 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002397 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002398 }
2399 }
2400
Eric Laurentd1f69b02014-12-15 14:33:13 -08002401 mHwSupportsPause = false;
2402 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002403 bool supportsPause = false, supportsResume = false;
2404 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
2405 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002406 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002407 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002408 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002409 } else if (supportsResume) {
2410 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08002411 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002412 }
2413 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002414 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2415 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2416 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002417
Andy Hungfbfc3952015-01-15 13:33:51 -08002418 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2419 // For best precision, we use float instead of the associated output
2420 // device format (typically PCM 16 bit).
2421
2422 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2423 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2424 mBufferSize = mFrameSize * mFrameCount;
2425
2426 // TODO: We currently use the associated output device channel mask and sample rate.
2427 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2428 // (if a valid mask) to avoid premature downmix.
2429 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2430 // instead of the output device sample rate to avoid loss of high frequency information.
2431 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2432 }
2433
Andy Hung09a50072014-02-27 14:30:47 -08002434 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002435 double multiplier = 1.0;
2436 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2437 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002438 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2439 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002440
Eric Laurent81784c32012-11-19 14:55:58 -08002441 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2442 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2443 maxNormalFrameCount = maxNormalFrameCount & ~15;
2444 if (maxNormalFrameCount < minNormalFrameCount) {
2445 maxNormalFrameCount = minNormalFrameCount;
2446 }
2447 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2448 if (multiplier <= 1.0) {
2449 multiplier = 1.0;
2450 } else if (multiplier <= 2.0) {
2451 if (2 * mFrameCount <= maxNormalFrameCount) {
2452 multiplier = 2.0;
2453 } else {
2454 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2455 }
2456 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002457 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002458 }
2459 }
2460 mNormalFrameCount = multiplier * mFrameCount;
2461 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002462 if (mType == MIXER || mType == DUPLICATING) {
2463 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2464 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002465 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002466 mNormalFrameCount);
2467
Andy Hung08fb1742015-05-31 23:22:10 -07002468 // Check if we want to throttle the processing to no more than 2x normal rate
2469 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002470 mThreadThrottleTimeMs = 0;
2471 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002472 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2473
Andy Hung010a1a12014-03-13 13:57:33 -07002474 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2475 // Originally this was int16_t[] array, need to remove legacy implications.
2476 free(mSinkBuffer);
2477 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002478 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2479 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2480 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002481 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002482
Andy Hung69aed5f2014-02-25 17:24:40 -08002483 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2484 // drives the output.
2485 free(mMixerBuffer);
2486 mMixerBuffer = NULL;
2487 if (mMixerBufferEnabled) {
2488 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2489 mMixerBufferSize = mNormalFrameCount * mChannelCount
2490 * audio_bytes_per_sample(mMixerBufferFormat);
2491 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2492 }
Andy Hung98ef9782014-03-04 14:46:50 -08002493 free(mEffectBuffer);
2494 mEffectBuffer = NULL;
2495 if (mEffectBufferEnabled) {
2496 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2497 mEffectBufferSize = mNormalFrameCount * mChannelCount
2498 * audio_bytes_per_sample(mEffectBufferFormat);
2499 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2500 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002501
Eric Laurent81784c32012-11-19 14:55:58 -08002502 // force reconfiguration of effect chains and engines to take new buffer size and audio
2503 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002504 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002505 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2506 // matter.
2507 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2508 Vector< sp<EffectChain> > effectChains = mEffectChains;
2509 for (size_t i = 0; i < effectChains.size(); i ++) {
2510 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2511 }
2512}
2513
2514
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002515status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002516{
2517 if (halFrames == NULL || dspFrames == NULL) {
2518 return BAD_VALUE;
2519 }
2520 Mutex::Autolock _l(mLock);
2521 if (initCheck() != NO_ERROR) {
2522 return INVALID_OPERATION;
2523 }
Andy Hung818e7a32016-02-16 18:08:07 -08002524 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002525 *halFrames = framesWritten;
2526
2527 if (isSuspended()) {
2528 // return an estimation of rendered frames when the output is suspended
2529 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002530 *dspFrames = (uint32_t)
2531 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002532 return NO_ERROR;
2533 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002534 status_t status;
2535 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002536 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002537 *dspFrames = (size_t)frames;
2538 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002539 }
2540}
2541
Eric Laurent4c415062016-06-17 16:14:16 -07002542// hasAudioSession_l() must be called with ThreadBase::mLock held
2543uint32_t AudioFlinger::PlaybackThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08002544{
Eric Laurent81784c32012-11-19 14:55:58 -08002545 uint32_t result = 0;
2546 if (getEffectChain_l(sessionId) != 0) {
2547 result = EFFECT_SESSION;
2548 }
2549
2550 for (size_t i = 0; i < mTracks.size(); ++i) {
2551 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002552 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002553 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07002554 if (track->isFastTrack()) {
2555 result |= FAST_SESSION;
2556 }
Eric Laurent81784c32012-11-19 14:55:58 -08002557 break;
2558 }
2559 }
2560
2561 return result;
2562}
2563
Glenn Kastend848eb42016-03-08 13:42:11 -08002564uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08002565{
2566 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2567 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2568 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2569 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2570 }
2571 for (size_t i = 0; i < mTracks.size(); i++) {
2572 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002573 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002574 return AudioSystem::getStrategyForStream(track->streamType());
2575 }
2576 }
2577 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2578}
2579
2580
Phil Burk062e67a2015-02-11 13:40:50 -08002581AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002582{
2583 Mutex::Autolock _l(mLock);
2584 return mOutput;
2585}
2586
Phil Burk062e67a2015-02-11 13:40:50 -08002587AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002588{
2589 Mutex::Autolock _l(mLock);
2590 AudioStreamOut *output = mOutput;
2591 mOutput = NULL;
2592 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2593 // must push a NULL and wait for ack
2594 mOutputSink.clear();
2595 mPipeSink.clear();
2596 mNormalSink.clear();
2597 return output;
2598}
2599
2600// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002601sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08002602{
2603 if (mOutput == NULL) {
2604 return NULL;
2605 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002606 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08002607}
2608
2609uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2610{
2611 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2612}
2613
2614status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2615{
2616 if (!isValidSyncEvent(event)) {
2617 return BAD_VALUE;
2618 }
2619
2620 Mutex::Autolock _l(mLock);
2621
2622 for (size_t i = 0; i < mTracks.size(); ++i) {
2623 sp<Track> track = mTracks[i];
2624 if (event->triggerSession() == track->sessionId()) {
2625 (void) track->setSyncEvent(event);
2626 return NO_ERROR;
2627 }
2628 }
2629
2630 return NAME_NOT_FOUND;
2631}
2632
2633bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2634{
2635 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2636}
2637
2638void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2639 const Vector< sp<Track> >& tracksToRemove)
2640{
2641 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002642 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002643 for (size_t i = 0 ; i < count ; i++) {
2644 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002645 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002646 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002647 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002648#ifdef ADD_BATTERY_DATA
2649 // to track the speaker usage
2650 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2651#endif
2652 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002653 AudioSystem::releaseOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002654 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002655 }
Eric Laurent81784c32012-11-19 14:55:58 -08002656 }
2657 }
2658 }
Eric Laurent81784c32012-11-19 14:55:58 -08002659}
2660
2661void AudioFlinger::PlaybackThread::checkSilentMode_l()
2662{
2663 if (!mMasterMute) {
2664 char value[PROPERTY_VALUE_MAX];
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07002665 if (mOutDevice == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) {
2666 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
2667 return;
2668 }
Eric Laurent81784c32012-11-19 14:55:58 -08002669 if (property_get("ro.audio.silent", value, "0") > 0) {
2670 char *endptr;
2671 unsigned long ul = strtoul(value, &endptr, 0);
2672 if (*endptr == '\0' && ul != 0) {
2673 ALOGD("Silence is golden");
2674 // The setprop command will not allow a property to be changed after
2675 // the first time it is set, so we don't have to worry about un-muting.
2676 setMasterMute_l(true);
2677 }
2678 }
2679 }
2680}
2681
2682// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002683ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002684{
Eric Laurent81784c32012-11-19 14:55:58 -08002685 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002686 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002687 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002688
2689 // If an NBAIO sink is present, use it to write the normal mixer's submix
2690 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002691
Andy Hung010a1a12014-03-13 13:57:33 -07002692 const size_t count = mBytesRemaining / mFrameSize;
2693
Simon Wilson2d590962012-11-29 15:18:50 -08002694 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002695 // update the setpoint when AudioFlinger::mScreenState changes
2696 uint32_t screenState = AudioFlinger::mScreenState;
2697 if (screenState != mScreenState) {
2698 mScreenState = screenState;
2699 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2700 if (pipe != NULL) {
2701 pipe->setAvgFrames((mScreenState & 1) ?
2702 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2703 }
2704 }
Andy Hung010a1a12014-03-13 13:57:33 -07002705 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002706 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002707 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002708 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002709 } else {
2710 bytesWritten = framesWritten;
2711 }
2712 // otherwise use the HAL / AudioStreamOut directly
2713 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002714 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002715
Eric Laurentbfb1b832013-01-07 09:53:42 -08002716 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002717 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2718 mWriteAckSequence += 2;
2719 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002720 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002721 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002722 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002723 // FIXME We should have an implementation of timestamps for direct output threads.
2724 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002725 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurent51716182016-02-29 18:00:56 -08002726
Eric Laurentbfb1b832013-01-07 09:53:42 -08002727 if (mUseAsyncWrite &&
2728 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2729 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002730 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002731 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002732 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002733 }
Eric Laurent81784c32012-11-19 14:55:58 -08002734 }
2735
Eric Laurent81784c32012-11-19 14:55:58 -08002736 mNumWrites++;
2737 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002738 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002739 return bytesWritten;
2740}
2741
2742void AudioFlinger::PlaybackThread::threadLoop_drain()
2743{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002744 bool supportsDrain = false;
2745 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002746 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2747 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002748 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2749 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002750 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002751 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002752 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07002753 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002754 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002755 }
2756}
2757
2758void AudioFlinger::PlaybackThread::threadLoop_exit()
2759{
Eric Laurent275e8e92014-11-30 15:14:47 -08002760 {
2761 Mutex::Autolock _l(mLock);
2762 for (size_t i = 0; i < mTracks.size(); i++) {
2763 sp<Track> track = mTracks[i];
2764 track->invalidate();
2765 }
2766 }
Eric Laurent81784c32012-11-19 14:55:58 -08002767}
2768
2769/*
2770The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002771 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002772 - mActiveSleepTimeUs from activeSleepTimeUs()
2773 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08002774 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
2775 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08002776 - maxPeriod from frame count and sample rate (MIXER only)
2777
2778The parameters that affect these derived values are:
2779 - frame count
2780 - frame size
2781 - sample rate
2782 - device type: A2DP or not
2783 - device latency
2784 - format: PCM or not
2785 - active sleep time
2786 - idle sleep time
2787*/
2788
2789void AudioFlinger::PlaybackThread::cacheParameters_l()
2790{
Andy Hung25c2dac2014-02-27 14:56:00 -08002791 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002792 mActiveSleepTimeUs = activeSleepTimeUs();
2793 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08002794
2795 // make sure standby delay is not too short when connected to an A2DP sink to avoid
2796 // truncating audio when going to standby.
2797 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
2798 if ((mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != 0) {
2799 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
2800 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
2801 }
2802 }
Eric Laurent81784c32012-11-19 14:55:58 -08002803}
2804
Eric Laurent13084622016-05-17 10:51:49 -07002805bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08002806{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002807 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08002808 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07002809 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002810 size_t size = mTracks.size();
2811 for (size_t i = 0; i < size; i++) {
2812 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07002813 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002814 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07002815 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002816 }
2817 }
Eric Laurent13084622016-05-17 10:51:49 -07002818 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08002819}
2820
Haynes Mathew George05317d22016-05-03 16:34:26 -07002821void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2822{
2823 Mutex::Autolock _l(mLock);
2824 invalidateTracks_l(streamType);
2825}
2826
Eric Laurent81784c32012-11-19 14:55:58 -08002827status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2828{
Glenn Kastend848eb42016-03-08 13:42:11 -08002829 audio_session_t session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002830 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2831 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002832 bool ownsBuffer = false;
2833
2834 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Glenn Kastend848eb42016-03-08 13:42:11 -08002835 if (session > AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002836 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002837 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002838 if (mType != DIRECT) {
2839 size_t numSamples = mNormalFrameCount * mChannelCount;
2840 buffer = new int16_t[numSamples];
2841 memset(buffer, 0, numSamples * sizeof(int16_t));
2842 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2843 ownsBuffer = true;
2844 }
2845
2846 // Attach all tracks with same session ID to this chain.
2847 for (size_t i = 0; i < mTracks.size(); ++i) {
2848 sp<Track> track = mTracks[i];
2849 if (session == track->sessionId()) {
2850 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2851 buffer);
2852 track->setMainBuffer(buffer);
2853 chain->incTrackCnt();
2854 }
2855 }
2856
2857 // indicate all active tracks in the chain
2858 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2859 sp<Track> track = mActiveTracks[i].promote();
2860 if (track == 0) {
2861 continue;
2862 }
2863 if (session == track->sessionId()) {
2864 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2865 chain->incActiveTrackCnt();
2866 }
2867 }
2868 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002869 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08002870 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002871 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2872 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002873 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Glenn Kastend848eb42016-03-08 13:42:11 -08002874 // chains list in order to be processed last as it contains output stage effects.
Eric Laurent81784c32012-11-19 14:55:58 -08002875 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2876 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08002877 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08002878 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08002879 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08002880 // Effect chain for other sessions are inserted at beginning of effect
2881 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08002882 // sessions is not important.
2883 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
2884 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX,
2885 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08002886 size_t size = mEffectChains.size();
2887 size_t i = 0;
2888 for (i = 0; i < size; i++) {
2889 if (mEffectChains[i]->sessionId() < session) {
2890 break;
2891 }
2892 }
2893 mEffectChains.insertAt(chain, i);
2894 checkSuspendOnAddEffectChain_l(chain);
2895
2896 return NO_ERROR;
2897}
2898
2899size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2900{
Glenn Kastend848eb42016-03-08 13:42:11 -08002901 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08002902
2903 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2904
2905 for (size_t i = 0; i < mEffectChains.size(); i++) {
2906 if (chain == mEffectChains[i]) {
2907 mEffectChains.removeAt(i);
2908 // detach all active tracks from the chain
2909 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2910 sp<Track> track = mActiveTracks[i].promote();
2911 if (track == 0) {
2912 continue;
2913 }
2914 if (session == track->sessionId()) {
2915 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2916 chain.get(), session);
2917 chain->decActiveTrackCnt();
2918 }
2919 }
2920
2921 // detach all tracks with same session ID from this chain
2922 for (size_t i = 0; i < mTracks.size(); ++i) {
2923 sp<Track> track = mTracks[i];
2924 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002925 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002926 chain->decTrackCnt();
2927 }
2928 }
2929 break;
2930 }
2931 }
2932 return mEffectChains.size();
2933}
2934
2935status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002936 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08002937{
2938 Mutex::Autolock _l(mLock);
2939 return attachAuxEffect_l(track, EffectId);
2940}
2941
2942status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002943 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08002944{
2945 status_t status = NO_ERROR;
2946
2947 if (EffectId == 0) {
2948 track->setAuxBuffer(0, NULL);
2949 } else {
2950 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2951 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2952 if (effect != 0) {
2953 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2954 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2955 } else {
2956 status = INVALID_OPERATION;
2957 }
2958 } else {
2959 status = BAD_VALUE;
2960 }
2961 }
2962 return status;
2963}
2964
2965void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2966{
2967 for (size_t i = 0; i < mTracks.size(); ++i) {
2968 sp<Track> track = mTracks[i];
2969 if (track->auxEffectId() == effectId) {
2970 attachAuxEffect_l(track, 0);
2971 }
2972 }
2973}
2974
2975bool AudioFlinger::PlaybackThread::threadLoop()
2976{
2977 Vector< sp<Track> > tracksToRemove;
2978
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002979 mStandbyTimeNs = systemTime();
Andy Hung69488c42016-05-16 18:43:33 -07002980 nsecs_t lastWriteFinished = -1; // time last server write completed
2981 int64_t lastFramesWritten = -1; // track changes in timestamp server frames written
Eric Laurent81784c32012-11-19 14:55:58 -08002982
2983 // MIXER
2984 nsecs_t lastWarning = 0;
2985
2986 // DUPLICATING
2987 // FIXME could this be made local to while loop?
2988 writeFrames = 0;
2989
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002990 int lastGeneration = 0;
2991
Eric Laurent81784c32012-11-19 14:55:58 -08002992 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002993 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002994
2995 if (mType == MIXER) {
2996 sleepTimeShift = 0;
2997 }
2998
2999 CpuStats cpuStats;
3000 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3001
3002 acquireWakeLock();
3003
Glenn Kasten9e58b552013-01-18 15:09:48 -08003004 // mNBLogWriter->log can only be called while thread mutex mLock is held.
3005 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3006 // and then that string will be logged at the next convenient opportunity.
3007 const char *logString = NULL;
3008
Eric Laurent664539d2013-09-23 18:24:31 -07003009 checkSilentMode_l();
3010
Eric Laurent81784c32012-11-19 14:55:58 -08003011 while (!exitPending())
3012 {
3013 cpuStats.sample(myName);
3014
3015 Vector< sp<EffectChain> > effectChains;
3016
Eric Laurent81784c32012-11-19 14:55:58 -08003017 { // scope for mLock
3018
3019 Mutex::Autolock _l(mLock);
3020
Eric Laurent021cf962014-05-13 10:18:14 -07003021 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07003022
Glenn Kasten9e58b552013-01-18 15:09:48 -08003023 if (logString != NULL) {
3024 mNBLogWriter->logTimestamp();
3025 mNBLogWriter->log(logString);
3026 logString = NULL;
3027 }
3028
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003029 // Gather the framesReleased counters for all active tracks,
Andy Hunge10393e2015-06-12 13:59:33 -07003030 // and associate with the sink frames written out. We need
3031 // this to convert the sink timestamp to the track timestamp.
Andy Hung69488c42016-05-16 18:43:33 -07003032 bool kernelLocationUpdate = false;
Andy Hunge10393e2015-06-12 13:59:33 -07003033 if (mNormalSink != 0) {
Andy Hungc54b1ff2016-02-23 14:07:07 -08003034 // Note: The DuplicatingThread may not have a mNormalSink.
Andy Hung818e7a32016-02-16 18:08:07 -08003035 // We always fetch the timestamp here because often the downstream
Andy Hung69488c42016-05-16 18:43:33 -07003036 // sink will block while writing.
Andy Hung818e7a32016-02-16 18:08:07 -08003037 ExtendedTimestamp timestamp; // use private copy to fetch
3038 (void) mNormalSink->getTimestamp(timestamp);
Andy Hung6d7b1192016-05-07 22:59:48 -07003039
3040 // We keep track of the last valid kernel position in case we are in underrun
3041 // and the normal mixer period is the same as the fast mixer period, or there
3042 // is some error from the HAL.
3043 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3044 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3045 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
3046 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3047 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
3048
3049 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3050 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
3051 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3052 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
Andy Hung69488c42016-05-16 18:43:33 -07003053 }
3054
3055 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3056 kernelLocationUpdate = true;
Andy Hung6d7b1192016-05-07 22:59:48 -07003057 } else {
Eric Laurent122f7e72016-06-29 11:53:29 -07003058 ALOGVV("getTimestamp error - no valid kernel position");
Andy Hung6d7b1192016-05-07 22:59:48 -07003059 }
3060
Andy Hung818e7a32016-02-16 18:08:07 -08003061 // copy over kernel info
3062 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
Andy Hung238fa3d2016-07-28 10:53:22 -07003063 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3064 + mSuspendedFrames; // add frames discarded when suspended
Andy Hung818e7a32016-02-16 18:08:07 -08003065 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
3066 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hungc54b1ff2016-02-23 14:07:07 -08003067 }
3068 // mFramesWritten for non-offloaded tracks are contiguous
3069 // even after standby() is called. This is useful for the track frame
3070 // to sink frame mapping.
Andy Hung69488c42016-05-16 18:43:33 -07003071 bool serverLocationUpdate = false;
3072 if (mFramesWritten != lastFramesWritten) {
3073 serverLocationUpdate = true;
3074 lastFramesWritten = mFramesWritten;
3075 }
3076 // Only update timestamps if there is a meaningful change.
3077 // Either the kernel timestamp must be valid or we have written something.
3078 if (kernelLocationUpdate || serverLocationUpdate) {
3079 if (serverLocationUpdate) {
3080 // use the time before we called the HAL write - it is a bit more accurate
3081 // to when the server last read data than the current time here.
3082 //
3083 // If we haven't written anything, mLastWriteTime will be -1
3084 // and we use systemTime().
3085 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
3086 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastWriteTime == -1
3087 ? systemTime() : mLastWriteTime;
3088 }
3089 const size_t size = mActiveTracks.size();
3090 for (size_t i = 0; i < size; ++i) {
3091 sp<Track> t = mActiveTracks[i].promote();
3092 if (t != 0 && !t->isFastTrack()) {
3093 t->updateTrackFrameInfo(
3094 t->mAudioTrackServerProxy->framesReleased(),
3095 mFramesWritten,
3096 mTimestamp);
3097 }
Andy Hunge10393e2015-06-12 13:59:33 -07003098 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07003099 }
3100
Eric Laurent81784c32012-11-19 14:55:58 -08003101 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003102 if (mSignalPending) {
3103 // A signal was raised while we were unlocked
3104 mSignalPending = false;
3105 } else if (waitingAsyncCallback_l()) {
3106 if (exitPending()) {
3107 break;
3108 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003109 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003110 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003111 releaseWakeLock_l();
3112 released = true;
Mikhail Naganove94c27a2016-08-18 17:31:46 -07003113 mWakeLockUids.clear();
3114 mActiveTracksGeneration++;
Marco Nelissen078538c2015-05-12 09:17:57 -07003115 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003116 ALOGV("wait async completion");
3117 mWaitWorkCV.wait(mLock);
3118 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003119 if (released) {
3120 acquireWakeLock_l();
3121 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003122 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3123 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003124
3125 continue;
3126 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003127 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003128 isSuspended()) {
3129 // put audio hardware into standby after short delay
3130 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003131
3132 threadLoop_standby();
3133
3134 mStandby = true;
3135 }
3136
3137 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
3138 // we're about to wait, flush the binder command buffer
3139 IPCThreadState::self()->flushCommands();
3140
3141 clearOutputTracks();
3142
3143 if (exitPending()) {
3144 break;
3145 }
3146
3147 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003148 mWakeLockUids.clear();
3149 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08003150 // wait until we have something to do...
3151 ALOGV("%s going to sleep", myName.string());
3152 mWaitWorkCV.wait(mLock);
3153 ALOGV("%s waking up", myName.string());
3154 acquireWakeLock_l();
3155
3156 mMixerStatus = MIXER_IDLE;
3157 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3158 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003159 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003160 checkSilentMode_l();
3161
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003162 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3163 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003164 if (mType == MIXER) {
3165 sleepTimeShift = 0;
3166 }
3167
3168 continue;
3169 }
3170 }
Eric Laurent81784c32012-11-19 14:55:58 -08003171 // mMixerStatusIgnoringFastTracks is also updated internally
3172 mMixerStatus = prepareTracks_l(&tracksToRemove);
3173
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003174 // compare with previously applied list
3175 if (lastGeneration != mActiveTracksGeneration) {
3176 // update wakelock
3177 updateWakeLockUids_l(mWakeLockUids);
3178 lastGeneration = mActiveTracksGeneration;
3179 }
3180
Eric Laurent81784c32012-11-19 14:55:58 -08003181 // prevent any changes in effect chain list and in each effect chain
3182 // during mixing and effect process as the audio buffers could be deleted
3183 // or modified if an effect is created or deleted
3184 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003185 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003186
Eric Laurentbfb1b832013-01-07 09:53:42 -08003187 if (mBytesRemaining == 0) {
3188 mCurrentWriteLength = 0;
3189 if (mMixerStatus == MIXER_TRACKS_READY) {
3190 // threadLoop_mix() sets mCurrentWriteLength
3191 threadLoop_mix();
3192 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3193 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003194 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003195 // must be written to HAL
3196 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003197 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003198 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003199 }
3200 }
Andy Hung98ef9782014-03-04 14:46:50 -08003201 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003202 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003203 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3204 // or mSinkBuffer (if there are no effects).
3205 //
3206 // This is done pre-effects computation; if effects change to
3207 // support higher precision, this needs to move.
3208 //
3209 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003210 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003211 if (mMixerBufferValid) {
3212 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3213 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3214
Andy Hung2ddee192015-12-18 17:34:44 -08003215 // mono blend occurs for mixer threads only (not direct or offloaded)
3216 // and is handled here if we're going directly to the sink.
3217 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003218 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3219 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003220 }
3221
Andy Hung98ef9782014-03-04 14:46:50 -08003222 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
3223 mNormalFrameCount * mChannelCount);
3224 }
3225
Eric Laurentbfb1b832013-01-07 09:53:42 -08003226 mBytesRemaining = mCurrentWriteLength;
3227 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003228 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3229 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3230 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3231 mBytesWritten += mBytesRemaining;
3232 mFramesWritten += framesRemaining;
3233 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003234 mBytesRemaining = 0;
3235 }
Eric Laurent81784c32012-11-19 14:55:58 -08003236
Eric Laurentbfb1b832013-01-07 09:53:42 -08003237 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003238 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003239 for (size_t i = 0; i < effectChains.size(); i ++) {
3240 effectChains[i]->process_l();
3241 }
Eric Laurent81784c32012-11-19 14:55:58 -08003242 }
3243 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003244 // Process effect chains for offloaded thread even if no audio
3245 // was read from audio track: process only updates effect state
3246 // and thus does have to be synchronized with audio writes but may have
3247 // to be called while waiting for async write callback
3248 if (mType == OFFLOAD) {
3249 for (size_t i = 0; i < effectChains.size(); i ++) {
3250 effectChains[i]->process_l();
3251 }
3252 }
Eric Laurent81784c32012-11-19 14:55:58 -08003253
Andy Hung98ef9782014-03-04 14:46:50 -08003254 // Only if the Effects buffer is enabled and there is data in the
3255 // Effects buffer (buffer valid), we need to
3256 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003257 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003258 if (mEffectBufferValid) {
3259 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003260
3261 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003262 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3263 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003264 }
3265
Andy Hung98ef9782014-03-04 14:46:50 -08003266 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
3267 mNormalFrameCount * mChannelCount);
3268 }
3269
Eric Laurent81784c32012-11-19 14:55:58 -08003270 // enable changes in effect chain
3271 unlockEffectChains(effectChains);
3272
Eric Laurentbfb1b832013-01-07 09:53:42 -08003273 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003274 // mSleepTimeUs == 0 means we must write to audio hardware
3275 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003276 ssize_t ret = 0;
Andy Hung69488c42016-05-16 18:43:33 -07003277 // We save lastWriteFinished here, as previousLastWriteFinished,
3278 // for throttling. On thread start, previousLastWriteFinished will be
3279 // set to -1, which properly results in no throttling after the first write.
3280 nsecs_t previousLastWriteFinished = lastWriteFinished;
3281 nsecs_t delta = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003282 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003283 // FIXME rewrite to reduce number of system calls
3284 mLastWriteTime = systemTime(); // also used for dumpsys
Andy Hung08fb1742015-05-31 23:22:10 -07003285 ret = threadLoop_write();
Andy Hung69488c42016-05-16 18:43:33 -07003286 lastWriteFinished = systemTime();
3287 delta = lastWriteFinished - mLastWriteTime;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003288 if (ret < 0) {
3289 mBytesRemaining = 0;
3290 } else {
3291 mBytesWritten += ret;
3292 mBytesRemaining -= ret;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003293 mFramesWritten += ret / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003294 }
3295 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3296 (mMixerStatus == MIXER_DRAIN_ALL)) {
3297 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003298 }
Andy Hung08fb1742015-05-31 23:22:10 -07003299 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003300 // write blocked detection
Andy Hung08fb1742015-05-31 23:22:10 -07003301 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003302 mNumDelayedWrites++;
Andy Hung69488c42016-05-16 18:43:33 -07003303 if ((lastWriteFinished - lastWarning) > kWarningThrottleNs) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003304 ATRACE_NAME("underrun");
3305 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003306 (unsigned long long) ns2ms(delta), mNumDelayedWrites, this);
Andy Hung69488c42016-05-16 18:43:33 -07003307 lastWarning = lastWriteFinished;
Glenn Kasten4944acb2013-08-19 08:39:20 -07003308 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003309 }
Andy Hung08fb1742015-05-31 23:22:10 -07003310
3311 if (mThreadThrottle
3312 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
3313 && ret > 0) { // we wrote something
3314 // Limit MixerThread data processing to no more than twice the
3315 // expected processing rate.
3316 //
3317 // This helps prevent underruns with NuPlayer and other applications
3318 // which may set up buffers that are close to the minimum size, or use
3319 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3320 //
3321 // The throttle smooths out sudden large data drains from the device,
3322 // e.g. when it comes out of standby, which often causes problems with
3323 // (1) mixer threads without a fast mixer (which has its own warm-up)
3324 // (2) minimum buffer sized tracks (even if the track is full,
3325 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07003326 //
3327 // Total time spent in last processing cycle equals time spent in
3328 // 1. threadLoop_write, as well as time spent in
3329 // 2. threadLoop_mix (significant for heavy mixing, especially
3330 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07003331
Andy Hung69488c42016-05-16 18:43:33 -07003332 // it's OK if deltaMs is an overestimate.
3333 const int32_t deltaMs =
3334 (lastWriteFinished - previousLastWriteFinished) / 1000000;
Andy Hung08fb1742015-05-31 23:22:10 -07003335 const int32_t throttleMs = mHalfBufferMs - deltaMs;
3336 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3337 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003338 // notify of throttle start on verbose log
3339 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3340 "mixer(%p) throttle begin:"
3341 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003342 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003343 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07003344 // Throttle must be attributed to the previous mixer loop's write time
3345 // to allow back-to-back throttling.
3346 lastWriteFinished += throttleMs * 1000000;
Andy Hung40eb1a12015-06-18 13:42:02 -07003347 } else {
3348 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3349 if (diff > 0) {
3350 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07003351 // but prevent spamming for bluetooth
3352 ALOGD_IF(!audio_is_a2dp_out_device(outDevice()),
3353 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07003354 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3355 }
Andy Hung08fb1742015-05-31 23:22:10 -07003356 }
3357 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003358 }
Eric Laurent81784c32012-11-19 14:55:58 -08003359
Eric Laurentbfb1b832013-01-07 09:53:42 -08003360 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003361 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07003362 Mutex::Autolock _l(mLock);
3363 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
3364 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08003365 }
Glenn Kastene7754022014-10-31 12:11:26 -07003366 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003367 }
Eric Laurent81784c32012-11-19 14:55:58 -08003368 }
3369
3370 // Finally let go of removed track(s), without the lock held
3371 // since we can't guarantee the destructors won't acquire that
3372 // same lock. This will also mutate and push a new fast mixer state.
3373 threadLoop_removeTracks(tracksToRemove);
3374 tracksToRemove.clear();
3375
3376 // FIXME I don't understand the need for this here;
3377 // it was in the original code but maybe the
3378 // assignment in saveOutputTracks() makes this unnecessary?
3379 clearOutputTracks();
3380
3381 // Effect chains will be actually deleted here if they were removed from
3382 // mEffectChains list during mixing or effects processing
3383 effectChains.clear();
3384
3385 // FIXME Note that the above .clear() is no longer necessary since effectChains
3386 // is now local to this block, but will keep it for now (at least until merge done).
3387 }
3388
Eric Laurentbfb1b832013-01-07 09:53:42 -08003389 threadLoop_exit();
3390
Eric Laurentcf817a22014-08-04 20:36:31 -07003391 if (!mStandby) {
3392 threadLoop_standby();
3393 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003394 }
3395
3396 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003397 mWakeLockUids.clear();
3398 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08003399
3400 ALOGV("Thread %p type %d exiting", this, mType);
3401 return false;
3402}
3403
Eric Laurentbfb1b832013-01-07 09:53:42 -08003404// removeTracks_l() must be called with ThreadBase::mLock held
3405void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3406{
3407 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003408 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003409 for (size_t i=0 ; i<count ; i++) {
3410 const sp<Track>& track = tracksToRemove.itemAt(i);
3411 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003412 mWakeLockUids.remove(track->uid());
3413 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003414 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3415 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3416 if (chain != 0) {
3417 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3418 track->sessionId());
3419 chain->decActiveTrackCnt();
3420 }
3421 if (track->isTerminated()) {
3422 removeTrack_l(track);
3423 }
3424 }
3425 }
3426
3427}
Eric Laurent81784c32012-11-19 14:55:58 -08003428
Eric Laurentaccc1472013-09-20 09:36:34 -07003429status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3430{
3431 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08003432 ExtendedTimestamp ets;
3433 status_t status = mNormalSink->getTimestamp(ets);
3434 if (status == NO_ERROR) {
3435 status = ets.getBestTimestamp(&timestamp);
3436 }
3437 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07003438 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003439 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003440 uint64_t position64;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003441 if (mOutput->getPresentationPosition(&position64, &timestamp.mTime) == OK) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003442 timestamp.mPosition = (uint32_t)position64;
3443 return NO_ERROR;
3444 }
3445 }
3446 return INVALID_OPERATION;
3447}
Eric Laurent1c333e22014-05-20 10:48:17 -07003448
Eric Laurent054d9d32015-04-24 08:48:48 -07003449status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3450 audio_patch_handle_t *handle)
3451{
Andy Hungf60abce2016-08-26 11:37:54 -07003452 status_t status;
3453 if (property_get_bool("af.patch_park", false /* default_value */)) {
3454 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3455 // or if HAL does not properly lock against access.
3456 AutoPark<FastMixer> park(mFastMixer);
3457 status = PlaybackThread::createAudioPatch_l(patch, handle);
3458 } else {
3459 status = PlaybackThread::createAudioPatch_l(patch, handle);
3460 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003461 return status;
3462}
3463
Eric Laurent1c333e22014-05-20 10:48:17 -07003464status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3465 audio_patch_handle_t *handle)
3466{
3467 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003468
3469 // store new device and send to effects
3470 audio_devices_t type = AUDIO_DEVICE_NONE;
3471 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3472 type |= patch->sinks[i].ext.device.type;
3473 }
3474
3475#ifdef ADD_BATTERY_DATA
3476 // when changing the audio output device, call addBatteryData to notify
3477 // the change
3478 if (mOutDevice != type) {
3479 uint32_t params = 0;
3480 // check whether speaker is on
3481 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3482 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003483 }
3484
Eric Laurent054d9d32015-04-24 08:48:48 -07003485 audio_devices_t deviceWithoutSpeaker
3486 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3487 // check if any other device (except speaker) is on
3488 if (type & deviceWithoutSpeaker) {
3489 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3490 }
3491
3492 if (params != 0) {
3493 addBatteryData(params);
3494 }
3495 }
3496#endif
3497
3498 for (size_t i = 0; i < mEffectChains.size(); i++) {
3499 mEffectChains[i]->setDevice_l(type);
3500 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003501
3502 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3503 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3504 bool configChanged = mPrevOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003505 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003506 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003507
3508 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003509 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3510 status = hwDevice->createAudioPatch(patch->num_sources,
3511 patch->sources,
3512 patch->num_sinks,
3513 patch->sinks,
3514 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003515 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003516 char *address;
3517 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3518 //FIXME: we only support address on first sink with HAL version < 3.0
3519 address = audio_device_address_to_parameter(
3520 patch->sinks[0].ext.device.type,
3521 patch->sinks[0].ext.device.address);
3522 } else {
3523 address = (char *)calloc(1, 1);
3524 }
3525 AudioParameter param = AudioParameter(String8(address));
3526 free(address);
3527 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), (int)type);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003528 status = mOutput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07003529 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003530 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003531 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003532 mPrevOutDevice = type;
Eric Laurente8726fe2015-06-26 09:39:24 -07003533 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3534 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003535 return status;
3536}
3537
Eric Laurent054d9d32015-04-24 08:48:48 -07003538status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3539{
Andy Hungf60abce2016-08-26 11:37:54 -07003540 status_t status;
3541 if (property_get_bool("af.patch_park", false /* default_value */)) {
3542 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3543 // or if HAL does not properly lock against access.
3544 AutoPark<FastMixer> park(mFastMixer);
3545 status = PlaybackThread::releaseAudioPatch_l(handle);
3546 } else {
3547 status = PlaybackThread::releaseAudioPatch_l(handle);
3548 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003549 return status;
3550}
3551
Eric Laurent1c333e22014-05-20 10:48:17 -07003552status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3553{
3554 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003555
3556 mOutDevice = AUDIO_DEVICE_NONE;
3557
Eric Laurent1c333e22014-05-20 10:48:17 -07003558 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003559 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3560 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003561 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003562 AudioParameter param;
3563 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003564 status = mOutput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07003565 }
3566 return status;
3567}
3568
Eric Laurent83b88082014-06-20 18:31:16 -07003569void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3570{
3571 Mutex::Autolock _l(mLock);
3572 mTracks.add(track);
3573}
3574
3575void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3576{
3577 Mutex::Autolock _l(mLock);
3578 destroyTrack_l(track);
3579}
3580
3581void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3582{
3583 ThreadBase::getAudioPortConfig(config);
3584 config->role = AUDIO_PORT_ROLE_SOURCE;
3585 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3586 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3587}
3588
Eric Laurent81784c32012-11-19 14:55:58 -08003589// ----------------------------------------------------------------------------
3590
3591AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003592 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3593 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003594 // mAudioMixer below
3595 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08003596 mFastMixerFutex(0),
3597 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08003598 // mOutputSink below
3599 // mPipeSink below
3600 // mNormalSink below
3601{
3602 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003603 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%zu, "
3604 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003605 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3606 mNormalFrameCount);
3607 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3608
Andy Hungfbfc3952015-01-15 13:33:51 -08003609 if (type == DUPLICATING) {
3610 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3611 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3612 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3613 return;
3614 }
Eric Laurent81784c32012-11-19 14:55:58 -08003615 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07003616 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08003617 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003618 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003619#if !LOG_NDEBUG
3620 ssize_t index =
3621#else
3622 (void)
3623#endif
3624 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003625 ALOG_ASSERT(index == 0);
3626
3627 // initialize fast mixer depending on configuration
3628 bool initFastMixer;
3629 switch (kUseFastMixer) {
3630 case FastMixer_Never:
3631 initFastMixer = false;
3632 break;
3633 case FastMixer_Always:
3634 initFastMixer = true;
3635 break;
3636 case FastMixer_Static:
3637 case FastMixer_Dynamic:
3638 initFastMixer = mFrameCount < mNormalFrameCount;
3639 break;
3640 }
3641 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003642 audio_format_t fastMixerFormat;
3643 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3644 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3645 } else {
3646 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3647 }
3648 if (mFormat != fastMixerFormat) {
3649 // change our Sink format to accept our intermediate precision
3650 mFormat = fastMixerFormat;
3651 free(mSinkBuffer);
3652 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3653 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3654 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3655 }
Eric Laurent81784c32012-11-19 14:55:58 -08003656
3657 // create a MonoPipe to connect our submix to FastMixer
3658 NBAIO_Format format = mOutputSink->format();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003659#ifdef TEE_SINK
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003660 NBAIO_Format origformat = format;
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003661#endif
Andy Hung1258c1a2014-05-23 21:22:17 -07003662 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07003663 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003664 format.mFormat = fastMixerFormat;
3665 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3666
Eric Laurent81784c32012-11-19 14:55:58 -08003667 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3668 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3669 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3670 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3671 const NBAIO_Format offers[1] = {format};
3672 size_t numCounterOffers = 0;
Glenn Kastenfc302fd2016-04-11 14:11:26 -07003673#if !LOG_NDEBUG || defined(TEE_SINK)
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003674 ssize_t index =
3675#else
3676 (void)
3677#endif
3678 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003679 ALOG_ASSERT(index == 0);
3680 monoPipe->setAvgFrames((mScreenState & 1) ?
3681 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3682 mPipeSink = monoPipe;
3683
Glenn Kasten46909e72013-02-26 09:20:22 -08003684#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003685 if (mTeeSinkOutputEnabled) {
3686 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003687 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3688 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003689 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003690 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003691 ALOG_ASSERT(index == 0);
3692 mTeeSink = teeSink;
3693 PipeReader *teeSource = new PipeReader(*teeSink);
3694 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003695 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003696 ALOG_ASSERT(index == 0);
3697 mTeeSource = teeSource;
3698 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003699#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003700
3701 // create fast mixer and configure it initially with just one fast track for our submix
3702 mFastMixer = new FastMixer();
3703 FastMixerStateQueue *sq = mFastMixer->sq();
3704#ifdef STATE_QUEUE_DUMP
3705 sq->setObserverDump(&mStateQueueObserverDump);
3706 sq->setMutatorDump(&mStateQueueMutatorDump);
3707#endif
3708 FastMixerState *state = sq->begin();
3709 FastTrack *fastTrack = &state->mFastTracks[0];
3710 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3711 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3712 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003713 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3714 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003715 fastTrack->mGeneration++;
3716 state->mFastTracksGen++;
3717 state->mTrackMask = 1;
3718 // fast mixer will use the HAL output sink
3719 state->mOutputSink = mOutputSink.get();
3720 state->mOutputSinkGen++;
3721 state->mFrameCount = mFrameCount;
3722 state->mCommand = FastMixerState::COLD_IDLE;
3723 // already done in constructor initialization list
3724 //mFastMixerFutex = 0;
3725 state->mColdFutexAddr = &mFastMixerFutex;
3726 state->mColdGen++;
3727 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003728#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003729 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003730#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003731 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3732 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003733 sq->end();
3734 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3735
3736 // start the fast mixer
3737 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3738 pid_t tid = mFastMixer->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003739 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003740
3741#ifdef AUDIO_WATCHDOG
3742 // create and start the watchdog
3743 mAudioWatchdog = new AudioWatchdog();
3744 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3745 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3746 tid = mAudioWatchdog->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003747 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003748#endif
3749
Eric Laurent81784c32012-11-19 14:55:58 -08003750 }
3751
3752 switch (kUseFastMixer) {
3753 case FastMixer_Never:
3754 case FastMixer_Dynamic:
3755 mNormalSink = mOutputSink;
3756 break;
3757 case FastMixer_Always:
3758 mNormalSink = mPipeSink;
3759 break;
3760 case FastMixer_Static:
3761 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3762 break;
3763 }
3764}
3765
3766AudioFlinger::MixerThread::~MixerThread()
3767{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003768 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003769 FastMixerStateQueue *sq = mFastMixer->sq();
3770 FastMixerState *state = sq->begin();
3771 if (state->mCommand == FastMixerState::COLD_IDLE) {
3772 int32_t old = android_atomic_inc(&mFastMixerFutex);
3773 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003774 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003775 }
3776 }
3777 state->mCommand = FastMixerState::EXIT;
3778 sq->end();
3779 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3780 mFastMixer->join();
3781 // Though the fast mixer thread has exited, it's state queue is still valid.
3782 // We'll use that extract the final state which contains one remaining fast track
3783 // corresponding to our sub-mix.
3784 state = sq->begin();
3785 ALOG_ASSERT(state->mTrackMask == 1);
3786 FastTrack *fastTrack = &state->mFastTracks[0];
3787 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3788 delete fastTrack->mBufferProvider;
3789 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003790 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003791#ifdef AUDIO_WATCHDOG
3792 if (mAudioWatchdog != 0) {
3793 mAudioWatchdog->requestExit();
3794 mAudioWatchdog->requestExitAndWait();
3795 mAudioWatchdog.clear();
3796 }
3797#endif
3798 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003799 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003800 delete mAudioMixer;
3801}
3802
3803
3804uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3805{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003806 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003807 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3808 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3809 }
3810 return latency;
3811}
3812
3813
3814void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3815{
3816 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3817}
3818
Eric Laurentbfb1b832013-01-07 09:53:42 -08003819ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003820{
3821 // FIXME we should only do one push per cycle; confirm this is true
3822 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003823 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003824 FastMixerStateQueue *sq = mFastMixer->sq();
3825 FastMixerState *state = sq->begin();
3826 if (state->mCommand != FastMixerState::MIX_WRITE &&
3827 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3828 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07003829
3830 // FIXME workaround for first HAL write being CPU bound on some devices
3831 ATRACE_BEGIN("write");
3832 mOutput->write((char *)mSinkBuffer, 0);
3833 ATRACE_END();
3834
Eric Laurent81784c32012-11-19 14:55:58 -08003835 int32_t old = android_atomic_inc(&mFastMixerFutex);
3836 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003837 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003838 }
3839#ifdef AUDIO_WATCHDOG
3840 if (mAudioWatchdog != 0) {
3841 mAudioWatchdog->resume();
3842 }
3843#endif
3844 }
3845 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003846#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003847 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003848 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003849#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003850 sq->end();
3851 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3852 if (kUseFastMixer == FastMixer_Dynamic) {
3853 mNormalSink = mPipeSink;
3854 }
3855 } else {
3856 sq->end(false /*didModify*/);
3857 }
3858 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003859 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003860}
3861
3862void AudioFlinger::MixerThread::threadLoop_standby()
3863{
3864 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003865 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003866 FastMixerStateQueue *sq = mFastMixer->sq();
3867 FastMixerState *state = sq->begin();
3868 if (!(state->mCommand & FastMixerState::IDLE)) {
3869 state->mCommand = FastMixerState::COLD_IDLE;
3870 state->mColdFutexAddr = &mFastMixerFutex;
3871 state->mColdGen++;
3872 mFastMixerFutex = 0;
3873 sq->end();
3874 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3875 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3876 if (kUseFastMixer == FastMixer_Dynamic) {
3877 mNormalSink = mOutputSink;
3878 }
3879#ifdef AUDIO_WATCHDOG
3880 if (mAudioWatchdog != 0) {
3881 mAudioWatchdog->pause();
3882 }
3883#endif
3884 } else {
3885 sq->end(false /*didModify*/);
3886 }
3887 }
3888 PlaybackThread::threadLoop_standby();
3889}
3890
Eric Laurentbfb1b832013-01-07 09:53:42 -08003891bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3892{
3893 return false;
3894}
3895
3896bool AudioFlinger::PlaybackThread::shouldStandby_l()
3897{
3898 return !mStandby;
3899}
3900
3901bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3902{
3903 Mutex::Autolock _l(mLock);
3904 return waitingAsyncCallback_l();
3905}
3906
Eric Laurent81784c32012-11-19 14:55:58 -08003907// shared by MIXER and DIRECT, overridden by DUPLICATING
3908void AudioFlinger::PlaybackThread::threadLoop_standby()
3909{
3910 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08003911 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003912 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003913 // discard any pending drain or write ack by incrementing sequence
3914 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3915 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003916 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003917 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3918 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003919 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003920 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003921}
3922
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003923void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3924{
3925 ALOGV("signal playback thread");
3926 broadcast_l();
3927}
3928
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003929void AudioFlinger::PlaybackThread::onAsyncError()
3930{
3931 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
3932 invalidateTracks((audio_stream_type_t)i);
3933 }
3934}
3935
Eric Laurent81784c32012-11-19 14:55:58 -08003936void AudioFlinger::MixerThread::threadLoop_mix()
3937{
Eric Laurent81784c32012-11-19 14:55:58 -08003938 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08003939 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08003940 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003941 // increase sleep time progressively when application underrun condition clears.
3942 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3943 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3944 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003945 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003946 sleepTimeShift--;
3947 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003948 mSleepTimeUs = 0;
3949 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08003950 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003951
Eric Laurent81784c32012-11-19 14:55:58 -08003952}
3953
3954void AudioFlinger::MixerThread::threadLoop_sleepTime()
3955{
3956 // If no tracks are ready, sleep once for the duration of an output
3957 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003958 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003959 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003960 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
3961 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
3962 mSleepTimeUs = kMinThreadSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003963 }
3964 // reduce sleep time in case of consecutive application underruns to avoid
3965 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3966 // duration we would end up writing less data than needed by the audio HAL if
3967 // the condition persists.
3968 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3969 sleepTimeShift++;
3970 }
3971 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003972 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003973 }
3974 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003975 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3976 // before effects processing or output.
3977 if (mMixerBufferValid) {
3978 memset(mMixerBuffer, 0, mMixerBufferSize);
3979 } else {
3980 memset(mSinkBuffer, 0, mSinkBufferSize);
3981 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003982 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003983 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3984 "anticipated start");
3985 }
3986 // TODO add standby time extension fct of effect tail
3987}
3988
3989// prepareTracks_l() must be called with ThreadBase::mLock held
3990AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3991 Vector< sp<Track> > *tracksToRemove)
3992{
3993
3994 mixer_state mixerStatus = MIXER_IDLE;
3995 // find out which tracks need to be processed
3996 size_t count = mActiveTracks.size();
3997 size_t mixedTracks = 0;
3998 size_t tracksWithEffect = 0;
3999 // counts only _active_ fast tracks
4000 size_t fastTracks = 0;
4001 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
4002
4003 float masterVolume = mMasterVolume;
4004 bool masterMute = mMasterMute;
4005
4006 if (masterMute) {
4007 masterVolume = 0;
4008 }
4009 // Delegate master volume control to effect in output mix effect chain if needed
4010 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4011 if (chain != 0) {
4012 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
4013 chain->setVolume_l(&v, &v);
4014 masterVolume = (float)((v + (1 << 23)) >> 24);
4015 chain.clear();
4016 }
4017
4018 // prepare a new state to push
4019 FastMixerStateQueue *sq = NULL;
4020 FastMixerState *state = NULL;
4021 bool didModify = false;
4022 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004023 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004024 sq = mFastMixer->sq();
4025 state = sq->begin();
4026 }
4027
Andy Hung69aed5f2014-02-25 17:24:40 -08004028 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08004029 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08004030
Eric Laurent81784c32012-11-19 14:55:58 -08004031 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07004032 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08004033 if (t == 0) {
4034 continue;
4035 }
4036
4037 // this const just means the local variable doesn't change
4038 Track* const track = t.get();
4039
4040 // process fast tracks
4041 if (track->isFastTrack()) {
4042
4043 // It's theoretically possible (though unlikely) for a fast track to be created
4044 // and then removed within the same normal mix cycle. This is not a problem, as
4045 // the track never becomes active so it's fast mixer slot is never touched.
4046 // The converse, of removing an (active) track and then creating a new track
4047 // at the identical fast mixer slot within the same normal mix cycle,
4048 // is impossible because the slot isn't marked available until the end of each cycle.
4049 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07004050 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08004051 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
4052 FastTrack *fastTrack = &state->mFastTracks[j];
4053
4054 // Determine whether the track is currently in underrun condition,
4055 // and whether it had a recent underrun.
4056 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
4057 FastTrackUnderruns underruns = ftDump->mUnderruns;
4058 uint32_t recentFull = (underruns.mBitFields.mFull -
4059 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
4060 uint32_t recentPartial = (underruns.mBitFields.mPartial -
4061 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
4062 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
4063 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
4064 uint32_t recentUnderruns = recentPartial + recentEmpty;
4065 track->mObservedUnderruns = underruns;
4066 // don't count underruns that occur while stopping or pausing
4067 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07004068 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
4069 recentUnderruns > 0) {
4070 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
4071 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Phil Burk2812d9e2016-01-04 10:34:30 -08004072 } else {
4073 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Eric Laurent81784c32012-11-19 14:55:58 -08004074 }
4075
4076 // This is similar to the state machine for normal tracks,
4077 // with a few modifications for fast tracks.
4078 bool isActive = true;
4079 switch (track->mState) {
4080 case TrackBase::STOPPING_1:
4081 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08004082 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004083 track->mState = TrackBase::STOPPING_2;
4084 }
4085 break;
4086 case TrackBase::PAUSING:
4087 // ramp down is not yet implemented
4088 track->setPaused();
4089 break;
4090 case TrackBase::RESUMING:
4091 // ramp up is not yet implemented
4092 track->mState = TrackBase::ACTIVE;
4093 break;
4094 case TrackBase::ACTIVE:
4095 if (recentFull > 0 || recentPartial > 0) {
4096 // track has provided at least some frames recently: reset retry count
4097 track->mRetryCount = kMaxTrackRetries;
4098 }
4099 if (recentUnderruns == 0) {
4100 // no recent underruns: stay active
4101 break;
4102 }
4103 // there has recently been an underrun of some kind
4104 if (track->sharedBuffer() == 0) {
4105 // were any of the recent underruns "empty" (no frames available)?
4106 if (recentEmpty == 0) {
4107 // no, then ignore the partial underruns as they are allowed indefinitely
4108 break;
4109 }
4110 // there has recently been an "empty" underrun: decrement the retry counter
4111 if (--(track->mRetryCount) > 0) {
4112 break;
4113 }
4114 // indicate to client process that the track was disabled because of underrun;
4115 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004116 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004117 // remove from active list, but state remains ACTIVE [confusing but true]
4118 isActive = false;
4119 break;
4120 }
4121 // fall through
4122 case TrackBase::STOPPING_2:
4123 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08004124 case TrackBase::STOPPED:
4125 case TrackBase::FLUSHED: // flush() while active
4126 // Check for presentation complete if track is inactive
4127 // We have consumed all the buffers of this track.
4128 // This would be incomplete if we auto-paused on underrun
4129 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004130 uint32_t latency = 0;
4131 status_t result = mOutput->stream->getLatency(&latency);
4132 ALOGE_IF(result != OK,
4133 "Error when retrieving output stream latency: %d", result);
4134 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004135 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004136 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
4137 // track stays in active list until presentation is complete
4138 break;
4139 }
4140 }
4141 if (track->isStopping_2()) {
4142 track->mState = TrackBase::STOPPED;
4143 }
4144 if (track->isStopped()) {
4145 // Can't reset directly, as fast mixer is still polling this track
4146 // track->reset();
4147 // So instead mark this track as needing to be reset after push with ack
4148 resetMask |= 1 << i;
4149 }
4150 isActive = false;
4151 break;
4152 case TrackBase::IDLE:
4153 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08004154 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08004155 }
4156
4157 if (isActive) {
4158 // was it previously inactive?
4159 if (!(state->mTrackMask & (1 << j))) {
4160 ExtendedAudioBufferProvider *eabp = track;
4161 VolumeProvider *vp = track;
4162 fastTrack->mBufferProvider = eabp;
4163 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08004164 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07004165 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08004166 fastTrack->mGeneration++;
4167 state->mTrackMask |= 1 << j;
4168 didModify = true;
4169 // no acknowledgement required for newly active tracks
4170 }
4171 // cache the combined master volume and stream type volume for fast mixer; this
4172 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08004173 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08004174 ++fastTracks;
4175 } else {
4176 // was it previously active?
4177 if (state->mTrackMask & (1 << j)) {
4178 fastTrack->mBufferProvider = NULL;
4179 fastTrack->mGeneration++;
4180 state->mTrackMask &= ~(1 << j);
4181 didModify = true;
4182 // If any fast tracks were removed, we must wait for acknowledgement
4183 // because we're about to decrement the last sp<> on those tracks.
4184 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4185 } else {
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08004186 LOG_ALWAYS_FATAL("fast track %d should have been active; "
4187 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
4188 j, track->mState, state->mTrackMask, recentUnderruns,
4189 track->sharedBuffer() != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004190 }
4191 tracksToRemove->add(track);
4192 // Avoids a misleading display in dumpsys
4193 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
4194 }
4195 continue;
4196 }
4197
4198 { // local variable scope to avoid goto warning
4199
4200 audio_track_cblk_t* cblk = track->cblk();
4201
4202 // The first time a track is added we wait
4203 // for all its buffers to be filled before processing it
4204 int name = track->name();
4205 // make sure that we have enough frames to mix one full buffer.
4206 // enforce this condition only once to enable draining the buffer in case the client
4207 // app does not call stop() and relies on underrun to stop:
4208 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
4209 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004210 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07004211 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004212 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004213
4214 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004215 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004216 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
4217 // add frames already consumed but not yet released by the resampler
4218 // because mAudioTrackServerProxy->framesReady() will include these frames
4219 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
4220
Eric Laurent81784c32012-11-19 14:55:58 -08004221 uint32_t minFrames = 1;
4222 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
4223 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004224 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08004225 }
Eric Laurent13e4c962013-12-20 17:36:01 -08004226
4227 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07004228 if (ATRACE_ENABLED()) {
4229 // I wish we had formatted trace names
4230 char traceName[16];
4231 strcpy(traceName, "nRdy");
4232 int name = track->name();
4233 if (AudioMixer::TRACK0 <= name &&
4234 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
4235 name -= AudioMixer::TRACK0;
4236 traceName[4] = (name / 10) + '0';
4237 traceName[5] = (name % 10) + '0';
4238 } else {
4239 traceName[4] = '?';
4240 traceName[5] = '?';
4241 }
4242 traceName[6] = '\0';
4243 ATRACE_INT(traceName, framesReady);
4244 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004245 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08004246 !track->isPaused() && !track->isTerminated())
4247 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004248 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004249
4250 mixedTracks++;
4251
Andy Hung69aed5f2014-02-25 17:24:40 -08004252 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
4253 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08004254 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08004255 if (track->mainBuffer() != mSinkBuffer &&
4256 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004257 if (mEffectBufferEnabled) {
4258 mEffectBufferValid = true; // Later can set directly.
4259 }
Eric Laurent81784c32012-11-19 14:55:58 -08004260 chain = getEffectChain_l(track->sessionId());
4261 // Delegate volume control to effect in track effect chain if needed
4262 if (chain != 0) {
4263 tracksWithEffect++;
4264 } else {
4265 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
4266 "session %d",
4267 name, track->sessionId());
4268 }
4269 }
4270
4271
4272 int param = AudioMixer::VOLUME;
4273 if (track->mFillingUpStatus == Track::FS_FILLED) {
4274 // no ramp for the first volume setting
4275 track->mFillingUpStatus = Track::FS_ACTIVE;
4276 if (track->mState == TrackBase::RESUMING) {
4277 track->mState = TrackBase::ACTIVE;
4278 param = AudioMixer::RAMP_VOLUME;
4279 }
4280 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004281 // FIXME should not make a decision based on mServer
4282 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004283 // If the track is stopped before the first frame was mixed,
4284 // do not apply ramp
4285 param = AudioMixer::RAMP_VOLUME;
4286 }
4287
4288 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07004289 uint32_t vl, vr; // in U8.24 integer format
4290 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08004291 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07004292 vl = vr = 0;
4293 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08004294 if (track->isPausing()) {
4295 track->setPaused();
4296 }
4297 } else {
4298
4299 // read original volumes with volume control
4300 float typeVolume = mStreamTypes[track->streamType()].volume;
4301 float v = masterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07004302 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004303 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07004304 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
4305 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08004306 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07004307 if (vlf > GAIN_FLOAT_UNITY) {
4308 ALOGV("Track left volume out of range: %.3g", vlf);
4309 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004310 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07004311 if (vrf > GAIN_FLOAT_UNITY) {
4312 ALOGV("Track right volume out of range: %.3g", vrf);
4313 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004314 }
4315 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07004316 vlf *= v;
4317 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08004318 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07004319 // then derive vl and vr as U8.24 versions for the effect chain
4320 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
4321 vl = (uint32_t) (scaleto8_24 * vlf);
4322 vr = (uint32_t) (scaleto8_24 * vrf);
4323 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08004324 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08004325 // send level comes from shared memory and so may be corrupt
4326 if (sendLevel > MAX_GAIN_INT) {
4327 ALOGV("Track send level out of range: %04X", sendLevel);
4328 sendLevel = MAX_GAIN_INT;
4329 }
Andy Hung6be49402014-05-30 10:42:03 -07004330 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4331 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08004332 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004333
Eric Laurent81784c32012-11-19 14:55:58 -08004334 // Delegate volume control to effect in track effect chain if needed
4335 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4336 // Do not ramp volume if volume is controlled by effect
4337 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08004338 // Update remaining floating point volume levels
4339 vlf = (float)vl / (1 << 24);
4340 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004341 track->mHasVolumeController = true;
4342 } else {
4343 // force no volume ramp when volume controller was just disabled or removed
4344 // from effect chain to avoid volume spike
4345 if (track->mHasVolumeController) {
4346 param = AudioMixer::VOLUME;
4347 }
4348 track->mHasVolumeController = false;
4349 }
4350
Eric Laurent81784c32012-11-19 14:55:58 -08004351 // XXX: these things DON'T need to be done each time
4352 mAudioMixer->setBufferProvider(name, track);
4353 mAudioMixer->enable(name);
4354
Andy Hung6be49402014-05-30 10:42:03 -07004355 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
4356 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
4357 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004358 mAudioMixer->setParameter(
4359 name,
4360 AudioMixer::TRACK,
4361 AudioMixer::FORMAT, (void *)track->format());
4362 mAudioMixer->setParameter(
4363 name,
4364 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004365 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004366 mAudioMixer->setParameter(
4367 name,
4368 AudioMixer::TRACK,
4369 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004370 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004371 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004372 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004373 if (reqSampleRate == 0) {
4374 reqSampleRate = mSampleRate;
4375 } else if (reqSampleRate > maxSampleRate) {
4376 reqSampleRate = maxSampleRate;
4377 }
Eric Laurent81784c32012-11-19 14:55:58 -08004378 mAudioMixer->setParameter(
4379 name,
4380 AudioMixer::RESAMPLE,
4381 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004382 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004383
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004384 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004385 mAudioMixer->setParameter(
4386 name,
4387 AudioMixer::TIMESTRETCH,
4388 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004389 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004390
Andy Hung69aed5f2014-02-25 17:24:40 -08004391 /*
4392 * Select the appropriate output buffer for the track.
4393 *
Andy Hung98ef9782014-03-04 14:46:50 -08004394 * Tracks with effects go into their own effects chain buffer
4395 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004396 *
4397 * Other tracks can use mMixerBuffer for higher precision
4398 * channel accumulation. If this buffer is enabled
4399 * (mMixerBufferEnabled true), then selected tracks will accumulate
4400 * into it.
4401 *
4402 */
4403 if (mMixerBufferEnabled
4404 && (track->mainBuffer() == mSinkBuffer
4405 || track->mainBuffer() == mMixerBuffer)) {
4406 mAudioMixer->setParameter(
4407 name,
4408 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004409 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004410 mAudioMixer->setParameter(
4411 name,
4412 AudioMixer::TRACK,
4413 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4414 // TODO: override track->mainBuffer()?
4415 mMixerBufferValid = true;
4416 } else {
4417 mAudioMixer->setParameter(
4418 name,
4419 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004420 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004421 mAudioMixer->setParameter(
4422 name,
4423 AudioMixer::TRACK,
4424 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4425 }
Eric Laurent81784c32012-11-19 14:55:58 -08004426 mAudioMixer->setParameter(
4427 name,
4428 AudioMixer::TRACK,
4429 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4430
4431 // reset retry count
4432 track->mRetryCount = kMaxTrackRetries;
4433
4434 // If one track is ready, set the mixer ready if:
4435 // - the mixer was not ready during previous round OR
4436 // - no other track is not ready
4437 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4438 mixerStatus != MIXER_TRACKS_ENABLED) {
4439 mixerStatus = MIXER_TRACKS_READY;
4440 }
4441 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004442 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hung08fb1742015-05-31 23:22:10 -07004443 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)",
4444 track, framesReady, desiredFrames);
Glenn Kasten82aaf942013-07-17 16:05:07 -07004445 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08004446 } else {
4447 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004448 }
Phil Burk2812d9e2016-01-04 10:34:30 -08004449
Eric Laurent81784c32012-11-19 14:55:58 -08004450 // clear effect chain input buffer if an active track underruns to avoid sending
4451 // previous audio buffer again to effects
4452 chain = getEffectChain_l(track->sessionId());
4453 if (chain != 0) {
4454 chain->clearInputBuffer();
4455 }
4456
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004457 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004458 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4459 track->isStopped() || track->isPaused()) {
4460 // We have consumed all the buffers of this track.
4461 // Remove it from the list of active tracks.
4462 // TODO: use actual buffer filling status instead of latency when available from
4463 // audio HAL
4464 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004465 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004466 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4467 if (track->isStopped()) {
4468 track->reset();
4469 }
4470 tracksToRemove->add(track);
4471 }
4472 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004473 // No buffers for this track. Give it a few chances to
4474 // fill a buffer, then remove it from active list.
4475 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004476 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004477 tracksToRemove->add(track);
4478 // indicate to client process that the track was disabled because of underrun;
4479 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004480 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004481 // If one track is not ready, mark the mixer also not ready if:
4482 // - the mixer was ready during previous round OR
4483 // - no other track is ready
4484 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4485 mixerStatus != MIXER_TRACKS_READY) {
4486 mixerStatus = MIXER_TRACKS_ENABLED;
4487 }
4488 }
4489 mAudioMixer->disable(name);
4490 }
4491
4492 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08004493
4494 }
4495
4496 // Push the new FastMixer state if necessary
4497 bool pauseAudioWatchdog = false;
4498 if (didModify) {
4499 state->mFastTracksGen++;
4500 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4501 if (kUseFastMixer == FastMixer_Dynamic &&
4502 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4503 state->mCommand = FastMixerState::COLD_IDLE;
4504 state->mColdFutexAddr = &mFastMixerFutex;
4505 state->mColdGen++;
4506 mFastMixerFutex = 0;
4507 if (kUseFastMixer == FastMixer_Dynamic) {
4508 mNormalSink = mOutputSink;
4509 }
4510 // If we go into cold idle, need to wait for acknowledgement
4511 // so that fast mixer stops doing I/O.
4512 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4513 pauseAudioWatchdog = true;
4514 }
Eric Laurent81784c32012-11-19 14:55:58 -08004515 }
4516 if (sq != NULL) {
4517 sq->end(didModify);
4518 sq->push(block);
4519 }
4520#ifdef AUDIO_WATCHDOG
4521 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4522 mAudioWatchdog->pause();
4523 }
4524#endif
4525
4526 // Now perform the deferred reset on fast tracks that have stopped
4527 while (resetMask != 0) {
4528 size_t i = __builtin_ctz(resetMask);
4529 ALOG_ASSERT(i < count);
4530 resetMask &= ~(1 << i);
4531 sp<Track> t = mActiveTracks[i].promote();
4532 if (t == 0) {
4533 continue;
4534 }
4535 Track* track = t.get();
4536 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4537 track->reset();
4538 }
4539
4540 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004541 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004542
Eric Laurent97d547d2014-09-02 14:45:53 -07004543 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4544 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004545 }
4546
4547 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004548 // as long as there are effects we should clear the effects buffer, to avoid
4549 // passing a non-clean buffer to the effect chain
4550 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004551 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004552 // sink or mix buffer must be cleared if all tracks are connected to an
4553 // effect chain as in this case the mixer will not write to the sink or mix buffer
4554 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004555 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4556 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004557 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004558 if (mMixerBufferValid) {
4559 memset(mMixerBuffer, 0, mMixerBufferSize);
4560 // TODO: In testing, mSinkBuffer below need not be cleared because
4561 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4562 // after mixing.
4563 //
4564 // To enforce this guarantee:
4565 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4566 // (mixedTracks == 0 && fastTracks > 0))
4567 // must imply MIXER_TRACKS_READY.
4568 // Later, we may clear buffers regardless, and skip much of this logic.
4569 }
Andy Hung98ef9782014-03-04 14:46:50 -08004570 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004571 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004572 }
4573
4574 // if any fast tracks, then status is ready
4575 mMixerStatusIgnoringFastTracks = mixerStatus;
4576 if (fastTracks > 0) {
4577 mixerStatus = MIXER_TRACKS_READY;
4578 }
4579 return mixerStatus;
4580}
4581
Eric Laurentad7dd962016-09-22 12:38:37 -07004582// trackCountForUid_l() must be called with ThreadBase::mLock held
4583uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid)
4584{
4585 uint32_t trackCount = 0;
4586 for (size_t i = 0; i < mTracks.size() ; i++) {
4587 if (mTracks[i]->uid() == (int)uid) {
4588 trackCount++;
4589 }
4590 }
4591 return trackCount;
4592}
4593
Eric Laurent81784c32012-11-19 14:55:58 -08004594// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07004595int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
Eric Laurentad7dd962016-09-22 12:38:37 -07004596 audio_format_t format, audio_session_t sessionId, uid_t uid)
Eric Laurent81784c32012-11-19 14:55:58 -08004597{
Eric Laurentad7dd962016-09-22 12:38:37 -07004598 if (trackCountForUid_l(uid) > (PlaybackThread::kMaxTracksPerUid - 1)) {
4599 return -1;
4600 }
Andy Hunge8a1ced2014-05-09 15:02:21 -07004601 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08004602}
4603
4604// deleteTrackName_l() must be called with ThreadBase::mLock held
4605void AudioFlinger::MixerThread::deleteTrackName_l(int name)
4606{
4607 ALOGV("remove track (%d) and delete from mixer", name);
4608 mAudioMixer->deleteTrackName(name);
4609}
4610
Eric Laurent10351942014-05-08 18:49:52 -07004611// checkForNewParameter_l() must be called with ThreadBase::mLock held
4612bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4613 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004614{
Eric Laurent81784c32012-11-19 14:55:58 -08004615 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08004616 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004617
Eric Laurent10351942014-05-08 18:49:52 -07004618 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004619
Glenn Kastenc05b8d72016-03-24 09:48:17 -07004620 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004621
Eric Laurent10351942014-05-08 18:49:52 -07004622 AudioParameter param = AudioParameter(keyValuePair);
4623 int value;
4624 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4625 reconfig = true;
4626 }
4627 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004628 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004629 status = BAD_VALUE;
4630 } else {
4631 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004632 reconfig = true;
4633 }
Eric Laurent10351942014-05-08 18:49:52 -07004634 }
4635 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004636 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004637 status = BAD_VALUE;
4638 } else {
4639 // no need to save value, since it's constant
4640 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004641 }
Eric Laurent10351942014-05-08 18:49:52 -07004642 }
4643 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4644 // do not accept frame count changes if tracks are open as the track buffer
4645 // size depends on frame count and correct behavior would not be guaranteed
4646 // if frame count is changed after track creation
4647 if (!mTracks.isEmpty()) {
4648 status = INVALID_OPERATION;
4649 } else {
4650 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004651 }
Eric Laurent10351942014-05-08 18:49:52 -07004652 }
4653 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004654#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004655 // when changing the audio output device, call addBatteryData to notify
4656 // the change
4657 if (mOutDevice != value) {
4658 uint32_t params = 0;
4659 // check whether speaker is on
4660 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4661 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004662 }
Eric Laurent10351942014-05-08 18:49:52 -07004663
4664 audio_devices_t deviceWithoutSpeaker
4665 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4666 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07004667 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07004668 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4669 }
4670
4671 if (params != 0) {
4672 addBatteryData(params);
4673 }
4674 }
Eric Laurent81784c32012-11-19 14:55:58 -08004675#endif
4676
Eric Laurent10351942014-05-08 18:49:52 -07004677 // forward device change to effects that have requested to be
4678 // aware of attached audio device.
4679 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08004680 a2dpDeviceChanged =
4681 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07004682 mOutDevice = value;
4683 for (size_t i = 0; i < mEffectChains.size(); i++) {
4684 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004685 }
4686 }
Eric Laurent10351942014-05-08 18:49:52 -07004687 }
Eric Laurent81784c32012-11-19 14:55:58 -08004688
Eric Laurent10351942014-05-08 18:49:52 -07004689 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004690 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07004691 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004692 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004693 mStandby = true;
4694 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004695 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08004696 }
Eric Laurent10351942014-05-08 18:49:52 -07004697 if (status == NO_ERROR && reconfig) {
4698 readOutputParameters_l();
4699 delete mAudioMixer;
4700 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4701 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004702 int name = getTrackName_l(mTracks[i]->mChannelMask,
Eric Laurentad7dd962016-09-22 12:38:37 -07004703 mTracks[i]->mFormat, mTracks[i]->mSessionId, mTracks[i]->uid());
Eric Laurent10351942014-05-08 18:49:52 -07004704 if (name < 0) {
4705 break;
4706 }
4707 mTracks[i]->mName = name;
4708 }
Eric Laurent73e26b62015-04-27 16:55:58 -07004709 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004710 }
Eric Laurent81784c32012-11-19 14:55:58 -08004711 }
4712
Eric Laurent42537be2016-01-08 17:16:42 -08004713 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08004714}
4715
4716
4717void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4718{
Eric Laurent81784c32012-11-19 14:55:58 -08004719 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07004720 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Elliott Hughes87cebad2014-05-22 10:14:43 -07004721 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Andy Hung2ddee192015-12-18 17:34:44 -08004722 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent81784c32012-11-19 14:55:58 -08004723
4724 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten2f90c512015-12-02 11:40:09 -08004725 // while we are dumping it. It may be inconsistent, but it won't mutate!
4726 // This is a large object so we place it on the heap.
4727 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
4728 const FastMixerDumpState *copy = new FastMixerDumpState(mFastMixerDumpState);
4729 copy->dump(fd);
4730 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08004731
4732#ifdef STATE_QUEUE_DUMP
4733 // Similar for state queue
4734 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4735 observerCopy.dump(fd);
4736 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4737 mutatorCopy.dump(fd);
4738#endif
4739
Glenn Kasten46909e72013-02-26 09:20:22 -08004740#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004741 // Write the tee output to a .wav file
4742 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08004743#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004744
4745#ifdef AUDIO_WATCHDOG
4746 if (mAudioWatchdog != 0) {
4747 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4748 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4749 wdCopy.dump(fd);
4750 }
4751#endif
4752}
4753
4754uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4755{
4756 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4757}
4758
4759uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4760{
4761 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4762}
4763
4764void AudioFlinger::MixerThread::cacheParameters_l()
4765{
4766 PlaybackThread::cacheParameters_l();
4767
4768 // FIXME: Relaxed timing because of a certain device that can't meet latency
4769 // Should be reduced to 2x after the vendor fixes the driver issue
4770 // increase threshold again due to low power audio mode. The way this warning
4771 // threshold is calculated and its usefulness should be reconsidered anyway.
4772 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4773}
4774
4775// ----------------------------------------------------------------------------
4776
4777AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07004778 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady)
4779 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08004780 // mLeftVolFloat, mRightVolFloat
4781{
4782}
4783
Eric Laurentbfb1b832013-01-07 09:53:42 -08004784AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4785 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurente93cc032016-05-05 10:15:10 -07004786 ThreadBase::type_t type, bool systemReady)
4787 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004788 // mLeftVolFloat, mRightVolFloat
4789{
4790}
4791
Eric Laurent81784c32012-11-19 14:55:58 -08004792AudioFlinger::DirectOutputThread::~DirectOutputThread()
4793{
4794}
4795
Eric Laurentbfb1b832013-01-07 09:53:42 -08004796void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
4797{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004798 float left, right;
4799
4800 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4801 left = right = 0;
4802 } else {
4803 float typeVolume = mStreamTypes[track->streamType()].volume;
4804 float v = mMasterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07004805 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004806 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4807 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4808 if (left > GAIN_FLOAT_UNITY) {
4809 left = GAIN_FLOAT_UNITY;
4810 }
4811 left *= v;
4812 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4813 if (right > GAIN_FLOAT_UNITY) {
4814 right = GAIN_FLOAT_UNITY;
4815 }
4816 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004817 }
4818
4819 if (lastTrack) {
4820 if (left != mLeftVolFloat || right != mRightVolFloat) {
4821 mLeftVolFloat = left;
4822 mRightVolFloat = right;
4823
4824 // Convert volumes from float to 8.24
4825 uint32_t vl = (uint32_t)(left * (1 << 24));
4826 uint32_t vr = (uint32_t)(right * (1 << 24));
4827
4828 // Delegate volume control to effect in track effect chain if needed
4829 // only one effect chain can be present on DirectOutputThread, so if
4830 // there is one, the track is connected to it
4831 if (!mEffectChains.isEmpty()) {
4832 mEffectChains[0]->setVolume_l(&vl, &vr);
4833 left = (float)vl / (1 << 24);
4834 right = (float)vr / (1 << 24);
4835 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004836 status_t result = mOutput->stream->setVolume(left, right);
4837 ALOGE_IF(result != OK, "Error when setting output stream volume: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004838 }
4839 }
4840}
4841
Phil Burk43b4dcc2015-06-09 16:53:44 -07004842void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
4843{
4844 sp<Track> previousTrack = mPreviousTrack.promote();
4845 sp<Track> latestTrack = mLatestActiveTrack.promote();
4846
Eric Laurent0f0631e2015-07-06 18:01:25 -07004847 if (previousTrack != 0 && latestTrack != 0) {
4848 if (mType == DIRECT) {
4849 if (previousTrack.get() != latestTrack.get()) {
4850 mFlushPending = true;
4851 }
4852 } else /* mType == OFFLOAD */ {
4853 if (previousTrack->sessionId() != latestTrack->sessionId()) {
4854 mFlushPending = true;
4855 }
4856 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004857 }
4858 PlaybackThread::onAddNewTrack_l();
4859}
Eric Laurentbfb1b832013-01-07 09:53:42 -08004860
Eric Laurent81784c32012-11-19 14:55:58 -08004861AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4862 Vector< sp<Track> > *tracksToRemove
4863)
4864{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004865 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004866 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004867 bool doHwPause = false;
4868 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004869
4870 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07004871 for (size_t i = 0; i < count; i++) {
4872 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08004873 // The track died recently
4874 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004875 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08004876 }
4877
Phil Burk43b4dcc2015-06-09 16:53:44 -07004878 if (t->isInvalid()) {
4879 ALOGW("An invalidated track shouldn't be in active list");
4880 tracksToRemove->add(t);
4881 continue;
4882 }
4883
Eric Laurent81784c32012-11-19 14:55:58 -08004884 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004885#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08004886 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004887#endif
Eric Laurentfd477972013-10-25 18:10:40 -07004888 // Only consider last track started for volume and mixer state control.
4889 // In theory an older track could underrun and restart after the new one starts
4890 // but as we only care about the transition phase between two tracks on a
4891 // direct output, it is not a problem to ignore the underrun case.
4892 sp<Track> l = mLatestActiveTrack.promote();
4893 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004894
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004895 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004896 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004897 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004898 doHwPause = true;
4899 mHwPaused = true;
4900 }
4901 tracksToRemove->add(track);
4902 } else if (track->isFlushPending()) {
4903 track->flushAck();
4904 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004905 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004906 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004907 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004908 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07004909 if (last) {
4910 mLeftVolFloat = mRightVolFloat = -1.0;
4911 if (mHwPaused) {
4912 doHwResume = true;
4913 mHwPaused = false;
4914 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004915 }
4916 }
4917
Eric Laurent81784c32012-11-19 14:55:58 -08004918 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004919 // for all its buffers to be filled before processing it.
4920 // Allow draining the buffer in case the client
4921 // app does not call stop() and relies on underrun to stop:
4922 // hence the test on (track->mRetryCount > 1).
4923 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07004924 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08004925 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004926 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08004927 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004928 minFrames = mNormalFrameCount;
4929 } else {
4930 minFrames = 1;
4931 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004932
Eric Laurentab5cdba2014-06-09 17:22:27 -07004933 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4934 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004935 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004936 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004937
4938 if (track->mFillingUpStatus == Track::FS_FILLED) {
4939 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07004940 if (last) {
4941 // make sure processVolume_l() will apply new volume even if 0
4942 mLeftVolFloat = mRightVolFloat = -1.0;
4943 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004944 if (!mHwSupportsPause) {
4945 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004946 }
4947 }
4948
4949 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004950 processVolume_l(track, last);
4951 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004952 sp<Track> previousTrack = mPreviousTrack.promote();
4953 if (previousTrack != 0) {
4954 if (track != previousTrack.get()) {
4955 // Flush any data still being written from last track
4956 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07004957 // Invalidate previous track to force a seek when resuming.
4958 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004959 }
4960 }
4961 mPreviousTrack = track;
4962
Eric Laurentd595b7c2013-04-03 17:27:56 -07004963 // reset retry count
4964 track->mRetryCount = kMaxTrackRetriesDirect;
4965 mActiveTrack = t;
4966 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07004967 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004968 doHwResume = true;
4969 mHwPaused = false;
4970 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004971 }
Eric Laurent81784c32012-11-19 14:55:58 -08004972 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004973 // clear effect chain input buffer if the last active track started underruns
4974 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004975 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004976 mEffectChains[0]->clearInputBuffer();
4977 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004978 if (track->isStopping_1()) {
4979 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07004980 if (last && mHwPaused) {
4981 doHwResume = true;
4982 mHwPaused = false;
4983 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004984 }
4985 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4986 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004987 // We have consumed all the buffers of this track.
4988 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004989 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08004990 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004991 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4992 } else {
4993 audioHALFrames = 0;
4994 }
4995
Andy Hung818e7a32016-02-16 18:08:07 -08004996 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004997 if (mStandby || !last ||
4998 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004999 if (track->isStopping_2()) {
5000 track->mState = TrackBase::STOPPED;
5001 }
Eric Laurent81784c32012-11-19 14:55:58 -08005002 if (track->isStopped()) {
5003 track->reset();
5004 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005005 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08005006 }
5007 } else {
5008 // No buffers for this track. Give it a few chances to
5009 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07005010 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08005011 if (--(track->mRetryCount) <= 0) {
5012 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07005013 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005014 // indicate to client process that the track was disabled because of underrun;
5015 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005016 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005017 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07005018 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
5019 "minFrames = %u, mFormat = %#x",
5020 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08005021 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07005022 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005023 doHwPause = true;
5024 mHwPaused = true;
5025 }
Eric Laurent81784c32012-11-19 14:55:58 -08005026 }
5027 }
5028 }
5029 }
5030
Eric Laurentd1f69b02014-12-15 14:33:13 -08005031 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07005032 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005033 for (size_t i = 0; i < mTracks.size(); i++) {
5034 if (mTracks[i]->isFlushPending()) {
5035 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005036 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005037 }
5038 }
5039 }
5040
5041 // make sure the pause/flush/resume sequence is executed in the right order.
5042 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5043 // before flush and then resume HW. This can happen in case of pause/flush/resume
5044 // if resume is received before pause is executed.
5045 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07005046 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005047 status_t result = mOutput->stream->pause();
5048 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005049 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005050 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005051 flushHw_l();
5052 }
5053 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005054 status_t result = mOutput->stream->resume();
5055 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005056 }
Eric Laurent81784c32012-11-19 14:55:58 -08005057 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005058 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005059
5060 return mixerStatus;
5061}
5062
5063void AudioFlinger::DirectOutputThread::threadLoop_mix()
5064{
Eric Laurent81784c32012-11-19 14:55:58 -08005065 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08005066 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005067 // output audio to hardware
5068 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07005069 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005070 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08005071 status_t status = mActiveTrack->getNextBuffer(&buffer);
5072 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08005073 // no need to pad with 0 for compressed audio
5074 if (audio_has_proportional_frames(mFormat)) {
5075 memset(curBuf, 0, frameCount * mFrameSize);
5076 }
Eric Laurent81784c32012-11-19 14:55:58 -08005077 break;
5078 }
5079 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
5080 frameCount -= buffer.frameCount;
5081 curBuf += buffer.frameCount * mFrameSize;
5082 mActiveTrack->releaseBuffer(&buffer);
5083 }
Andy Hung2098f272014-02-27 14:00:06 -08005084 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005085 mSleepTimeUs = 0;
5086 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005087 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005088}
5089
5090void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
5091{
Eric Laurentd1f69b02014-12-15 14:33:13 -08005092 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005093 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005094 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005095 return;
5096 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005097 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005098 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurente93cc032016-05-05 10:15:10 -07005099 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005100 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005101 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005102 }
Phil Burkfdb3c072016-02-09 10:47:02 -08005103 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08005104 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005105 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005106 }
5107}
5108
Eric Laurentd1f69b02014-12-15 14:33:13 -08005109void AudioFlinger::DirectOutputThread::threadLoop_exit()
5110{
5111 {
5112 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005113 for (size_t i = 0; i < mTracks.size(); i++) {
5114 if (mTracks[i]->isFlushPending()) {
5115 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005116 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005117 }
5118 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005119 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005120 flushHw_l();
5121 }
5122 }
5123 PlaybackThread::threadLoop_exit();
5124}
5125
5126// must be called with thread mutex locked
5127bool AudioFlinger::DirectOutputThread::shouldStandby_l()
5128{
5129 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07005130 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005131
vivek mehta9cd7ad12016-03-17 00:18:29 -07005132 if ((mType == DIRECT) && audio_is_linear_pcm(mFormat) && !usesHwAvSync()) {
5133 return !mStandby;
5134 }
5135
Eric Laurentd1f69b02014-12-15 14:33:13 -08005136 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
5137 // after a timeout and we will enter standby then.
5138 if (mTracks.size() > 0) {
5139 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07005140 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
5141 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005142 }
5143
Eric Laurent5cff4032015-05-26 13:49:58 -07005144 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08005145}
5146
Eric Laurent81784c32012-11-19 14:55:58 -08005147// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005148int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Eric Laurentad7dd962016-09-22 12:38:37 -07005149 audio_format_t format __unused, audio_session_t sessionId __unused, uid_t uid)
Eric Laurent81784c32012-11-19 14:55:58 -08005150{
Eric Laurentad7dd962016-09-22 12:38:37 -07005151 if (trackCountForUid_l(uid) > (PlaybackThread::kMaxTracksPerUid - 1)) {
5152 return -1;
5153 }
Eric Laurent81784c32012-11-19 14:55:58 -08005154 return 0;
5155}
5156
5157// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005158void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005159{
5160}
5161
Eric Laurent10351942014-05-08 18:49:52 -07005162// checkForNewParameter_l() must be called with ThreadBase::mLock held
5163bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
5164 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005165{
5166 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005167 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005168
Eric Laurent10351942014-05-08 18:49:52 -07005169 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005170
Eric Laurent10351942014-05-08 18:49:52 -07005171 AudioParameter param = AudioParameter(keyValuePair);
5172 int value;
5173 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5174 // forward device change to effects that have requested to be
5175 // aware of attached audio device.
5176 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005177 a2dpDeviceChanged =
5178 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005179 mOutDevice = value;
5180 for (size_t i = 0; i < mEffectChains.size(); i++) {
5181 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07005182 }
5183 }
Eric Laurent81784c32012-11-19 14:55:58 -08005184 }
Eric Laurent10351942014-05-08 18:49:52 -07005185 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5186 // do not accept frame count changes if tracks are open as the track buffer
5187 // size depends on frame count and correct behavior would not be garantied
5188 // if frame count is changed after track creation
5189 if (!mTracks.isEmpty()) {
5190 status = INVALID_OPERATION;
5191 } else {
5192 reconfig = true;
5193 }
5194 }
5195 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005196 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005197 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005198 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005199 mStandby = true;
5200 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005201 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005202 }
5203 if (status == NO_ERROR && reconfig) {
5204 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07005205 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005206 }
5207 }
5208
Eric Laurent42537be2016-01-08 17:16:42 -08005209 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005210}
5211
5212uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
5213{
5214 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005215 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005216 time = PlaybackThread::activeSleepTimeUs();
5217 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005218 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005219 }
5220 return time;
5221}
5222
5223uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
5224{
5225 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005226 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005227 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
5228 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005229 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005230 }
5231 return time;
5232}
5233
5234uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
5235{
5236 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005237 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005238 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
5239 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005240 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005241 }
5242 return time;
5243}
5244
5245void AudioFlinger::DirectOutputThread::cacheParameters_l()
5246{
5247 PlaybackThread::cacheParameters_l();
5248
5249 // use shorter standby delay as on normal output to release
5250 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07005251 // no delay on outputs with HW A/V sync
5252 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005253 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08005254 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005255 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07005256 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005257 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07005258 }
Eric Laurent81784c32012-11-19 14:55:58 -08005259}
5260
Eric Laurente659ef42014-09-29 13:06:46 -07005261void AudioFlinger::DirectOutputThread::flushHw_l()
5262{
Phil Burk062e67a2015-02-11 13:40:50 -08005263 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08005264 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005265 mFlushPending = false;
Eric Laurente659ef42014-09-29 13:06:46 -07005266}
5267
Eric Laurent81784c32012-11-19 14:55:58 -08005268// ----------------------------------------------------------------------------
5269
Eric Laurentbfb1b832013-01-07 09:53:42 -08005270AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07005271 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005272 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07005273 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07005274 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005275 mDrainSequence(0),
5276 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005277{
5278}
5279
5280AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
5281{
5282}
5283
5284void AudioFlinger::AsyncCallbackThread::onFirstRef()
5285{
5286 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
5287}
5288
5289bool AudioFlinger::AsyncCallbackThread::threadLoop()
5290{
5291 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005292 uint32_t writeAckSequence;
5293 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005294 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005295
5296 {
5297 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005298 while (!((mWriteAckSequence & 1) ||
5299 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005300 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005301 exitPending())) {
5302 mWaitWorkCV.wait(mLock);
5303 }
5304
Eric Laurentbfb1b832013-01-07 09:53:42 -08005305 if (exitPending()) {
5306 break;
5307 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005308 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
5309 mWriteAckSequence, mDrainSequence);
5310 writeAckSequence = mWriteAckSequence;
5311 mWriteAckSequence &= ~1;
5312 drainSequence = mDrainSequence;
5313 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005314 asyncError = mAsyncError;
5315 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005316 }
5317 {
Eric Laurent4de95592013-09-26 15:28:21 -07005318 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
5319 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005320 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005321 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005322 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005323 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005324 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005325 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005326 if (asyncError) {
5327 playbackThread->onAsyncError();
5328 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005329 }
5330 }
5331 }
5332 return false;
5333}
5334
5335void AudioFlinger::AsyncCallbackThread::exit()
5336{
5337 ALOGV("AsyncCallbackThread::exit");
5338 Mutex::Autolock _l(mLock);
5339 requestExit();
5340 mWaitWorkCV.broadcast();
5341}
5342
Eric Laurent3b4529e2013-09-05 18:09:19 -07005343void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005344{
5345 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005346 // bit 0 is cleared
5347 mWriteAckSequence = sequence << 1;
5348}
5349
5350void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5351{
5352 Mutex::Autolock _l(mLock);
5353 // ignore unexpected callbacks
5354 if (mWriteAckSequence & 2) {
5355 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005356 mWaitWorkCV.signal();
5357 }
5358}
5359
Eric Laurent3b4529e2013-09-05 18:09:19 -07005360void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005361{
5362 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005363 // bit 0 is cleared
5364 mDrainSequence = sequence << 1;
5365}
5366
5367void AudioFlinger::AsyncCallbackThread::resetDraining()
5368{
5369 Mutex::Autolock _l(mLock);
5370 // ignore unexpected callbacks
5371 if (mDrainSequence & 2) {
5372 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005373 mWaitWorkCV.signal();
5374 }
5375}
5376
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005377void AudioFlinger::AsyncCallbackThread::setAsyncError()
5378{
5379 Mutex::Autolock _l(mLock);
5380 mAsyncError = true;
5381 mWaitWorkCV.signal();
5382}
5383
Eric Laurentbfb1b832013-01-07 09:53:42 -08005384
5385// ----------------------------------------------------------------------------
5386AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07005387 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
5388 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07005389 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
5390 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005391{
Eric Laurentfd477972013-10-25 18:10:40 -07005392 //FIXME: mStandby should be set to true by ThreadBase constructor
5393 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07005394 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005395}
5396
Eric Laurentbfb1b832013-01-07 09:53:42 -08005397void AudioFlinger::OffloadThread::threadLoop_exit()
5398{
5399 if (mFlushPending || mHwPaused) {
5400 // If a flush is pending or track was paused, just discard buffered data
5401 flushHw_l();
5402 } else {
5403 mMixerStatus = MIXER_DRAIN_ALL;
5404 threadLoop_drain();
5405 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005406 if (mUseAsyncWrite) {
5407 ALOG_ASSERT(mCallbackThread != 0);
5408 mCallbackThread->exit();
5409 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005410 PlaybackThread::threadLoop_exit();
5411}
5412
5413AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5414 Vector< sp<Track> > *tracksToRemove
5415)
5416{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005417 size_t count = mActiveTracks.size();
5418
5419 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005420 bool doHwPause = false;
5421 bool doHwResume = false;
5422
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005423 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07005424
Eric Laurentbfb1b832013-01-07 09:53:42 -08005425 // find out which tracks need to be processed
5426 for (size_t i = 0; i < count; i++) {
5427 sp<Track> t = mActiveTracks[i].promote();
5428 // The track died recently
5429 if (t == 0) {
5430 continue;
5431 }
5432 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005433#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08005434 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005435#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005436 // Only consider last track started for volume and mixer state control.
5437 // In theory an older track could underrun and restart after the new one starts
5438 // but as we only care about the transition phase between two tracks on a
5439 // direct output, it is not a problem to ignore the underrun case.
5440 sp<Track> l = mLatestActiveTrack.promote();
5441 bool last = l.get() == track;
5442
Haynes Mathew George7844f672014-01-15 12:32:55 -08005443 if (track->isInvalid()) {
5444 ALOGW("An invalidated track shouldn't be in active list");
5445 tracksToRemove->add(track);
5446 continue;
5447 }
5448
5449 if (track->mState == TrackBase::IDLE) {
5450 ALOGW("An idle track shouldn't be in active list");
5451 continue;
5452 }
5453
Eric Laurentbfb1b832013-01-07 09:53:42 -08005454 if (track->isPausing()) {
5455 track->setPaused();
5456 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005457 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005458 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005459 mHwPaused = true;
5460 }
5461 // If we were part way through writing the mixbuffer to
5462 // the HAL we must save this until we resume
5463 // BUG - this will be wrong if a different track is made active,
5464 // in that case we want to discard the pending data in the
5465 // mixbuffer and tell the client to present it again when the
5466 // track is resumed
5467 mPausedWriteLength = mCurrentWriteLength;
5468 mPausedBytesRemaining = mBytesRemaining;
5469 mBytesRemaining = 0; // stop writing
5470 }
5471 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005472 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005473 if (track->isStopping_1()) {
5474 track->mRetryCount = kMaxTrackStopRetriesOffload;
5475 } else {
5476 track->mRetryCount = kMaxTrackRetriesOffload;
5477 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08005478 track->flushAck();
5479 if (last) {
5480 mFlushPending = true;
5481 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005482 } else if (track->isResumePending()){
5483 track->resumeAck();
5484 if (last) {
5485 if (mPausedBytesRemaining) {
5486 // Need to continue write that was interrupted
5487 mCurrentWriteLength = mPausedWriteLength;
5488 mBytesRemaining = mPausedBytesRemaining;
5489 mPausedBytesRemaining = 0;
5490 }
5491 if (mHwPaused) {
5492 doHwResume = true;
5493 mHwPaused = false;
5494 // threadLoop_mix() will handle the case that we need to
5495 // resume an interrupted write
5496 }
5497 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005498 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005499
Eric Laurent3df841a2016-07-15 15:15:40 -07005500 mLeftVolFloat = mRightVolFloat = -1.0;
5501
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005502 // Do not handle new data in this iteration even if track->framesReady()
5503 mixerStatus = MIXER_TRACKS_ENABLED;
5504 }
5505 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005506 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005507 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005508 if (track->mFillingUpStatus == Track::FS_FILLED) {
5509 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005510 if (last) {
5511 // make sure processVolume_l() will apply new volume even if 0
5512 mLeftVolFloat = mRightVolFloat = -1.0;
5513 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005514 }
5515
5516 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005517 sp<Track> previousTrack = mPreviousTrack.promote();
5518 if (previousTrack != 0) {
5519 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005520 // Flush any data still being written from last track
5521 mBytesRemaining = 0;
5522 if (mPausedBytesRemaining) {
5523 // Last track was paused so we also need to flush saved
5524 // mixbuffer state and invalidate track so that it will
5525 // re-submit that unwritten data when it is next resumed
5526 mPausedBytesRemaining = 0;
5527 // Invalidate is a bit drastic - would be more efficient
5528 // to have a flag to tell client that some of the
5529 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005530 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005531 }
5532 // flush data already sent to the DSP if changing audio session as audio
5533 // comes from a different source. Also invalidate previous track to force a
5534 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005535 if (previousTrack->sessionId() != track->sessionId()) {
5536 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005537 }
5538 }
5539 }
5540 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005541 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07005542 if (track->isStopping_1()) {
5543 track->mRetryCount = kMaxTrackStopRetriesOffload;
5544 } else {
5545 track->mRetryCount = kMaxTrackRetriesOffload;
5546 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005547 mActiveTrack = t;
5548 mixerStatus = MIXER_TRACKS_READY;
5549 }
5550 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005551 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005552 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005553 if (--(track->mRetryCount) <= 0) {
5554 // Hardware buffer can hold a large amount of audio so we must
5555 // wait for all current track's data to drain before we say
5556 // that the track is stopped.
5557 if (mBytesRemaining == 0) {
5558 // Only start draining when all data in mixbuffer
5559 // has been written
5560 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5561 track->mState = TrackBase::STOPPING_2; // so presentation completes after
5562 // drain do not drain if no data was ever sent to HAL (mStandby == true)
5563 if (last && !mStandby) {
5564 // do not modify drain sequence if we are already draining. This happens
5565 // when resuming from pause after drain.
5566 if ((mDrainSequence & 1) == 0) {
5567 mSleepTimeUs = 0;
5568 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
5569 mixerStatus = MIXER_DRAIN_TRACK;
5570 mDrainSequence += 2;
5571 }
5572 if (mHwPaused) {
5573 // It is possible to move from PAUSED to STOPPING_1 without
5574 // a resume so we must ensure hardware is running
5575 doHwResume = true;
5576 mHwPaused = false;
5577 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005578 }
5579 }
Eric Laurente93cc032016-05-05 10:15:10 -07005580 } else if (last) {
5581 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
5582 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005583 }
5584 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005585 // Drain has completed or we are in standby, signal presentation complete
5586 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005587 track->mState = TrackBase::STOPPED;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005588 uint32_t latency = 0;
5589 status_t result = mOutput->stream->getLatency(&latency);
5590 ALOGE_IF(result != OK,
5591 "Error when retrieving output stream latency: %d", result);
5592 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005593 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005594 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005595 track->presentationComplete(framesWritten, audioHALFrames);
5596 track->reset();
5597 tracksToRemove->add(track);
5598 }
5599 } else {
5600 // No buffers for this track. Give it a few chances to
5601 // fill a buffer, then remove it from active list.
5602 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07005603 bool running = false;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005604 uint64_t position = 0;
5605 struct timespec unused;
5606 // The running check restarts the retry counter at least once.
5607 status_t ret = mOutput->stream->getPresentationPosition(&position, &unused);
5608 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
5609 running = true;
5610 mOffloadUnderrunPosition = position;
5611 }
5612 if (ret == NO_ERROR) {
Andy Hungf8044752016-07-27 14:58:11 -07005613 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
5614 (long long)position, (long long)mOffloadUnderrunPosition);
5615 }
5616 if (running) { // still running, give us more time.
5617 track->mRetryCount = kMaxTrackRetriesOffload;
5618 } else {
5619 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5620 track->name());
5621 tracksToRemove->add(track);
5622 // indicate to client process that the track was disabled because of underrun;
5623 // it will then automatically call start() when data is available
5624 track->disable();
5625 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005626 } else if (last){
5627 mixerStatus = MIXER_TRACKS_ENABLED;
5628 }
5629 }
5630 }
5631 // compute volume for this track
5632 processVolume_l(track, last);
5633 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005634
Eric Laurentea0fade2013-10-04 16:23:48 -07005635 // make sure the pause/flush/resume sequence is executed in the right order.
5636 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5637 // before flush and then resume HW. This can happen in case of pause/flush/resume
5638 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07005639 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005640 status_t result = mOutput->stream->pause();
5641 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07005642 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005643 if (mFlushPending) {
5644 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005645 }
Eric Laurentfd477972013-10-25 18:10:40 -07005646 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005647 status_t result = mOutput->stream->resume();
5648 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07005649 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005650
Eric Laurentbfb1b832013-01-07 09:53:42 -08005651 // remove all the tracks that need to be...
5652 removeTracks_l(*tracksToRemove);
5653
5654 return mixerStatus;
5655}
5656
Eric Laurentbfb1b832013-01-07 09:53:42 -08005657// must be called with thread mutex locked
5658bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5659{
Eric Laurent3b4529e2013-09-05 18:09:19 -07005660 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5661 mWriteAckSequence, mDrainSequence);
5662 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005663 return true;
5664 }
5665 return false;
5666}
5667
Eric Laurentbfb1b832013-01-07 09:53:42 -08005668bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5669{
5670 Mutex::Autolock _l(mLock);
5671 return waitingAsyncCallback_l();
5672}
5673
5674void AudioFlinger::OffloadThread::flushHw_l()
5675{
Eric Laurente659ef42014-09-29 13:06:46 -07005676 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005677 // Flush anything still waiting in the mixbuffer
5678 mCurrentWriteLength = 0;
5679 mBytesRemaining = 0;
5680 mPausedWriteLength = 0;
5681 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07005682 // reset bytes written count to reflect that DSP buffers are empty after flush.
5683 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07005684 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08005685
Eric Laurentbfb1b832013-01-07 09:53:42 -08005686 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005687 // discard any pending drain or write ack by incrementing sequence
5688 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5689 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005690 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005691 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5692 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005693 }
5694}
5695
Haynes Mathew George05317d22016-05-03 16:34:26 -07005696void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
5697{
5698 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07005699 if (PlaybackThread::invalidateTracks_l(streamType)) {
5700 mFlushPending = true;
5701 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07005702}
5703
Eric Laurentbfb1b832013-01-07 09:53:42 -08005704// ----------------------------------------------------------------------------
5705
Eric Laurent81784c32012-11-19 14:55:58 -08005706AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005707 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005708 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07005709 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08005710 mWaitTimeMs(UINT_MAX)
5711{
5712 addOutputTrack(mainThread);
5713}
5714
5715AudioFlinger::DuplicatingThread::~DuplicatingThread()
5716{
5717 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5718 mOutputTracks[i]->destroy();
5719 }
5720}
5721
5722void AudioFlinger::DuplicatingThread::threadLoop_mix()
5723{
5724 // mix buffers...
5725 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08005726 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08005727 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005728 if (mMixerBufferValid) {
5729 memset(mMixerBuffer, 0, mMixerBufferSize);
5730 } else {
5731 memset(mSinkBuffer, 0, mSinkBufferSize);
5732 }
Eric Laurent81784c32012-11-19 14:55:58 -08005733 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005734 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005735 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005736 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005737 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005738}
5739
5740void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5741{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005742 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005743 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005744 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005745 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005746 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005747 }
5748 } else if (mBytesWritten != 0) {
5749 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5750 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005751 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005752 } else {
5753 // flush remaining overflow buffers in output tracks
5754 writeFrames = 0;
5755 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005756 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005757 }
5758}
5759
Eric Laurentbfb1b832013-01-07 09:53:42 -08005760ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005761{
5762 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005763 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005764 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005765 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005766 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005767}
5768
5769void AudioFlinger::DuplicatingThread::threadLoop_standby()
5770{
5771 // DuplicatingThread implements standby by stopping all tracks
5772 for (size_t i = 0; i < outputTracks.size(); i++) {
5773 outputTracks[i]->stop();
5774 }
5775}
5776
5777void AudioFlinger::DuplicatingThread::saveOutputTracks()
5778{
5779 outputTracks = mOutputTracks;
5780}
5781
5782void AudioFlinger::DuplicatingThread::clearOutputTracks()
5783{
5784 outputTracks.clear();
5785}
5786
5787void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5788{
5789 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005790 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5791 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5792 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5793 const size_t frameCount =
5794 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5795 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5796 // from different OutputTracks and their associated MixerThreads (e.g. one may
5797 // nearly empty and the other may be dropping data).
5798
5799 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005800 this,
5801 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005802 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005803 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005804 frameCount,
5805 IPCThreadState::self()->getCallingUid());
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07005806 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
5807 if (status != NO_ERROR) {
5808 ALOGE("addOutputTrack() initCheck failed %d", status);
5809 return;
Eric Laurent81784c32012-11-19 14:55:58 -08005810 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07005811 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
5812 mOutputTracks.add(outputTrack);
5813 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
5814 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005815}
5816
5817void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5818{
5819 Mutex::Autolock _l(mLock);
5820 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5821 if (mOutputTracks[i]->thread() == thread) {
5822 mOutputTracks[i]->destroy();
5823 mOutputTracks.removeAt(i);
5824 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07005825 if (thread->getOutput() == mOutput) {
5826 mOutput = NULL;
5827 }
Eric Laurent81784c32012-11-19 14:55:58 -08005828 return;
5829 }
5830 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07005831 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005832}
5833
5834// caller must hold mLock
5835void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5836{
5837 mWaitTimeMs = UINT_MAX;
5838 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5839 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5840 if (strong != 0) {
5841 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5842 if (waitTimeMs < mWaitTimeMs) {
5843 mWaitTimeMs = waitTimeMs;
5844 }
5845 }
5846 }
5847}
5848
5849
5850bool AudioFlinger::DuplicatingThread::outputsReady(
5851 const SortedVector< sp<OutputTrack> > &outputTracks)
5852{
5853 for (size_t i = 0; i < outputTracks.size(); i++) {
5854 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5855 if (thread == 0) {
5856 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5857 outputTracks[i].get());
5858 return false;
5859 }
5860 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5861 // see note at standby() declaration
5862 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5863 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5864 thread.get());
5865 return false;
5866 }
5867 }
5868 return true;
5869}
5870
5871uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5872{
5873 return (mWaitTimeMs * 1000) / 2;
5874}
5875
5876void AudioFlinger::DuplicatingThread::cacheParameters_l()
5877{
5878 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5879 updateWaitTime_l();
5880
5881 MixerThread::cacheParameters_l();
5882}
5883
5884// ----------------------------------------------------------------------------
5885// Record
5886// ----------------------------------------------------------------------------
5887
5888AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5889 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005890 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005891 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07005892 audio_devices_t inDevice,
5893 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08005894#ifdef TEE_SINK
5895 , const sp<NBAIO_Sink>& teeSink
5896#endif
5897 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07005898 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005899 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07005900 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005901 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005902#ifdef TEE_SINK
5903 , mTeeSink(teeSink)
5904#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005905 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5906 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005907 // mFastCapture below
5908 , mFastCaptureFutex(0)
5909 // mInputSource
5910 // mPipeSink
5911 // mPipeSource
5912 , mPipeFramesP2(0)
5913 // mPipeMemory
5914 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005915 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005916{
Glenn Kastend7dca052015-03-05 16:05:54 -08005917 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5918 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08005919
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005920 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005921
5922 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07005923 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005924 size_t numCounterOffers = 0;
5925 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005926#if !LOG_NDEBUG
5927 ssize_t index =
5928#else
5929 (void)
5930#endif
5931 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005932 ALOG_ASSERT(index == 0);
5933
5934 // initialize fast capture depending on configuration
5935 bool initFastCapture;
5936 switch (kUseFastCapture) {
5937 case FastCapture_Never:
5938 initFastCapture = false;
5939 break;
5940 case FastCapture_Always:
5941 initFastCapture = true;
5942 break;
5943 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07005944 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005945 break;
5946 // case FastCapture_Dynamic:
5947 }
5948
5949 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07005950 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005951 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07005952 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
5953 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005954 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5955 void *pipeBuffer;
5956 const sp<MemoryDealer> roHeap(readOnlyHeap());
5957 sp<IMemory> pipeMemory;
5958 if ((roHeap == 0) ||
5959 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5960 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5961 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5962 goto failed;
5963 }
5964 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5965 memset(pipeBuffer, 0, pipeSize);
5966 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5967 const NBAIO_Format offers[1] = {format};
5968 size_t numCounterOffers = 0;
5969 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5970 ALOG_ASSERT(index == 0);
5971 mPipeSink = pipe;
5972 PipeReader *pipeReader = new PipeReader(*pipe);
5973 numCounterOffers = 0;
5974 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5975 ALOG_ASSERT(index == 0);
5976 mPipeSource = pipeReader;
5977 mPipeFramesP2 = pipeFramesP2;
5978 mPipeMemory = pipeMemory;
5979
5980 // create fast capture
5981 mFastCapture = new FastCapture();
5982 FastCaptureStateQueue *sq = mFastCapture->sq();
5983#ifdef STATE_QUEUE_DUMP
5984 // FIXME
5985#endif
5986 FastCaptureState *state = sq->begin();
5987 state->mCblk = NULL;
5988 state->mInputSource = mInputSource.get();
5989 state->mInputSourceGen++;
5990 state->mPipeSink = pipe;
5991 state->mPipeSinkGen++;
5992 state->mFrameCount = mFrameCount;
5993 state->mCommand = FastCaptureState::COLD_IDLE;
5994 // already done in constructor initialization list
5995 //mFastCaptureFutex = 0;
5996 state->mColdFutexAddr = &mFastCaptureFutex;
5997 state->mColdGen++;
5998 state->mDumpState = &mFastCaptureDumpState;
5999#ifdef TEE_SINK
6000 // FIXME
6001#endif
6002 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
6003 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
6004 sq->end();
6005 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6006
6007 // start the fast capture
6008 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
6009 pid_t tid = mFastCapture->getTid();
Glenn Kasten8379b722016-03-18 14:54:17 -07006010 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006011#ifdef AUDIO_WATCHDOG
6012 // FIXME
6013#endif
6014
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006015 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006016 }
6017failed: ;
6018
6019 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08006020}
6021
Eric Laurent81784c32012-11-19 14:55:58 -08006022AudioFlinger::RecordThread::~RecordThread()
6023{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006024 if (mFastCapture != 0) {
6025 FastCaptureStateQueue *sq = mFastCapture->sq();
6026 FastCaptureState *state = sq->begin();
6027 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6028 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6029 if (old == -1) {
6030 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6031 }
6032 }
6033 state->mCommand = FastCaptureState::EXIT;
6034 sq->end();
6035 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6036 mFastCapture->join();
6037 mFastCapture.clear();
6038 }
6039 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07006040 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07006041 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08006042}
6043
6044void AudioFlinger::RecordThread::onFirstRef()
6045{
Glenn Kastend7dca052015-03-05 16:05:54 -08006046 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08006047}
6048
Eric Laurent81784c32012-11-19 14:55:58 -08006049bool AudioFlinger::RecordThread::threadLoop()
6050{
Eric Laurent81784c32012-11-19 14:55:58 -08006051 nsecs_t lastWarning = 0;
6052
6053 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006054
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006055reacquire_wakelock:
6056 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08006057 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006058 {
6059 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006060 size_t size = mActiveTracks.size();
6061 activeTracksGen = mActiveTracksGen;
6062 if (size > 0) {
6063 // FIXME an arbitrary choice
6064 activeTrack = mActiveTracks[0];
6065 acquireWakeLock_l(activeTrack->uid());
6066 if (size > 1) {
6067 SortedVector<int> tmp;
6068 for (size_t i = 0; i < size; i++) {
6069 tmp.add(mActiveTracks[i]->uid());
6070 }
6071 updateWakeLockUids_l(tmp);
6072 }
6073 } else {
6074 acquireWakeLock_l(-1);
6075 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006076 }
6077
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006078 // used to request a deferred sleep, to be executed later while mutex is unlocked
6079 uint32_t sleepUs = 0;
6080
6081 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006082 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006083 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07006084
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006085 // activeTracks accumulates a copy of a subset of mActiveTracks
6086 Vector< sp<RecordTrack> > activeTracks;
6087
Glenn Kasten735f45f2014-08-18 15:51:59 -07006088 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006089 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07006090
Glenn Kasten735f45f2014-08-18 15:51:59 -07006091 // reference to a fast track which is about to be removed
6092 sp<RecordTrack> fastTrackToRemove;
6093
Eric Laurent81784c32012-11-19 14:55:58 -08006094 { // scope for mLock
6095 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08006096
Eric Laurent021cf962014-05-13 10:18:14 -07006097 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006098
Eric Laurent000a4192014-01-29 15:17:32 -08006099 // check exitPending here because checkForNewParameters_l() and
6100 // checkForNewParameters_l() can temporarily release mLock
6101 if (exitPending()) {
6102 break;
6103 }
6104
Eric Laurent5c25d562016-07-13 17:17:45 -07006105 // sleep with mutex unlocked
6106 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07006107 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07006108 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
6109 ATRACE_END();
6110 sleepUs = 0;
6111 continue;
6112 }
6113
Glenn Kasten2b806402013-11-20 16:37:38 -08006114 // if no active track(s), then standby and release wakelock
6115 size_t size = mActiveTracks.size();
6116 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07006117 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006118 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08006119 releaseWakeLock_l();
6120 ALOGV("RecordThread: loop stopping");
6121 // go to sleep
6122 mWaitWorkCV.wait(mLock);
6123 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006124 goto reacquire_wakelock;
6125 }
6126
Glenn Kasten2b806402013-11-20 16:37:38 -08006127 if (mActiveTracksGen != activeTracksGen) {
6128 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006129 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08006130 for (size_t i = 0; i < size; i++) {
6131 tmp.add(mActiveTracks[i]->uid());
6132 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006133 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08006134 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006135
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006136 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07006137 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006138 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07006139
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006140 activeTrack = mActiveTracks[i];
6141 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07006142 if (activeTrack->isFastTrack()) {
6143 ALOG_ASSERT(fastTrackToRemove == 0);
6144 fastTrackToRemove = activeTrack;
6145 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006146 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08006147 mActiveTracks.remove(activeTrack);
6148 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006149 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07006150 continue;
6151 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006152
6153 TrackBase::track_state activeTrackState = activeTrack->mState;
6154 switch (activeTrackState) {
6155
6156 case TrackBase::PAUSING:
6157 mActiveTracks.remove(activeTrack);
6158 mActiveTracksGen++;
6159 doBroadcast = true;
6160 size--;
6161 continue;
6162
6163 case TrackBase::STARTING_1:
6164 sleepUs = 10000;
6165 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07006166 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006167 continue;
6168
6169 case TrackBase::STARTING_2:
6170 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006171 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07006172 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07006173 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006174 break;
6175
6176 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07006177 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006178 break;
6179
6180 case TrackBase::IDLE:
6181 i++;
6182 continue;
6183
6184 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08006185 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07006186 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006187
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006188 activeTracks.add(activeTrack);
6189 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07006190
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006191 if (activeTrack->isFastTrack()) {
6192 ALOG_ASSERT(!mFastTrackAvail);
6193 ALOG_ASSERT(fastTrack == 0);
6194 fastTrack = activeTrack;
6195 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006196 }
Eric Laurent5c25d562016-07-13 17:17:45 -07006197
6198 if (allStopped) {
6199 standbyIfNotAlreadyInStandby();
6200 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006201 if (doBroadcast) {
6202 mStartStopCond.broadcast();
6203 }
6204
6205 // sleep if there are no active tracks to process
6206 if (activeTracks.size() == 0) {
6207 if (sleepUs == 0) {
6208 sleepUs = kRecordThreadSleepUs;
6209 }
6210 continue;
6211 }
6212 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07006213
Eric Laurent81784c32012-11-19 14:55:58 -08006214 lockEffectChains_l(effectChains);
6215 }
6216
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006217 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07006218
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006219 size_t size = effectChains.size();
6220 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006221 // thread mutex is not locked, but effect chain is locked
6222 effectChains[i]->process_l();
6223 }
6224
Glenn Kasten735f45f2014-08-18 15:51:59 -07006225 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006226 if (mFastCapture != 0) {
6227 FastCaptureStateQueue *sq = mFastCapture->sq();
6228 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07006229 bool didModify = false;
6230 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006231 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
6232 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
6233 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6234 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6235 if (old == -1) {
6236 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6237 }
6238 }
6239 state->mCommand = FastCaptureState::READ_WRITE;
6240#if 0 // FIXME
6241 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08006242 FastThreadDumpState::kSamplingNforLowRamDevice :
6243 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006244#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07006245 didModify = true;
6246 }
6247 audio_track_cblk_t *cblkOld = state->mCblk;
6248 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
6249 if (cblkNew != cblkOld) {
6250 state->mCblk = cblkNew;
6251 // block until acked if removing a fast track
6252 if (cblkOld != NULL) {
6253 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
6254 }
6255 didModify = true;
6256 }
6257 sq->end(didModify);
6258 if (didModify) {
6259 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006260#if 0
6261 if (kUseFastCapture == FastCapture_Dynamic) {
6262 mNormalSource = mPipeSource;
6263 }
6264#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006265 }
6266 }
6267
Glenn Kasten735f45f2014-08-18 15:51:59 -07006268 // now run the fast track destructor with thread mutex unlocked
6269 fastTrackToRemove.clear();
6270
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006271 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
6272 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
6273 // slow, then this RecordThread will overrun by not calling HAL read often enough.
6274 // If destination is non-contiguous, first read past the nominal end of buffer, then
6275 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006276
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006277 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006278 ssize_t framesRead;
6279
6280 // If an NBAIO source is present, use it to read the normal capture's data
6281 if (mPipeSource != 0) {
6282 size_t framesToRead = mBufferSize / mFrameSize;
Glenn Kasten1b291842016-07-18 14:55:21 -07006283 framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hung57446612015-04-19 23:56:46 -07006284 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
Glenn Kastend79072e2016-01-06 08:41:20 -08006285 framesToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07006286 // since pipe is non-blocking, simulate blocking input by waiting for 1/2 of
6287 // buffer size or at least for 20ms.
6288 size_t sleepFrames = max(
6289 min(mPipeFramesP2, mRsmpInFramesP2) / 2, FMS_20 * mSampleRate / 1000);
6290 if (framesRead <= (ssize_t) sleepFrames) {
6291 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
6292 }
6293 if (framesRead < 0) {
6294 status_t status = (status_t) framesRead;
6295 switch (status) {
6296 case OVERRUN:
6297 ALOGW("overrun on read from pipe");
6298 framesRead = 0;
6299 break;
6300 case NEGOTIATE:
6301 ALOGE("re-negotiation is needed");
6302 framesRead = -1; // Will cause an attempt to recover.
6303 break;
6304 default:
6305 ALOGE("unknown error %d on read from pipe", status);
6306 break;
6307 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006308 }
6309 // otherwise use the HAL / AudioStreamIn directly
6310 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07006311 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006312 size_t bytesRead;
6313 status_t result = mInput->stream->read(
6314 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07006315 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006316 if (result < 0) {
6317 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006318 } else {
6319 framesRead = bytesRead / mFrameSize;
6320 }
6321 }
6322
Andy Hung3f0c9022016-01-15 17:49:46 -08006323 // Update server timestamp with server stats
6324 // systemTime() is optional if the hardware supports timestamps.
6325 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
6326 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6327
6328 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006329 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08006330 int64_t position, time;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006331 int ret = mInput->stream->getCapturePosition(&position, &time);
Andy Hung3f0c9022016-01-15 17:49:46 -08006332 if (ret == NO_ERROR) {
6333 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
6334 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
6335 // Note: In general record buffers should tend to be empty in
6336 // a properly running pipeline.
6337 //
6338 // Also, it is not advantageous to call get_presentation_position during the read
6339 // as the read obtains a lock, preventing the timestamp call from executing.
6340 }
6341 }
6342 // Use this to track timestamp information
6343 // ALOGD("%s", mTimestamp.toString().c_str());
6344
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006345 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006346 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006347 // Force input into standby so that it tries to recover at next read attempt
6348 inputStandBy();
6349 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006350 }
6351 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006352 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006353 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006354 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006355
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006356 if (mTeeSink != 0) {
Andy Hung57446612015-04-19 23:56:46 -07006357 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006358 }
6359 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006360 {
6361 size_t part1 = mRsmpInFramesP2 - rear;
6362 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07006363 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006364 (framesRead - part1) * mFrameSize);
6365 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006366 }
6367 rear = mRsmpInRear += framesRead;
6368
6369 size = activeTracks.size();
6370 // loop over each active track
6371 for (size_t i = 0; i < size; i++) {
6372 activeTrack = activeTracks[i];
6373
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006374 // skip fast tracks, as those are handled directly by FastCapture
6375 if (activeTrack->isFastTrack()) {
6376 continue;
6377 }
6378
Andy Hung73c02e42015-03-29 01:13:58 -07006379 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07006380 // TODO: Update the activeTrack buffer converter in case of reconfigure.
6381
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006382 enum {
6383 OVERRUN_UNKNOWN,
6384 OVERRUN_TRUE,
6385 OVERRUN_FALSE
6386 } overrun = OVERRUN_UNKNOWN;
6387
6388 // loop over getNextBuffer to handle circular sink
6389 for (;;) {
6390
6391 activeTrack->mSink.frameCount = ~0;
6392 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
6393 size_t framesOut = activeTrack->mSink.frameCount;
6394 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
6395
Andy Hung73c02e42015-03-29 01:13:58 -07006396 // check available frames and handle overrun conditions
6397 // if the record track isn't draining fast enough.
6398 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006399 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07006400 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
6401 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006402 overrun = OVERRUN_TRUE;
6403 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006404 if (framesOut == 0 || framesIn == 0) {
6405 break;
6406 }
6407
Andy Hung6770c6f2015-04-07 13:43:36 -07006408 // Don't allow framesOut to be larger than what is possible with resampling
6409 // from framesIn.
6410 // This isn't strictly necessary but helps limit buffer resizing in
6411 // RecordBufferConverter. TODO: remove when no longer needed.
6412 framesOut = min(framesOut,
6413 destinationFramesPossible(
6414 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07006415 // process frames from the RecordThread buffer provider to the RecordTrack buffer
6416 framesOut = activeTrack->mRecordBufferConverter->convert(
6417 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006418
6419 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
6420 overrun = OVERRUN_FALSE;
6421 }
6422
6423 if (activeTrack->mFramesToDrop == 0) {
6424 if (framesOut > 0) {
6425 activeTrack->mSink.frameCount = framesOut;
6426 activeTrack->releaseBuffer(&activeTrack->mSink);
6427 }
6428 } else {
6429 // FIXME could do a partial drop of framesOut
6430 if (activeTrack->mFramesToDrop > 0) {
6431 activeTrack->mFramesToDrop -= framesOut;
6432 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006433 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006434 }
6435 } else {
6436 activeTrack->mFramesToDrop += framesOut;
6437 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
6438 activeTrack->mSyncStartEvent->isCancelled()) {
6439 ALOGW("Synced record %s, session %d, trigger session %d",
6440 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
6441 activeTrack->sessionId(),
6442 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08006443 activeTrack->mSyncStartEvent->triggerSession() :
6444 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006445 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006446 }
6447 }
6448 }
6449
6450 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006451 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006452 }
6453 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006454
6455 switch (overrun) {
6456 case OVERRUN_TRUE:
6457 // client isn't retrieving buffers fast enough
6458 if (!activeTrack->setOverflow()) {
6459 nsecs_t now = systemTime();
6460 // FIXME should lastWarning per track?
6461 if ((now - lastWarning) > kWarningThrottleNs) {
6462 ALOGW("RecordThread: buffer overflow");
6463 lastWarning = now;
6464 }
6465 }
6466 break;
6467 case OVERRUN_FALSE:
6468 activeTrack->clearOverflow();
6469 break;
6470 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006471 break;
6472 }
6473
Andy Hung3f0c9022016-01-15 17:49:46 -08006474 // update frame information and push timestamp out
6475 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08006476 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08006477 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
6478 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006479 }
6480
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006481unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08006482 // enable changes in effect chain
6483 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006484 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08006485 }
6486
Glenn Kasten93e471f2013-08-19 08:40:07 -07006487 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08006488
6489 {
6490 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07006491 for (size_t i = 0; i < mTracks.size(); i++) {
6492 sp<RecordTrack> track = mTracks[i];
6493 track->invalidate();
6494 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006495 mActiveTracks.clear();
6496 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08006497 mStartStopCond.broadcast();
6498 }
6499
6500 releaseWakeLock();
6501
6502 ALOGV("RecordThread %p exiting", this);
6503 return false;
6504}
6505
Glenn Kasten93e471f2013-08-19 08:40:07 -07006506void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08006507{
6508 if (!mStandby) {
6509 inputStandBy();
6510 mStandby = true;
6511 }
6512}
6513
6514void AudioFlinger::RecordThread::inputStandBy()
6515{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006516 // Idle the fast capture if it's currently running
6517 if (mFastCapture != 0) {
6518 FastCaptureStateQueue *sq = mFastCapture->sq();
6519 FastCaptureState *state = sq->begin();
6520 if (!(state->mCommand & FastCaptureState::IDLE)) {
6521 state->mCommand = FastCaptureState::COLD_IDLE;
6522 state->mColdFutexAddr = &mFastCaptureFutex;
6523 state->mColdGen++;
6524 mFastCaptureFutex = 0;
6525 sq->end();
6526 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
6527 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
6528#if 0
6529 if (kUseFastCapture == FastCapture_Dynamic) {
6530 // FIXME
6531 }
6532#endif
6533#ifdef AUDIO_WATCHDOG
6534 // FIXME
6535#endif
6536 } else {
6537 sq->end(false /*didModify*/);
6538 }
6539 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006540 status_t result = mInput->stream->standby();
6541 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07006542
6543 // If going into standby, flush the pipe source.
6544 if (mPipeSource.get() != nullptr) {
6545 const ssize_t flushed = mPipeSource->flush();
6546 if (flushed > 0) {
6547 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
6548 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
6549 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6550 }
6551 }
Eric Laurent81784c32012-11-19 14:55:58 -08006552}
6553
Glenn Kasten05997e22014-03-13 15:08:33 -07006554// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07006555sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08006556 const sp<AudioFlinger::Client>& client,
6557 uint32_t sampleRate,
6558 audio_format_t format,
6559 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08006560 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08006561 audio_session_t sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07006562 size_t *notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006563 int uid,
Eric Laurent05067782016-06-01 18:27:28 -07006564 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08006565 pid_t tid,
6566 status_t *status)
6567{
Glenn Kasten74935e42013-12-19 08:56:45 -08006568 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08006569 sp<RecordTrack> track;
6570 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07006571 audio_input_flags_t inputFlags = mInput->flags;
6572
6573 // special case for FAST flag considered OK if fast capture is present
6574 if (hasFastCapture()) {
6575 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
6576 }
6577
6578 // Check if requested flags are compatible with output stream flags
6579 if ((*flags & inputFlags) != *flags) {
6580 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
6581 " input flags (%08x)",
6582 *flags, inputFlags);
6583 *flags = (audio_input_flags_t)(*flags & inputFlags);
6584 }
Eric Laurent81784c32012-11-19 14:55:58 -08006585
Glenn Kasten90e58b12013-07-31 16:16:02 -07006586 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07006587 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006588 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07006589 // we formerly checked for a callback handler (non-0 tid),
6590 // but that is no longer required for TRANSFER_OBTAIN mode
6591 //
Glenn Kasten74105912014-07-03 12:28:53 -07006592 // frame count is not specified, or is exactly the pipe depth
6593 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006594 // PCM data
6595 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006596 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006597 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006598 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006599 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006600 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07006601 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006602 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006603 hasFastCapture() &&
6604 // there are sufficient fast track slots available
6605 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07006606 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07006607 // check compatibility with audio effects.
6608 Mutex::Autolock _l(mLock);
6609 // Do not accept FAST flag if the session has software effects
6610 sp<EffectChain> chain = getEffectChain_l(sessionId);
6611 if (chain != 0) {
Eric Laurent122f7e72016-06-29 11:53:29 -07006612 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_RAW) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07006613 "AUDIO_INPUT_FLAG_RAW denied: effect present on session");
6614 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_RAW);
6615 if (chain->hasSoftwareEffect()) {
6616 ALOGV("AUDIO_INPUT_FLAG_FAST denied: software effect present on session");
6617 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
6618 }
6619 }
Eric Laurent122f7e72016-06-29 11:53:29 -07006620 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07006621 "AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
6622 frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006623 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006624 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
Glenn Kasten74105912014-07-03 12:28:53 -07006625 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006626 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07006627 frameCount, mFrameCount, mPipeFramesP2,
6628 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
6629 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07006630 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07006631 }
6632 }
6633
6634 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07006635 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07006636 // fast track: frame count is exactly the pipe depth
6637 frameCount = mPipeFramesP2;
6638 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
6639 *notificationFrames = mFrameCount;
6640 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006641 // not fast track: max notification period is resampled equivalent of one HAL buffer time
6642 // or 20 ms if there is a fast capture
6643 // TODO This could be a roundupRatio inline, and const
6644 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
6645 * sampleRate + mSampleRate - 1) / mSampleRate;
6646 // minimum number of notification periods is at least kMinNotifications,
6647 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
6648 static const size_t kMinNotifications = 3;
6649 static const uint32_t kMinMs = 30;
6650 // TODO This could be a roundupRatio inline
6651 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
6652 // TODO This could be a roundupRatio inline
6653 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
6654 maxNotificationFrames;
6655 const size_t minFrameCount = maxNotificationFrames *
6656 max(kMinNotifications, minNotificationsByMs);
6657 frameCount = max(frameCount, minFrameCount);
6658 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
6659 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07006660 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07006661 }
Glenn Kasten74935e42013-12-19 08:56:45 -08006662 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07006663
Glenn Kasten15e57982013-09-24 11:52:37 -07006664 lStatus = initCheck();
6665 if (lStatus != NO_ERROR) {
6666 ALOGE("createRecordTrack_l() audio driver not initialized");
6667 goto Exit;
6668 }
Eric Laurent81784c32012-11-19 14:55:58 -08006669
6670 { // scope for mLock
6671 Mutex::Autolock _l(mLock);
6672
6673 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07006674 format, channelMask, frameCount, NULL, sessionId, uid,
6675 *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08006676
Glenn Kasten03003332013-08-06 15:40:54 -07006677 lStatus = track->initCheck();
6678 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07006679 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08006680 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08006681 goto Exit;
6682 }
6683 mTracks.add(track);
6684
6685 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6686 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6687 mAudioFlinger->btNrecIsOff();
6688 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6689 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006690
Eric Laurent05067782016-06-01 18:27:28 -07006691 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006692 pid_t callingPid = IPCThreadState::self()->getCallingPid();
6693 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
6694 // so ask activity manager to do this on our behalf
6695 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
6696 }
Eric Laurent81784c32012-11-19 14:55:58 -08006697 }
Glenn Kasten05997e22014-03-13 15:08:33 -07006698
Eric Laurent81784c32012-11-19 14:55:58 -08006699 lStatus = NO_ERROR;
6700
6701Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07006702 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08006703 return track;
6704}
6705
6706status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6707 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08006708 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08006709{
6710 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6711 sp<ThreadBase> strongMe = this;
6712 status_t status = NO_ERROR;
6713
6714 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006715 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006716 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006717 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08006718 triggerSession,
6719 recordTrack->sessionId(),
6720 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006721 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08006722 // Sync event can be cancelled by the trigger session if the track is not in a
6723 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006724 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006725 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006726 } else {
6727 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006728 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006729 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08006730 }
6731 }
6732
6733 {
Glenn Kasten47c20702013-08-13 15:37:35 -07006734 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08006735 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006736 if (mActiveTracks.indexOf(recordTrack) >= 0) {
6737 if (recordTrack->mState == TrackBase::PAUSING) {
6738 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006739 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006740 } else {
6741 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08006742 }
6743 return status;
6744 }
6745
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006746 // TODO consider other ways of handling this, such as changing the state to :STARTING and
6747 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6748 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006749 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08006750 mActiveTracks.add(recordTrack);
6751 mActiveTracksGen++;
Eric Laurent83b88082014-06-20 18:31:16 -07006752 status_t status = NO_ERROR;
6753 if (recordTrack->isExternalTrack()) {
6754 mLock.unlock();
Glenn Kastend848eb42016-03-08 13:42:11 -08006755 status = AudioSystem::startInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006756 mLock.lock();
6757 // FIXME should verify that recordTrack is still in mActiveTracks
6758 if (status != NO_ERROR) {
6759 mActiveTracks.remove(recordTrack);
6760 mActiveTracksGen++;
6761 recordTrack->clearSyncStartEvent();
6762 ALOGV("RecordThread::start error %d", status);
6763 return status;
6764 }
Eric Laurent81784c32012-11-19 14:55:58 -08006765 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006766 // Catch up with current buffer indices if thread is already running.
6767 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
6768 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6769 // see previously buffered data before it called start(), but with greater risk of overrun.
6770
Andy Hung73c02e42015-03-29 01:13:58 -07006771 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07006772 // clear any converter state as new data will be discontinuous
6773 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006774 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08006775 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08006776 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08006777 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006778 ALOGV("Record failed to start");
6779 status = BAD_VALUE;
6780 goto startError;
6781 }
Eric Laurent81784c32012-11-19 14:55:58 -08006782 return status;
6783 }
Glenn Kasten7c027242012-12-26 14:43:16 -08006784
Eric Laurent81784c32012-11-19 14:55:58 -08006785startError:
Eric Laurent83b88082014-06-20 18:31:16 -07006786 if (recordTrack->isExternalTrack()) {
Glenn Kastend848eb42016-03-08 13:42:11 -08006787 AudioSystem::stopInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006788 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006789 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006790 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08006791 return status;
6792}
6793
Eric Laurent81784c32012-11-19 14:55:58 -08006794void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6795{
6796 sp<SyncEvent> strongEvent = event.promote();
6797
6798 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08006799 sp<RefBase> ptr = strongEvent->cookie().promote();
6800 if (ptr != 0) {
6801 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6802 recordTrack->handleSyncStartEvent(strongEvent);
6803 }
Eric Laurent81784c32012-11-19 14:55:58 -08006804 }
6805}
6806
Glenn Kastena8356f62013-07-25 14:37:52 -07006807bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08006808 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07006809 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006810 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08006811 return false;
6812 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006813 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006814 recordTrack->mState = TrackBase::PAUSING;
Eric Laurent5c25d562016-07-13 17:17:45 -07006815 // signal thread to stop
6816 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08006817 // do not wait for mStartStopCond if exiting
6818 if (exitPending()) {
6819 return true;
6820 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006821 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08006822 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006823 // if we have been restarted, recordTrack is in mActiveTracks here
6824 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006825 ALOGV("Record stopped OK");
6826 return true;
6827 }
6828 return false;
6829}
6830
Glenn Kasten0f11b512014-01-31 16:18:54 -08006831bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08006832{
6833 return false;
6834}
6835
Glenn Kasten0f11b512014-01-31 16:18:54 -08006836status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006837{
6838#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6839 if (!isValidSyncEvent(event)) {
6840 return BAD_VALUE;
6841 }
6842
Glenn Kastend848eb42016-03-08 13:42:11 -08006843 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08006844 status_t ret = NAME_NOT_FOUND;
6845
6846 Mutex::Autolock _l(mLock);
6847
6848 for (size_t i = 0; i < mTracks.size(); i++) {
6849 sp<RecordTrack> track = mTracks[i];
6850 if (eventSession == track->sessionId()) {
6851 (void) track->setSyncEvent(event);
6852 ret = NO_ERROR;
6853 }
6854 }
6855 return ret;
6856#else
6857 return BAD_VALUE;
6858#endif
6859}
6860
6861// destroyTrack_l() must be called with ThreadBase::mLock held
6862void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6863{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006864 track->terminate();
6865 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006866 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006867 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006868 removeTrack_l(track);
6869 }
6870}
6871
6872void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6873{
6874 mTracks.remove(track);
6875 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006876 if (track->isFastTrack()) {
6877 ALOG_ASSERT(!mFastTrackAvail);
6878 mFastTrackAvail = true;
6879 }
Eric Laurent81784c32012-11-19 14:55:58 -08006880}
6881
6882void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6883{
6884 dumpInternals(fd, args);
6885 dumpTracks(fd, args);
6886 dumpEffectChains(fd, args);
6887}
6888
6889void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6890{
Elliott Hughes87cebad2014-05-22 10:14:43 -07006891 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08006892
Glenn Kasten44182c22015-03-05 17:12:23 -08006893 dumpBase(fd, args);
6894
6895 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006896 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006897 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006898 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006899 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08006900
Glenn Kasten2f90c512015-12-02 11:40:09 -08006901 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
6902 // while we are dumping it. It may be inconsistent, but it won't mutate!
6903 // This is a large object so we place it on the heap.
6904 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
6905 const FastCaptureDumpState *copy = new FastCaptureDumpState(mFastCaptureDumpState);
6906 copy->dump(fd);
6907 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08006908}
6909
Glenn Kasten0f11b512014-01-31 16:18:54 -08006910void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006911{
6912 const size_t SIZE = 256;
6913 char buffer[SIZE];
6914 String8 result;
6915
Marco Nelissenb2208842014-02-07 14:00:50 -08006916 size_t numtracks = mTracks.size();
6917 size_t numactive = mActiveTracks.size();
6918 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006919 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006920 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006921 dprintf(fd, " of which %zu are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006922 RecordTrack::appendDumpHeader(result);
6923 for (size_t i = 0; i < numtracks ; ++i) {
6924 sp<RecordTrack> track = mTracks[i];
6925 if (track != 0) {
6926 bool active = mActiveTracks.indexOf(track) >= 0;
6927 if (active) {
6928 numactiveseen++;
6929 }
6930 track->dump(buffer, SIZE, active);
6931 result.append(buffer);
6932 }
Eric Laurent81784c32012-11-19 14:55:58 -08006933 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006934 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006935 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006936 }
6937
Marco Nelissenb2208842014-02-07 14:00:50 -08006938 if (numactiveseen != numactive) {
6939 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6940 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006941 result.append(buffer);
6942 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006943 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006944 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006945 if (mTracks.indexOf(track) < 0) {
6946 track->dump(buffer, SIZE, true);
6947 result.append(buffer);
6948 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006949 }
Eric Laurent81784c32012-11-19 14:55:58 -08006950
6951 }
6952 write(fd, result.string(), result.size());
6953}
6954
Andy Hung73c02e42015-03-29 01:13:58 -07006955
6956void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
6957{
6958 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6959 RecordThread *recordThread = (RecordThread *) threadBase.get();
6960 mRsmpInFront = recordThread->mRsmpInRear;
6961 mRsmpInUnrel = 0;
6962}
6963
6964void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
6965 size_t *framesAvailable, bool *hasOverrun)
6966{
6967 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6968 RecordThread *recordThread = (RecordThread *) threadBase.get();
6969 const int32_t rear = recordThread->mRsmpInRear;
6970 const int32_t front = mRsmpInFront;
6971 const ssize_t filled = rear - front;
6972
6973 size_t framesIn;
6974 bool overrun = false;
6975 if (filled < 0) {
6976 // should not happen, but treat like a massive overrun and re-sync
6977 framesIn = 0;
6978 mRsmpInFront = rear;
6979 overrun = true;
6980 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
6981 framesIn = (size_t) filled;
6982 } else {
6983 // client is not keeping up with server, but give it latest data
6984 framesIn = recordThread->mRsmpInFrames;
6985 mRsmpInFront = /* front = */ rear - framesIn;
6986 overrun = true;
6987 }
6988 if (framesAvailable != NULL) {
6989 *framesAvailable = framesIn;
6990 }
6991 if (hasOverrun != NULL) {
6992 *hasOverrun = overrun;
6993 }
6994}
6995
Eric Laurent81784c32012-11-19 14:55:58 -08006996// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006997status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08006998 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006999{
Andy Hung73c02e42015-03-29 01:13:58 -07007000 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007001 if (threadBase == 0) {
7002 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08007003 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007004 return NOT_ENOUGH_DATA;
7005 }
7006 RecordThread *recordThread = (RecordThread *) threadBase.get();
7007 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07007008 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07007009 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007010 // FIXME should not be P2 (don't want to increase latency)
7011 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08007012 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07007013 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007014 front &= recordThread->mRsmpInFramesP2 - 1;
7015 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07007016 if (part1 > (size_t) filled) {
7017 part1 = filled;
7018 }
7019 size_t ask = buffer->frameCount;
7020 ALOG_ASSERT(ask > 0);
7021 if (part1 > ask) {
7022 part1 = ask;
7023 }
7024 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07007025 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07007026 buffer->raw = NULL;
7027 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07007028 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07007029 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08007030 }
7031
Andy Hung57446612015-04-19 23:56:46 -07007032 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07007033 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07007034 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08007035 return NO_ERROR;
7036}
7037
7038// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007039void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
7040 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08007041{
Glenn Kasten85948432013-08-19 12:09:05 -07007042 size_t stepCount = buffer->frameCount;
7043 if (stepCount == 0) {
7044 return;
7045 }
Andy Hung73c02e42015-03-29 01:13:58 -07007046 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
7047 mRsmpInUnrel -= stepCount;
7048 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07007049 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08007050 buffer->frameCount = 0;
7051}
7052
Andy Hung97a893e2015-03-29 01:03:07 -07007053AudioFlinger::RecordThread::RecordBufferConverter::RecordBufferConverter(
7054 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
7055 uint32_t srcSampleRate,
7056 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
7057 uint32_t dstSampleRate) :
7058 mSrcChannelMask(AUDIO_CHANNEL_INVALID), // updateParameters will set following vars
7059 // mSrcFormat
7060 // mSrcSampleRate
7061 // mDstChannelMask
7062 // mDstFormat
7063 // mDstSampleRate
7064 // mSrcChannelCount
7065 // mDstChannelCount
7066 // mDstFrameSize
7067 mBuf(NULL), mBufFrames(0), mBufFrameSize(0),
Andy Hungd330ee42015-04-20 13:23:41 -07007068 mResampler(NULL),
7069 mIsLegacyDownmix(false),
7070 mIsLegacyUpmix(false),
7071 mRequiresFloat(false),
7072 mInputConverterProvider(NULL)
Andy Hung97a893e2015-03-29 01:03:07 -07007073{
7074 (void)updateParameters(srcChannelMask, srcFormat, srcSampleRate,
7075 dstChannelMask, dstFormat, dstSampleRate);
7076}
7077
7078AudioFlinger::RecordThread::RecordBufferConverter::~RecordBufferConverter() {
7079 free(mBuf);
7080 delete mResampler;
Andy Hungd330ee42015-04-20 13:23:41 -07007081 delete mInputConverterProvider;
Andy Hung97a893e2015-03-29 01:03:07 -07007082}
7083
7084size_t AudioFlinger::RecordThread::RecordBufferConverter::convert(void *dst,
7085 AudioBufferProvider *provider, size_t frames)
7086{
Andy Hungd330ee42015-04-20 13:23:41 -07007087 if (mInputConverterProvider != NULL) {
7088 mInputConverterProvider->setBufferProvider(provider);
7089 provider = mInputConverterProvider;
7090 }
7091
7092 if (mResampler == NULL) {
Andy Hung97a893e2015-03-29 01:03:07 -07007093 ALOGVV("NO RESAMPLING sampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
7094 mSrcSampleRate, mSrcFormat, mDstFormat);
7095
7096 AudioBufferProvider::Buffer buffer;
7097 for (size_t i = frames; i > 0; ) {
7098 buffer.frameCount = i;
Glenn Kastend79072e2016-01-06 08:41:20 -08007099 status_t status = provider->getNextBuffer(&buffer);
Andy Hung97a893e2015-03-29 01:03:07 -07007100 if (status != OK || buffer.frameCount == 0) {
7101 frames -= i; // cannot fill request.
7102 break;
7103 }
Andy Hungd330ee42015-04-20 13:23:41 -07007104 // format convert to destination buffer
7105 convertNoResampler(dst, buffer.raw, buffer.frameCount);
Andy Hung97a893e2015-03-29 01:03:07 -07007106
7107 dst = (int8_t*)dst + buffer.frameCount * mDstFrameSize;
7108 i -= buffer.frameCount;
7109 provider->releaseBuffer(&buffer);
7110 }
7111 } else {
7112 ALOGVV("RESAMPLING mSrcSampleRate:%u mDstSampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
7113 mSrcSampleRate, mDstSampleRate, mSrcFormat, mDstFormat);
7114
Andy Hungd330ee42015-04-20 13:23:41 -07007115 // reallocate buffer if needed
7116 if (mBufFrameSize != 0 && mBufFrames < frames) {
7117 free(mBuf);
7118 mBufFrames = frames;
7119 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
7120 }
Andy Hung97a893e2015-03-29 01:03:07 -07007121 // resampler accumulates, but we only have one source track
Andy Hungd330ee42015-04-20 13:23:41 -07007122 memset(mBuf, 0, frames * mBufFrameSize);
7123 frames = mResampler->resample((int32_t*)mBuf, frames, provider);
7124 // format convert to destination buffer
7125 convertResampler(dst, mBuf, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07007126 }
7127 return frames;
7128}
7129
7130status_t AudioFlinger::RecordThread::RecordBufferConverter::updateParameters(
7131 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
7132 uint32_t srcSampleRate,
7133 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
7134 uint32_t dstSampleRate)
7135{
7136 // quick evaluation if there is any change.
7137 if (mSrcFormat == srcFormat
7138 && mSrcChannelMask == srcChannelMask
7139 && mSrcSampleRate == srcSampleRate
7140 && mDstFormat == dstFormat
7141 && mDstChannelMask == dstChannelMask
7142 && mDstSampleRate == dstSampleRate) {
7143 return NO_ERROR;
7144 }
7145
Andy Hungdb4c0312015-05-06 08:46:52 -07007146 ALOGV("RecordBufferConverter updateParameters srcMask:%#x dstMask:%#x"
7147 " srcFormat:%#x dstFormat:%#x srcRate:%u dstRate:%u",
7148 srcChannelMask, dstChannelMask, srcFormat, dstFormat, srcSampleRate, dstSampleRate);
Andy Hung97a893e2015-03-29 01:03:07 -07007149 const bool valid =
7150 audio_is_input_channel(srcChannelMask)
7151 && audio_is_input_channel(dstChannelMask)
7152 && audio_is_valid_format(srcFormat) && audio_is_linear_pcm(srcFormat)
7153 && audio_is_valid_format(dstFormat) && audio_is_linear_pcm(dstFormat)
7154 && (srcSampleRate <= dstSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX)
7155 ; // no upsampling checks for now
7156 if (!valid) {
7157 return BAD_VALUE;
7158 }
7159
7160 mSrcFormat = srcFormat;
7161 mSrcChannelMask = srcChannelMask;
7162 mSrcSampleRate = srcSampleRate;
7163 mDstFormat = dstFormat;
7164 mDstChannelMask = dstChannelMask;
7165 mDstSampleRate = dstSampleRate;
7166
7167 // compute derived parameters
7168 mSrcChannelCount = audio_channel_count_from_in_mask(srcChannelMask);
7169 mDstChannelCount = audio_channel_count_from_in_mask(dstChannelMask);
7170 mDstFrameSize = mDstChannelCount * audio_bytes_per_sample(mDstFormat);
7171
Andy Hungd330ee42015-04-20 13:23:41 -07007172 // do we need to resample?
7173 delete mResampler;
7174 mResampler = NULL;
7175 if (mSrcSampleRate != mDstSampleRate) {
7176 mResampler = AudioResampler::create(AUDIO_FORMAT_PCM_FLOAT,
7177 mSrcChannelCount, mDstSampleRate);
7178 mResampler->setSampleRate(mSrcSampleRate);
7179 mResampler->setVolume(AudioMixer::UNITY_GAIN_FLOAT, AudioMixer::UNITY_GAIN_FLOAT);
7180 }
7181
7182 // are we running legacy channel conversion modes?
7183 mIsLegacyDownmix = (mSrcChannelMask == AUDIO_CHANNEL_IN_STEREO
7184 || mSrcChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK)
7185 && mDstChannelMask == AUDIO_CHANNEL_IN_MONO;
7186 mIsLegacyUpmix = mSrcChannelMask == AUDIO_CHANNEL_IN_MONO
7187 && (mDstChannelMask == AUDIO_CHANNEL_IN_STEREO
7188 || mDstChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK);
7189
7190 // do we need to process in float?
7191 mRequiresFloat = mResampler != NULL || mIsLegacyDownmix || mIsLegacyUpmix;
7192
7193 // do we need a staging buffer to convert for destination (we can still optimize this)?
7194 // we use mBufFrameSize > 0 to indicate both frame size as well as buffer necessity
7195 if (mResampler != NULL) {
7196 mBufFrameSize = max(mSrcChannelCount, FCC_2)
7197 * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
Andy Hunga97630b2015-07-22 23:27:24 -07007198 } else if (mIsLegacyUpmix || mIsLegacyDownmix) { // legacy modes always float
Andy Hungd330ee42015-04-20 13:23:41 -07007199 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
7200 } else if (mSrcChannelMask != mDstChannelMask && mDstFormat != mSrcFormat) {
Andy Hung97a893e2015-03-29 01:03:07 -07007201 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(mSrcFormat);
7202 } else {
7203 mBufFrameSize = 0;
7204 }
7205 mBufFrames = 0; // force the buffer to be resized.
7206
Andy Hungd330ee42015-04-20 13:23:41 -07007207 // do we need an input converter buffer provider to give us float?
7208 delete mInputConverterProvider;
7209 mInputConverterProvider = NULL;
7210 if (mRequiresFloat && mSrcFormat != AUDIO_FORMAT_PCM_FLOAT) {
7211 mInputConverterProvider = new ReformatBufferProvider(
7212 audio_channel_count_from_in_mask(mSrcChannelMask),
7213 mSrcFormat,
7214 AUDIO_FORMAT_PCM_FLOAT,
7215 256 /* provider buffer frame count */);
7216 }
7217
7218 // do we need a remixer to do channel mask conversion
7219 if (!mIsLegacyDownmix && !mIsLegacyUpmix && mSrcChannelMask != mDstChannelMask) {
7220 (void) memcpy_by_index_array_initialization_from_channel_mask(
7221 mIdxAry, ARRAY_SIZE(mIdxAry), mDstChannelMask, mSrcChannelMask);
Andy Hung97a893e2015-03-29 01:03:07 -07007222 }
7223 return NO_ERROR;
7224}
7225
Andy Hungd330ee42015-04-20 13:23:41 -07007226void AudioFlinger::RecordThread::RecordBufferConverter::convertNoResampler(
7227 void *dst, const void *src, size_t frames)
Andy Hung97a893e2015-03-29 01:03:07 -07007228{
Andy Hungd330ee42015-04-20 13:23:41 -07007229 // src is native type unless there is legacy upmix or downmix, whereupon it is float.
Andy Hung97a893e2015-03-29 01:03:07 -07007230 if (mBufFrameSize != 0 && mBufFrames < frames) {
7231 free(mBuf);
7232 mBufFrames = frames;
7233 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
7234 }
Andy Hungd330ee42015-04-20 13:23:41 -07007235 // do we need to do legacy upmix and downmix?
7236 if (mIsLegacyUpmix || mIsLegacyDownmix) {
Andy Hung97a893e2015-03-29 01:03:07 -07007237 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07007238 if (mIsLegacyUpmix) {
7239 upmix_to_stereo_float_from_mono_float((float *)dstBuf,
7240 (const float *)src, frames);
7241 } else /*mIsLegacyDownmix */ {
7242 downmix_to_mono_float_from_stereo_float((float *)dstBuf,
7243 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07007244 }
Andy Hungd330ee42015-04-20 13:23:41 -07007245 if (mBuf != NULL) {
7246 memcpy_by_audio_format(dst, mDstFormat, mBuf, AUDIO_FORMAT_PCM_FLOAT,
7247 frames * mDstChannelCount);
7248 }
7249 return;
7250 }
7251 // do we need to do channel mask conversion?
7252 if (mSrcChannelMask != mDstChannelMask) {
Andy Hung97a893e2015-03-29 01:03:07 -07007253 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07007254 memcpy_by_index_array(dstBuf, mDstChannelCount,
7255 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mSrcFormat), frames);
7256 if (dstBuf == dst) {
7257 return; // format is the same
7258 }
7259 }
7260 // convert to destination buffer
7261 const void *convertBuf = mBuf != NULL ? mBuf : src;
7262 memcpy_by_audio_format(dst, mDstFormat, convertBuf, mSrcFormat,
7263 frames * mDstChannelCount);
7264}
7265
7266void AudioFlinger::RecordThread::RecordBufferConverter::convertResampler(
7267 void *dst, /*not-a-const*/ void *src, size_t frames)
7268{
7269 // src buffer format is ALWAYS float when entering this routine
7270 if (mIsLegacyUpmix) {
7271 ; // mono to stereo already handled by resampler
7272 } else if (mIsLegacyDownmix
7273 || (mSrcChannelMask == mDstChannelMask && mSrcChannelCount == 1)) {
7274 // the resampler outputs stereo for mono input channel (a feature?)
7275 // must convert to mono
7276 downmix_to_mono_float_from_stereo_float((float *)src,
7277 (const float *)src, frames);
7278 } else if (mSrcChannelMask != mDstChannelMask) {
7279 // convert to mono channel again for channel mask conversion (could be skipped
7280 // with further optimization).
Andy Hung97a893e2015-03-29 01:03:07 -07007281 if (mSrcChannelCount == 1) {
Andy Hungd330ee42015-04-20 13:23:41 -07007282 downmix_to_mono_float_from_stereo_float((float *)src,
7283 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07007284 }
Andy Hungd330ee42015-04-20 13:23:41 -07007285 // convert to destination format (in place, OK as float is larger than other types)
7286 if (mDstFormat != AUDIO_FORMAT_PCM_FLOAT) {
7287 memcpy_by_audio_format(src, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
7288 frames * mSrcChannelCount);
7289 }
7290 // channel convert and save to dst
7291 memcpy_by_index_array(dst, mDstChannelCount,
7292 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mDstFormat), frames);
7293 return;
Andy Hung97a893e2015-03-29 01:03:07 -07007294 }
Andy Hungd330ee42015-04-20 13:23:41 -07007295 // convert to destination format and save to dst
7296 memcpy_by_audio_format(dst, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
7297 frames * mDstChannelCount);
Andy Hung97a893e2015-03-29 01:03:07 -07007298}
7299
Eric Laurent10351942014-05-08 18:49:52 -07007300bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
7301 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007302{
7303 bool reconfig = false;
7304
Eric Laurent10351942014-05-08 18:49:52 -07007305 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007306
Eric Laurent10351942014-05-08 18:49:52 -07007307 audio_format_t reqFormat = mFormat;
7308 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07007309 // 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 -07007310 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
7311
7312 AudioParameter param = AudioParameter(keyValuePair);
7313 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07007314
7315 // scope for AutoPark extends to end of method
7316 AutoPark<FastCapture> park(mFastCapture);
7317
Eric Laurent10351942014-05-08 18:49:52 -07007318 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
7319 // channel count change can be requested. Do we mandate the first client defines the
7320 // HAL sampling rate and channel count or do we allow changes on the fly?
7321 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
7322 samplingRate = value;
7323 reconfig = true;
7324 }
7325 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07007326 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07007327 status = BAD_VALUE;
7328 } else {
7329 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08007330 reconfig = true;
7331 }
Eric Laurent10351942014-05-08 18:49:52 -07007332 }
7333 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
7334 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07007335 if (!audio_is_input_channel(mask) ||
7336 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007337 status = BAD_VALUE;
7338 } else {
7339 channelMask = mask;
7340 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007341 }
Eric Laurent10351942014-05-08 18:49:52 -07007342 }
7343 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7344 // do not accept frame count changes if tracks are open as the track buffer
7345 // size depends on frame count and correct behavior would not be guaranteed
7346 // if frame count is changed after track creation
7347 if (mActiveTracks.size() > 0) {
7348 status = INVALID_OPERATION;
7349 } else {
7350 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007351 }
Eric Laurent10351942014-05-08 18:49:52 -07007352 }
7353 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7354 // forward device change to effects that have requested to be
7355 // aware of attached audio device.
7356 for (size_t i = 0; i < mEffectChains.size(); i++) {
7357 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08007358 }
Eric Laurent81784c32012-11-19 14:55:58 -08007359
Eric Laurent10351942014-05-08 18:49:52 -07007360 // store input device and output device but do not forward output device to audio HAL.
7361 // Note that status is ignored by the caller for output device
7362 // (see AudioFlinger::setParameters()
7363 if (audio_is_output_devices(value)) {
7364 mOutDevice = value;
7365 status = BAD_VALUE;
7366 } else {
7367 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07007368 if (value != AUDIO_DEVICE_NONE) {
7369 mPrevInDevice = value;
7370 }
Eric Laurent10351942014-05-08 18:49:52 -07007371 // disable AEC and NS if the device is a BT SCO headset supporting those
7372 // pre processings
7373 if (mTracks.size() > 0) {
7374 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7375 mAudioFlinger->btNrecIsOff();
7376 for (size_t i = 0; i < mTracks.size(); i++) {
7377 sp<RecordTrack> track = mTracks[i];
7378 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7379 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08007380 }
7381 }
7382 }
Eric Laurent10351942014-05-08 18:49:52 -07007383 }
7384 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
7385 mAudioSource != (audio_source_t)value) {
7386 // forward device change to effects that have requested to be
7387 // aware of attached audio device.
7388 for (size_t i = 0; i < mEffectChains.size(); i++) {
7389 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08007390 }
Eric Laurent10351942014-05-08 18:49:52 -07007391 mAudioSource = (audio_source_t)value;
7392 }
Glenn Kastene198c362013-08-13 09:13:36 -07007393
Eric Laurent10351942014-05-08 18:49:52 -07007394 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007395 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007396 if (status == INVALID_OPERATION) {
7397 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007398 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007399 }
7400 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007401 if (status == BAD_VALUE) {
7402 uint32_t sRate;
7403 audio_channel_mask_t channelMask;
7404 audio_format_t format;
7405 if (mInput->stream->getAudioProperties(&sRate, &channelMask, &format) == OK &&
7406 audio_is_linear_pcm(format) && audio_is_linear_pcm(reqFormat) &&
7407 sRate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
7408 audio_channel_count_from_in_mask(channelMask) <= FCC_8) {
7409 status = NO_ERROR;
7410 }
Eric Laurent81784c32012-11-19 14:55:58 -08007411 }
Eric Laurent10351942014-05-08 18:49:52 -07007412 if (status == NO_ERROR) {
7413 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007414 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08007415 }
7416 }
Eric Laurent81784c32012-11-19 14:55:58 -08007417 }
Eric Laurent10351942014-05-08 18:49:52 -07007418
Eric Laurent81784c32012-11-19 14:55:58 -08007419 return reconfig;
7420}
7421
7422String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
7423{
Eric Laurent81784c32012-11-19 14:55:58 -08007424 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007425 if (initCheck() == NO_ERROR) {
7426 String8 out_s8;
7427 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
7428 return out_s8;
7429 }
Eric Laurent81784c32012-11-19 14:55:58 -08007430 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007431 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08007432}
7433
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007434void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007435 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7436
7437 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08007438
7439 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007440 case AUDIO_INPUT_OPENED:
7441 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07007442 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07007443 desc->mChannelMask = mChannelMask;
7444 desc->mSamplingRate = mSampleRate;
7445 desc->mFormat = mFormat;
7446 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07007447 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07007448 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007449 break;
7450
Eric Laurent73e26b62015-04-27 16:55:58 -07007451 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08007452 default:
7453 break;
7454 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007455 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08007456}
7457
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007458void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007459{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007460 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
7461 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hunge5412692014-05-16 11:25:07 -07007462 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007463 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_8, "HAL channel count %d > %d", mChannelCount, FCC_8);
Andy Hung463be252014-07-10 16:56:07 -07007464 mFormat = mHALFormat;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007465 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
7466 result = mInput->stream->getFrameSize(&mFrameSize);
7467 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
7468 result = mInput->stream->getBufferSize(&mBufferSize);
7469 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08007470 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007471 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08007472 // 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 -07007473 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08007474 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007475 // A larger value should allow more old data to be read after a track calls start(),
7476 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07007477 //
7478 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08007479 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07007480 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07007481 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07007482 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007483
7484 // TODO optimize audio capture buffer sizes ...
7485 // Here we calculate the size of the sliding buffer used as a source
7486 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
7487 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
7488 // be better to have it derived from the pipe depth in the long term.
7489 // The current value is higher than necessary. However it should not add to latency.
7490
Glenn Kasten85948432013-08-19 12:09:05 -07007491 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Glenn Kasten1b291842016-07-18 14:55:21 -07007492 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
7493 (void)posix_memalign(&mRsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
7494 memset(mRsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize); // if posix_memalign fails, will segv here.
Eric Laurent81784c32012-11-19 14:55:58 -08007495
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007496 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
7497 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08007498}
7499
Glenn Kasten5f972c02014-01-13 09:59:31 -08007500uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08007501{
7502 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007503 uint32_t result;
7504 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
7505 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08007506 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007507 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007508}
7509
Eric Laurent4c415062016-06-17 16:14:16 -07007510// hasAudioSession_l() must be called with ThreadBase::mLock held
7511uint32_t AudioFlinger::RecordThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08007512{
Eric Laurent81784c32012-11-19 14:55:58 -08007513 uint32_t result = 0;
7514 if (getEffectChain_l(sessionId) != 0) {
7515 result = EFFECT_SESSION;
7516 }
7517
7518 for (size_t i = 0; i < mTracks.size(); ++i) {
7519 if (sessionId == mTracks[i]->sessionId()) {
7520 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07007521 if (mTracks[i]->isFastTrack()) {
7522 result |= FAST_SESSION;
7523 }
Eric Laurent81784c32012-11-19 14:55:58 -08007524 break;
7525 }
7526 }
7527
7528 return result;
7529}
7530
Glenn Kastend848eb42016-03-08 13:42:11 -08007531KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08007532{
Glenn Kastend848eb42016-03-08 13:42:11 -08007533 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08007534 Mutex::Autolock _l(mLock);
7535 for (size_t j = 0; j < mTracks.size(); ++j) {
7536 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08007537 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08007538 if (ids.indexOfKey(sessionId) < 0) {
7539 ids.add(sessionId, true);
7540 }
7541 }
7542 return ids;
7543}
7544
7545AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7546{
7547 Mutex::Autolock _l(mLock);
7548 AudioStreamIn *input = mInput;
7549 mInput = NULL;
7550 return input;
7551}
7552
7553// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007554sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08007555{
7556 if (mInput == NULL) {
7557 return NULL;
7558 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007559 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08007560}
7561
7562status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7563{
7564 // only one chain per input thread
7565 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07007566 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08007567 return INVALID_OPERATION;
7568 }
7569 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07007570 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08007571 chain->setInBuffer(NULL);
7572 chain->setOutBuffer(NULL);
7573
7574 checkSuspendOnAddEffectChain_l(chain);
7575
Eric Laurent1b928682014-10-02 19:41:47 -07007576 // make sure enabled pre processing effects state is communicated to the HAL as we
7577 // just moved them to a new input stream.
7578 chain->syncHalEffectsState();
7579
Eric Laurent81784c32012-11-19 14:55:58 -08007580 mEffectChains.add(chain);
7581
7582 return NO_ERROR;
7583}
7584
7585size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7586{
7587 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7588 ALOGW_IF(mEffectChains.size() != 1,
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007589 "removeEffectChain_l() %p invalid chain size %zu on thread %p",
Eric Laurent81784c32012-11-19 14:55:58 -08007590 chain.get(), mEffectChains.size(), this);
7591 if (mEffectChains.size() == 1) {
7592 mEffectChains.removeAt(0);
7593 }
7594 return 0;
7595}
7596
Eric Laurent1c333e22014-05-20 10:48:17 -07007597status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7598 audio_patch_handle_t *handle)
7599{
7600 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007601
7602 // store new device and send to effects
7603 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07007604 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07007605 for (size_t i = 0; i < mEffectChains.size(); i++) {
7606 mEffectChains[i]->setDevice_l(mInDevice);
7607 }
7608
7609 // disable AEC and NS if the device is a BT SCO headset supporting those
7610 // pre processings
7611 if (mTracks.size() > 0) {
7612 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7613 mAudioFlinger->btNrecIsOff();
7614 for (size_t i = 0; i < mTracks.size(); i++) {
7615 sp<RecordTrack> track = mTracks[i];
7616 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7617 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
7618 }
7619 }
7620
7621 // store new source and send to effects
7622 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7623 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07007624 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07007625 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07007626 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007627 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007628
Eric Laurent054d9d32015-04-24 08:48:48 -07007629 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007630 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7631 status = hwDevice->createAudioPatch(patch->num_sources,
7632 patch->sources,
7633 patch->num_sinks,
7634 patch->sinks,
7635 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007636 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007637 char *address;
7638 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7639 address = audio_device_address_to_parameter(
7640 patch->sources[0].ext.device.type,
7641 patch->sources[0].ext.device.address);
7642 } else {
7643 address = (char *)calloc(1, 1);
7644 }
7645 AudioParameter param = AudioParameter(String8(address));
7646 free(address);
7647 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING),
7648 (int)patch->sources[0].ext.device.type);
7649 param.addInt(String8(AUDIO_PARAMETER_STREAM_INPUT_SOURCE),
7650 (int)patch->sinks[0].ext.mix.usecase.source);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007651 status = mInput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07007652 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07007653 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007654
Eric Laurente8726fe2015-06-26 09:39:24 -07007655 if (mInDevice != mPrevInDevice) {
7656 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7657 mPrevInDevice = mInDevice;
7658 }
Eric Laurent296fb132015-05-01 11:38:42 -07007659
Eric Laurent1c333e22014-05-20 10:48:17 -07007660 return status;
7661}
7662
7663status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7664{
7665 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007666
7667 mInDevice = AUDIO_DEVICE_NONE;
7668
Eric Laurent1c333e22014-05-20 10:48:17 -07007669 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007670 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7671 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007672 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007673 AudioParameter param;
7674 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007675 status = mInput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07007676 }
7677 return status;
7678}
7679
Eric Laurent83b88082014-06-20 18:31:16 -07007680void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
7681{
7682 Mutex::Autolock _l(mLock);
7683 mTracks.add(record);
7684}
7685
7686void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
7687{
7688 Mutex::Autolock _l(mLock);
7689 destroyTrack_l(record);
7690}
7691
7692void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
7693{
7694 ThreadBase::getAudioPortConfig(config);
7695 config->role = AUDIO_PORT_ROLE_SINK;
7696 config->ext.mix.hw_module = mInput->audioHwDev->handle();
7697 config->ext.mix.usecase.source = mAudioSource;
7698}
Eric Laurent1c333e22014-05-20 10:48:17 -07007699
Glenn Kasten63238ef2015-03-02 15:50:29 -08007700} // namespace android