blob: e661a3b0fac5aeca72dff1848badda9bd6db2517 [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>
Andy Hung2ddee192015-12-18 17:34:44 -080036#include <audio_utils/conversion.h>
Eric Laurent81784c32012-11-19 14:55:58 -080037#include <audio_utils/primitives.h>
Andy Hung98ef9782014-03-04 14:46:50 -080038#include <audio_utils/format.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070039#include <audio_utils/minifloat.h>
Mikhail Naganov9fe94012016-10-14 14:57:40 -070040#include <system/audio_effects/effect_ns.h>
41#include <system/audio_effects/effect_aec.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
Mikhail Naganov00260b52016-10-13 12:54:24 -070056#include <hardware/audio.h> // for AUDIO_DEVICE_API_VERSION_...
57
Eric Laurent81784c32012-11-19 14:55:58 -080058#include "AudioFlinger.h"
59#include "AudioMixer.h"
Andy Hungd330ee42015-04-20 13:23:41 -070060#include "BufferProviders.h"
Eric Laurent81784c32012-11-19 14:55:58 -080061#include "FastMixer.h"
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070062#include "FastCapture.h"
Eric Laurent81784c32012-11-19 14:55:58 -080063#include "ServiceUtilities.h"
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -070064#include "mediautils/SchedulingPolicyService.h"
Eric Laurent81784c32012-11-19 14:55:58 -080065
Eric Laurent81784c32012-11-19 14:55:58 -080066#ifdef ADD_BATTERY_DATA
67#include <media/IMediaPlayerService.h>
68#include <media/IMediaDeathNotifier.h>
69#endif
70
Eric Laurent81784c32012-11-19 14:55:58 -080071#ifdef DEBUG_CPU_USAGE
72#include <cpustats/CentralTendencyStatistics.h>
73#include <cpustats/ThreadCpuUsage.h>
74#endif
75
Glenn Kastenc05b8d72016-03-24 09:48:17 -070076#include "AutoPark.h"
77
Eric Laurent81784c32012-11-19 14:55:58 -080078// ----------------------------------------------------------------------------
79
80// Note: the following macro is used for extremely verbose logging message. In
81// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
82// 0; but one side effect of this is to turn all LOGV's as well. Some messages
83// are so verbose that we want to suppress them even when we have ALOG_ASSERT
84// turned on. Do not uncomment the #def below unless you really know what you
85// are doing and want to see all of the extremely verbose messages.
86//#define VERY_VERY_VERBOSE_LOGGING
87#ifdef VERY_VERY_VERBOSE_LOGGING
88#define ALOGVV ALOGV
89#else
90#define ALOGVV(a...) do { } while(0)
91#endif
92
Andy Hung6770c6f2015-04-07 13:43:36 -070093// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -070094#define max(a, b) ((a) > (b) ? (a) : (b))
Andy Hung6770c6f2015-04-07 13:43:36 -070095template <typename T>
96static inline T min(const T& a, const T& b)
97{
98 return a < b ? a : b;
99}
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700100
Andy Hungd330ee42015-04-20 13:23:41 -0700101#ifndef ARRAY_SIZE
Chih-Hung Hsiehbf291732016-05-17 15:16:07 -0700102#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
Andy Hungd330ee42015-04-20 13:23:41 -0700103#endif
104
Eric Laurent81784c32012-11-19 14:55:58 -0800105namespace android {
106
107// retry counts for buffer fill timeout
108// 50 * ~20msecs = 1 second
109static const int8_t kMaxTrackRetries = 50;
110static const int8_t kMaxTrackStartupRetries = 50;
111// allow less retry attempts on direct output thread.
112// direct outputs can be a scarce resource in audio hardware and should
113// be released as quickly as possible.
114static const int8_t kMaxTrackRetriesDirect = 2;
Eric Laurente93cc032016-05-05 10:15:10 -0700115
Eric Laurent51716182016-02-29 18:00:56 -0800116
Eric Laurent81784c32012-11-19 14:55:58 -0800117
118// don't warn about blocked writes or record buffer overflows more often than this
119static const nsecs_t kWarningThrottleNs = seconds(5);
120
121// RecordThread loop sleep time upon application overrun or audio HAL read error
122static const int kRecordThreadSleepUs = 5000;
123
Eric Laurent10351942014-05-08 18:49:52 -0700124// maximum time to wait in sendConfigEvent_l() for a status to be received
125static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800126
127// minimum sleep time for the mixer thread loop when tracks are active but in underrun
128static const uint32_t kMinThreadSleepTimeUs = 5000;
129// maximum divider applied to the active sleep time in the mixer thread loop
130static const uint32_t kMaxThreadSleepTimeShift = 2;
131
Andy Hung09a50072014-02-27 14:30:47 -0800132// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700133// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800134static const uint32_t kMinNormalSinkBufferSizeMs = 20;
135// maximum normal sink buffer size
136static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800137
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700138// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
139// FIXME This should be based on experimentally observed scheduling jitter
140static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
141
Eric Laurent972a1732013-09-04 09:42:59 -0700142// Offloaded output thread standby delay: allows track transition without going to standby
143static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
144
Eric Laurent51716182016-02-29 18:00:56 -0800145// Direct output thread minimum sleep time in idle or active(underrun) state
146static const nsecs_t kDirectMinSleepTimeUs = 10000;
147
Glenn Kasten1b291842016-07-18 14:55:21 -0700148// The universal constant for ubiquitous 20ms value. The value of 20ms seems to provide a good
149// balance between power consumption and latency, and allows threads to be scheduled reliably
150// by the CFS scheduler.
151// FIXME Express other hardcoded references to 20ms with references to this constant and move
152// it appropriately.
153#define FMS_20 20
Eric Laurent51716182016-02-29 18:00:56 -0800154
Eric Laurent81784c32012-11-19 14:55:58 -0800155// Whether to use fast mixer
156static const enum {
157 FastMixer_Never, // never initialize or use: for debugging only
158 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
159 // normal mixer multiplier is 1
160 FastMixer_Static, // initialize if needed, then use all the time if initialized,
161 // multiplier is calculated based on min & max normal mixer buffer size
162 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
163 // multiplier is calculated based on min & max normal mixer buffer size
164 // FIXME for FastMixer_Dynamic:
165 // Supporting this option will require fixing HALs that can't handle large writes.
166 // For example, one HAL implementation returns an error from a large write,
167 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
168 // We could either fix the HAL implementations, or provide a wrapper that breaks
169 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
170} kUseFastMixer = FastMixer_Static;
171
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700172// Whether to use fast capture
173static const enum {
174 FastCapture_Never, // never initialize or use: for debugging only
175 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
176 FastCapture_Static, // initialize if needed, then use all the time if initialized
177} kUseFastCapture = FastCapture_Static;
178
Eric Laurent81784c32012-11-19 14:55:58 -0800179// Priorities for requestPriority
180static const int kPriorityAudioApp = 2;
181static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700182static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800183
Glenn Kastenea38ee72016-04-18 11:08:01 -0700184// IAudioFlinger::createTrack() has an in/out parameter 'pFrameCount' for the total size of the
185// track buffer in shared memory. Zero on input means to use a default value. For fast tracks,
186// AudioFlinger derives the default from HAL buffer size and 'fast track multiplier'.
Glenn Kasten03490092014-05-27 12:30:54 -0700187
188// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800189static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800190
Glenn Kasten03490092014-05-27 12:30:54 -0700191// The minimum and maximum allowed values
192static const int kFastTrackMultiplierMin = 1;
193static const int kFastTrackMultiplierMax = 2;
194
195// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
196static int sFastTrackMultiplier = kFastTrackMultiplier;
197
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700198// See Thread::readOnlyHeap().
199// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
200// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
201// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Glenn Kasten9f81de32014-07-27 15:02:23 -0700202static const size_t kRecordThreadReadOnlyHeapSize = 0x2000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700203
Eric Laurent81784c32012-11-19 14:55:58 -0800204// ----------------------------------------------------------------------------
205
Glenn Kasten03490092014-05-27 12:30:54 -0700206static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
207
208static void sFastTrackMultiplierInit()
209{
210 char value[PROPERTY_VALUE_MAX];
211 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
212 char *endptr;
213 unsigned long ul = strtoul(value, &endptr, 0);
214 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
215 sFastTrackMultiplier = (int) ul;
216 }
217 }
218}
219
220// ----------------------------------------------------------------------------
221
Eric Laurent81784c32012-11-19 14:55:58 -0800222#ifdef ADD_BATTERY_DATA
223// To collect the amplifier usage
224static void addBatteryData(uint32_t params) {
225 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
226 if (service == NULL) {
227 // it already logged
228 return;
229 }
230
231 service->addBatteryData(params);
232}
233#endif
234
Andy Hung3f0c9022016-01-15 17:49:46 -0800235// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
236struct {
237 // call when you acquire a partial wakelock
238 void acquire(const sp<IBinder> &wakeLockToken) {
239 pthread_mutex_lock(&mLock);
240 if (wakeLockToken.get() == nullptr) {
241 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
242 } else {
243 if (mCount == 0) {
244 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
245 }
246 ++mCount;
247 }
248 pthread_mutex_unlock(&mLock);
249 }
250
251 // call when you release a partial wakelock.
252 void release(const sp<IBinder> &wakeLockToken) {
253 if (wakeLockToken.get() == nullptr) {
254 return;
255 }
256 pthread_mutex_lock(&mLock);
257 if (--mCount < 0) {
258 ALOGE("negative wakelock count");
259 mCount = 0;
260 }
261 pthread_mutex_unlock(&mLock);
262 }
263
264 // retrieves the boottime timebase offset from monotonic.
265 int64_t getBoottimeOffset() {
266 pthread_mutex_lock(&mLock);
267 int64_t boottimeOffset = mBoottimeOffset;
268 pthread_mutex_unlock(&mLock);
269 return boottimeOffset;
270 }
271
272 // Adjusts the timebase offset between TIMEBASE_MONOTONIC
273 // and the selected timebase.
274 // Currently only TIMEBASE_BOOTTIME is allowed.
275 //
276 // This only needs to be called upon acquiring the first partial wakelock
277 // after all other partial wakelocks are released.
278 //
279 // We do an empirical measurement of the offset rather than parsing
280 // /proc/timer_list since the latter is not a formal kernel ABI.
281 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
282 int clockbase;
283 switch (timebase) {
284 case ExtendedTimestamp::TIMEBASE_BOOTTIME:
285 clockbase = SYSTEM_TIME_BOOTTIME;
286 break;
287 default:
288 LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
289 break;
290 }
291 // try three times to get the clock offset, choose the one
292 // with the minimum gap in measurements.
293 const int tries = 3;
294 nsecs_t bestGap, measured;
295 for (int i = 0; i < tries; ++i) {
296 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
297 const nsecs_t tbase = systemTime(clockbase);
298 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
299 const nsecs_t gap = tmono2 - tmono;
300 if (i == 0 || gap < bestGap) {
301 bestGap = gap;
302 measured = tbase - ((tmono + tmono2) >> 1);
303 }
304 }
305
306 // to avoid micro-adjusting, we don't change the timebase
307 // unless it is significantly different.
308 //
309 // Assumption: It probably takes more than toleranceNs to
310 // suspend and resume the device.
311 static int64_t toleranceNs = 10000; // 10 us
312 if (llabs(*offset - measured) > toleranceNs) {
313 ALOGV("Adjusting timebase offset old: %lld new: %lld",
314 (long long)*offset, (long long)measured);
315 *offset = measured;
316 }
317 }
318
319 pthread_mutex_t mLock;
320 int32_t mCount;
321 int64_t mBoottimeOffset;
322} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
Eric Laurent81784c32012-11-19 14:55:58 -0800323
324// ----------------------------------------------------------------------------
325// CPU Stats
326// ----------------------------------------------------------------------------
327
328class CpuStats {
329public:
330 CpuStats();
331 void sample(const String8 &title);
332#ifdef DEBUG_CPU_USAGE
333private:
334 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
335 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
336
337 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
338
339 int mCpuNum; // thread's current CPU number
340 int mCpukHz; // frequency of thread's current CPU in kHz
341#endif
342};
343
344CpuStats::CpuStats()
345#ifdef DEBUG_CPU_USAGE
346 : mCpuNum(-1), mCpukHz(-1)
347#endif
348{
349}
350
Glenn Kasten0f11b512014-01-31 16:18:54 -0800351void CpuStats::sample(const String8 &title
352#ifndef DEBUG_CPU_USAGE
353 __unused
354#endif
355 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800356#ifdef DEBUG_CPU_USAGE
357 // get current thread's delta CPU time in wall clock ns
358 double wcNs;
359 bool valid = mCpuUsage.sampleAndEnable(wcNs);
360
361 // record sample for wall clock statistics
362 if (valid) {
363 mWcStats.sample(wcNs);
364 }
365
366 // get the current CPU number
367 int cpuNum = sched_getcpu();
368
369 // get the current CPU frequency in kHz
370 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
371
372 // check if either CPU number or frequency changed
373 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
374 mCpuNum = cpuNum;
375 mCpukHz = cpukHz;
376 // ignore sample for purposes of cycles
377 valid = false;
378 }
379
380 // if no change in CPU number or frequency, then record sample for cycle statistics
381 if (valid && mCpukHz > 0) {
382 double cycles = wcNs * cpukHz * 0.000001;
383 mHzStats.sample(cycles);
384 }
385
386 unsigned n = mWcStats.n();
387 // mCpuUsage.elapsed() is expensive, so don't call it every loop
388 if ((n & 127) == 1) {
389 long long elapsed = mCpuUsage.elapsed();
390 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
391 double perLoop = elapsed / (double) n;
392 double perLoop100 = perLoop * 0.01;
393 double perLoop1k = perLoop * 0.001;
394 double mean = mWcStats.mean();
395 double stddev = mWcStats.stddev();
396 double minimum = mWcStats.minimum();
397 double maximum = mWcStats.maximum();
398 double meanCycles = mHzStats.mean();
399 double stddevCycles = mHzStats.stddev();
400 double minCycles = mHzStats.minimum();
401 double maxCycles = mHzStats.maximum();
402 mCpuUsage.resetElapsed();
403 mWcStats.reset();
404 mHzStats.reset();
405 ALOGD("CPU usage for %s over past %.1f secs\n"
406 " (%u mixer loops at %.1f mean ms per loop):\n"
407 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
408 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
409 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
410 title.string(),
411 elapsed * .000000001, n, perLoop * .000001,
412 mean * .001,
413 stddev * .001,
414 minimum * .001,
415 maximum * .001,
416 mean / perLoop100,
417 stddev / perLoop100,
418 minimum / perLoop100,
419 maximum / perLoop100,
420 meanCycles / perLoop1k,
421 stddevCycles / perLoop1k,
422 minCycles / perLoop1k,
423 maxCycles / perLoop1k);
424
425 }
426 }
427#endif
428};
429
430// ----------------------------------------------------------------------------
431// ThreadBase
432// ----------------------------------------------------------------------------
433
Glenn Kasten97b7b752014-09-28 13:04:24 -0700434// static
435const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
436{
437 switch (type) {
438 case MIXER:
439 return "MIXER";
440 case DIRECT:
441 return "DIRECT";
442 case DUPLICATING:
443 return "DUPLICATING";
444 case RECORD:
445 return "RECORD";
446 case OFFLOAD:
447 return "OFFLOAD";
448 default:
449 return "unknown";
450 }
451}
452
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800453String8 devicesToString(audio_devices_t devices)
454{
455 static const struct mapping {
456 audio_devices_t mDevices;
457 const char * mString;
458 } mappingsOut[] = {
Glenn Kasten818da522015-12-02 13:53:26 -0800459 {AUDIO_DEVICE_OUT_EARPIECE, "EARPIECE"},
460 {AUDIO_DEVICE_OUT_SPEAKER, "SPEAKER"},
461 {AUDIO_DEVICE_OUT_WIRED_HEADSET, "WIRED_HEADSET"},
462 {AUDIO_DEVICE_OUT_WIRED_HEADPHONE, "WIRED_HEADPHONE"},
463 {AUDIO_DEVICE_OUT_BLUETOOTH_SCO, "BLUETOOTH_SCO"},
464 {AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET, "BLUETOOTH_SCO_HEADSET"},
465 {AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT, "BLUETOOTH_SCO_CARKIT"},
466 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, "BLUETOOTH_A2DP"},
467 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,"BLUETOOTH_A2DP_HEADPHONES"},
468 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER, "BLUETOOTH_A2DP_SPEAKER"},
469 {AUDIO_DEVICE_OUT_AUX_DIGITAL, "AUX_DIGITAL"},
470 {AUDIO_DEVICE_OUT_HDMI, "HDMI"},
471 {AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET,"ANLG_DOCK_HEADSET"},
472 {AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET,"DGTL_DOCK_HEADSET"},
473 {AUDIO_DEVICE_OUT_USB_ACCESSORY, "USB_ACCESSORY"},
474 {AUDIO_DEVICE_OUT_USB_DEVICE, "USB_DEVICE"},
475 {AUDIO_DEVICE_OUT_TELEPHONY_TX, "TELEPHONY_TX"},
476 {AUDIO_DEVICE_OUT_LINE, "LINE"},
477 {AUDIO_DEVICE_OUT_HDMI_ARC, "HDMI_ARC"},
478 {AUDIO_DEVICE_OUT_SPDIF, "SPDIF"},
479 {AUDIO_DEVICE_OUT_FM, "FM"},
480 {AUDIO_DEVICE_OUT_AUX_LINE, "AUX_LINE"},
481 {AUDIO_DEVICE_OUT_SPEAKER_SAFE, "SPEAKER_SAFE"},
482 {AUDIO_DEVICE_OUT_IP, "IP"},
Eric Laurent58545be2016-02-22 18:54:20 -0800483 {AUDIO_DEVICE_OUT_BUS, "BUS"},
Glenn Kasten818da522015-12-02 13:53:26 -0800484 {AUDIO_DEVICE_NONE, "NONE"}, // must be last
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800485 }, mappingsIn[] = {
Glenn Kasten818da522015-12-02 13:53:26 -0800486 {AUDIO_DEVICE_IN_COMMUNICATION, "COMMUNICATION"},
487 {AUDIO_DEVICE_IN_AMBIENT, "AMBIENT"},
488 {AUDIO_DEVICE_IN_BUILTIN_MIC, "BUILTIN_MIC"},
489 {AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET, "BLUETOOTH_SCO_HEADSET"},
490 {AUDIO_DEVICE_IN_WIRED_HEADSET, "WIRED_HEADSET"},
491 {AUDIO_DEVICE_IN_AUX_DIGITAL, "AUX_DIGITAL"},
492 {AUDIO_DEVICE_IN_VOICE_CALL, "VOICE_CALL"},
493 {AUDIO_DEVICE_IN_TELEPHONY_RX, "TELEPHONY_RX"},
494 {AUDIO_DEVICE_IN_BACK_MIC, "BACK_MIC"},
495 {AUDIO_DEVICE_IN_REMOTE_SUBMIX, "REMOTE_SUBMIX"},
496 {AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET, "ANLG_DOCK_HEADSET"},
497 {AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET, "DGTL_DOCK_HEADSET"},
498 {AUDIO_DEVICE_IN_USB_ACCESSORY, "USB_ACCESSORY"},
499 {AUDIO_DEVICE_IN_USB_DEVICE, "USB_DEVICE"},
500 {AUDIO_DEVICE_IN_FM_TUNER, "FM_TUNER"},
501 {AUDIO_DEVICE_IN_TV_TUNER, "TV_TUNER"},
502 {AUDIO_DEVICE_IN_LINE, "LINE"},
503 {AUDIO_DEVICE_IN_SPDIF, "SPDIF"},
504 {AUDIO_DEVICE_IN_BLUETOOTH_A2DP, "BLUETOOTH_A2DP"},
505 {AUDIO_DEVICE_IN_LOOPBACK, "LOOPBACK"},
506 {AUDIO_DEVICE_IN_IP, "IP"},
Eric Laurent58545be2016-02-22 18:54:20 -0800507 {AUDIO_DEVICE_IN_BUS, "BUS"},
Glenn Kasten818da522015-12-02 13:53:26 -0800508 {AUDIO_DEVICE_NONE, "NONE"}, // must be last
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800509 };
510 String8 result;
511 audio_devices_t allDevices = AUDIO_DEVICE_NONE;
512 const mapping *entry;
513 if (devices & AUDIO_DEVICE_BIT_IN) {
514 devices &= ~AUDIO_DEVICE_BIT_IN;
515 entry = mappingsIn;
516 } else {
517 entry = mappingsOut;
518 }
519 for ( ; entry->mDevices != AUDIO_DEVICE_NONE; entry++) {
520 allDevices = (audio_devices_t) (allDevices | entry->mDevices);
521 if (devices & entry->mDevices) {
522 if (!result.isEmpty()) {
523 result.append("|");
524 }
525 result.append(entry->mString);
526 }
527 }
528 if (devices & ~allDevices) {
529 if (!result.isEmpty()) {
530 result.append("|");
531 }
532 result.appendFormat("0x%X", devices & ~allDevices);
533 }
534 if (result.isEmpty()) {
535 result.append(entry->mString);
536 }
537 return result;
538}
539
540String8 inputFlagsToString(audio_input_flags_t flags)
541{
542 static const struct mapping {
543 audio_input_flags_t mFlag;
544 const char * mString;
545 } mappings[] = {
Glenn Kasten818da522015-12-02 13:53:26 -0800546 {AUDIO_INPUT_FLAG_FAST, "FAST"},
547 {AUDIO_INPUT_FLAG_HW_HOTWORD, "HW_HOTWORD"},
548 {AUDIO_INPUT_FLAG_RAW, "RAW"},
549 {AUDIO_INPUT_FLAG_SYNC, "SYNC"},
550 {AUDIO_INPUT_FLAG_NONE, "NONE"}, // must be last
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800551 };
552 String8 result;
553 audio_input_flags_t allFlags = AUDIO_INPUT_FLAG_NONE;
554 const mapping *entry;
555 for (entry = mappings; entry->mFlag != AUDIO_INPUT_FLAG_NONE; entry++) {
556 allFlags = (audio_input_flags_t) (allFlags | entry->mFlag);
557 if (flags & entry->mFlag) {
558 if (!result.isEmpty()) {
559 result.append("|");
560 }
561 result.append(entry->mString);
562 }
563 }
564 if (flags & ~allFlags) {
565 if (!result.isEmpty()) {
566 result.append("|");
567 }
568 result.appendFormat("0x%X", flags & ~allFlags);
569 }
570 if (result.isEmpty()) {
571 result.append(entry->mString);
572 }
573 return result;
574}
575
576String8 outputFlagsToString(audio_output_flags_t flags)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700577{
578 static const struct mapping {
579 audio_output_flags_t mFlag;
580 const char * mString;
581 } mappings[] = {
Glenn Kasten818da522015-12-02 13:53:26 -0800582 {AUDIO_OUTPUT_FLAG_DIRECT, "DIRECT"},
583 {AUDIO_OUTPUT_FLAG_PRIMARY, "PRIMARY"},
584 {AUDIO_OUTPUT_FLAG_FAST, "FAST"},
585 {AUDIO_OUTPUT_FLAG_DEEP_BUFFER, "DEEP_BUFFER"},
586 {AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,"COMPRESS_OFFLOAD"},
587 {AUDIO_OUTPUT_FLAG_NON_BLOCKING, "NON_BLOCKING"},
588 {AUDIO_OUTPUT_FLAG_HW_AV_SYNC, "HW_AV_SYNC"},
589 {AUDIO_OUTPUT_FLAG_RAW, "RAW"},
590 {AUDIO_OUTPUT_FLAG_SYNC, "SYNC"},
591 {AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO, "IEC958_NONAUDIO"},
592 {AUDIO_OUTPUT_FLAG_NONE, "NONE"}, // must be last
Glenn Kasten97b7b752014-09-28 13:04:24 -0700593 };
594 String8 result;
595 audio_output_flags_t allFlags = AUDIO_OUTPUT_FLAG_NONE;
596 const mapping *entry;
597 for (entry = mappings; entry->mFlag != AUDIO_OUTPUT_FLAG_NONE; entry++) {
598 allFlags = (audio_output_flags_t) (allFlags | entry->mFlag);
599 if (flags & entry->mFlag) {
600 if (!result.isEmpty()) {
601 result.append("|");
602 }
603 result.append(entry->mString);
604 }
605 }
606 if (flags & ~allFlags) {
607 if (!result.isEmpty()) {
608 result.append("|");
609 }
610 result.appendFormat("0x%X", flags & ~allFlags);
611 }
612 if (result.isEmpty()) {
613 result.append(entry->mString);
614 }
615 return result;
616}
617
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800618const char *sourceToString(audio_source_t source)
619{
620 switch (source) {
621 case AUDIO_SOURCE_DEFAULT: return "default";
622 case AUDIO_SOURCE_MIC: return "mic";
623 case AUDIO_SOURCE_VOICE_UPLINK: return "voice uplink";
624 case AUDIO_SOURCE_VOICE_DOWNLINK: return "voice downlink";
625 case AUDIO_SOURCE_VOICE_CALL: return "voice call";
626 case AUDIO_SOURCE_CAMCORDER: return "camcorder";
627 case AUDIO_SOURCE_VOICE_RECOGNITION: return "voice recognition";
628 case AUDIO_SOURCE_VOICE_COMMUNICATION: return "voice communication";
629 case AUDIO_SOURCE_REMOTE_SUBMIX: return "remote submix";
rago8a397d52015-12-02 11:27:57 -0800630 case AUDIO_SOURCE_UNPROCESSED: return "unprocessed";
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800631 case AUDIO_SOURCE_FM_TUNER: return "FM tuner";
632 case AUDIO_SOURCE_HOTWORD: return "hotword";
633 default: return "unknown";
634 }
635}
636
Eric Laurent81784c32012-11-19 14:55:58 -0800637AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -0700638 audio_devices_t outDevice, audio_devices_t inDevice, type_t type, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -0800639 : Thread(false /*canCallJava*/),
640 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700641 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700642 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800643 // are set by PlaybackThread::readOutputParameters_l() or
644 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700645 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800646 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700647 mPrevOutDevice(AUDIO_DEVICE_NONE), mPrevInDevice(AUDIO_DEVICE_NONE),
648 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800649 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700650 mDeathRecipient(new PMDeathRecipient(this)),
Wei Jia3f273d12015-11-24 09:06:49 -0800651 mSystemReady(systemReady),
652 mNotifiedBatteryStart(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800653{
Eric Laurent296fb132015-05-01 11:38:42 -0700654 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800655}
656
657AudioFlinger::ThreadBase::~ThreadBase()
658{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700659 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700660 mConfigEvents.clear();
661
Eric Laurent81784c32012-11-19 14:55:58 -0800662 // do not lock the mutex in destructor
663 releaseWakeLock_l();
664 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800665 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800666 binder->unlinkToDeath(mDeathRecipient);
667 }
668}
669
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700670status_t AudioFlinger::ThreadBase::readyToRun()
671{
672 status_t status = initCheck();
673 if (status == NO_ERROR) {
674 ALOGI("AudioFlinger's thread %p ready to run", this);
675 } else {
676 ALOGE("No working audio driver found.");
677 }
678 return status;
679}
680
Eric Laurent81784c32012-11-19 14:55:58 -0800681void AudioFlinger::ThreadBase::exit()
682{
683 ALOGV("ThreadBase::exit");
684 // do any cleanup required for exit to succeed
685 preExit();
686 {
687 // This lock prevents the following race in thread (uniprocessor for illustration):
688 // if (!exitPending()) {
689 // // context switch from here to exit()
690 // // exit() calls requestExit(), what exitPending() observes
691 // // exit() calls signal(), which is dropped since no waiters
692 // // context switch back from exit() to here
693 // mWaitWorkCV.wait(...);
694 // // now thread is hung
695 // }
696 AutoMutex lock(mLock);
697 requestExit();
698 mWaitWorkCV.broadcast();
699 }
700 // When Thread::requestExitAndWait is made virtual and this method is renamed to
701 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
702 requestExitAndWait();
703}
704
705status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
706{
Eric Laurent81784c32012-11-19 14:55:58 -0800707 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
708 Mutex::Autolock _l(mLock);
709
Eric Laurent10351942014-05-08 18:49:52 -0700710 return sendSetParameterConfigEvent_l(keyValuePairs);
711}
712
713// sendConfigEvent_l() must be called with ThreadBase::mLock held
714// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
715status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
716{
717 status_t status = NO_ERROR;
718
Eric Laurent72e3f392015-05-20 14:43:50 -0700719 if (event->mRequiresSystemReady && !mSystemReady) {
720 event->mWaitStatus = false;
721 mPendingConfigEvents.add(event);
722 return status;
723 }
Eric Laurent10351942014-05-08 18:49:52 -0700724 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700725 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800726 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700727 mLock.unlock();
728 {
729 Mutex::Autolock _l(event->mLock);
730 while (event->mWaitStatus) {
731 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
732 event->mStatus = TIMED_OUT;
733 event->mWaitStatus = false;
734 }
735 }
736 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800737 }
Eric Laurent10351942014-05-08 18:49:52 -0700738 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800739 return status;
740}
741
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700742void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800743{
744 Mutex::Autolock _l(mLock);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700745 sendIoConfigEvent_l(event, pid);
Eric Laurent81784c32012-11-19 14:55:58 -0800746}
747
748// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700749void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800750{
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700751 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid);
Eric Laurent10351942014-05-08 18:49:52 -0700752 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800753}
754
Eric Laurent72e3f392015-05-20 14:43:50 -0700755void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio)
756{
757 Mutex::Autolock _l(mLock);
758 sendPrioConfigEvent_l(pid, tid, prio);
759}
760
Eric Laurent81784c32012-11-19 14:55:58 -0800761// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
762void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
763{
Eric Laurent10351942014-05-08 18:49:52 -0700764 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio);
765 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800766}
767
Eric Laurent10351942014-05-08 18:49:52 -0700768// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
769status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800770{
Andy Hung2ddee192015-12-18 17:34:44 -0800771 sp<ConfigEvent> configEvent;
772 AudioParameter param(keyValuePair);
773 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700774 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800775 setMasterMono_l(value != 0);
776 if (param.size() == 1) {
777 return NO_ERROR; // should be a solo parameter - we don't pass down
778 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700779 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800780 configEvent = new SetParameterConfigEvent(param.toString());
781 } else {
782 configEvent = new SetParameterConfigEvent(keyValuePair);
783 }
Eric Laurent10351942014-05-08 18:49:52 -0700784 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700785}
786
Eric Laurent1c333e22014-05-20 10:48:17 -0700787status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
788 const struct audio_patch *patch,
789 audio_patch_handle_t *handle)
790{
791 Mutex::Autolock _l(mLock);
792 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
793 status_t status = sendConfigEvent_l(configEvent);
794 if (status == NO_ERROR) {
795 CreateAudioPatchConfigEventData *data =
796 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
797 *handle = data->mHandle;
798 }
799 return status;
800}
801
802status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
803 const audio_patch_handle_t handle)
804{
805 Mutex::Autolock _l(mLock);
806 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
807 return sendConfigEvent_l(configEvent);
808}
809
810
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700811// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700812void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700813{
Eric Laurent10351942014-05-08 18:49:52 -0700814 bool configChanged = false;
815
Eric Laurent81784c32012-11-19 14:55:58 -0800816 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700817 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700818 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800819 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700820 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700821 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700822 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
823 // FIXME Need to understand why this has to be done asynchronously
824 int err = requestPriority(data->mPid, data->mTid, data->mPrio,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700825 true /*asynchronous*/);
826 if (err != 0) {
827 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700828 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700829 }
830 } break;
831 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700832 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700833 ioConfigChanged(data->mEvent, data->mPid);
Eric Laurent10351942014-05-08 18:49:52 -0700834 } break;
835 case CFG_EVENT_SET_PARAMETER: {
836 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
837 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
838 configChanged = true;
Glenn Kastend5418eb2013-08-14 13:11:06 -0700839 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700840 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700841 case CFG_EVENT_CREATE_AUDIO_PATCH: {
842 CreateAudioPatchConfigEventData *data =
843 (CreateAudioPatchConfigEventData *)event->mData.get();
844 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
845 } break;
846 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
847 ReleaseAudioPatchConfigEventData *data =
848 (ReleaseAudioPatchConfigEventData *)event->mData.get();
849 event->mStatus = releaseAudioPatch_l(data->mHandle);
850 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700851 default:
Eric Laurent10351942014-05-08 18:49:52 -0700852 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700853 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800854 }
Eric Laurent10351942014-05-08 18:49:52 -0700855 {
856 Mutex::Autolock _l(event->mLock);
857 if (event->mWaitStatus) {
858 event->mWaitStatus = false;
859 event->mCond.signal();
860 }
861 }
862 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
863 }
864
865 if (configChanged) {
866 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800867 }
Eric Laurent81784c32012-11-19 14:55:58 -0800868}
869
Marco Nelissenb2208842014-02-07 14:00:50 -0800870String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
871 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700872 const audio_channel_representation_t representation =
873 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700874
875 switch (representation) {
876 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
877 if (output) {
878 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
879 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
880 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
881 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
882 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
883 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
884 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
885 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
886 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
887 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
888 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
889 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
890 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
891 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
892 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
893 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
894 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
895 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
896 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
897 } else {
898 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
899 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
900 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
901 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
902 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
903 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
904 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
905 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
906 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
907 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
908 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
909 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
910 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
911 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
912 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
913 }
914 const int len = s.length();
915 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -0700916 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -0700917 s.unlockBuffer(len - 2); // remove trailing ", "
918 }
919 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800920 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700921 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
922 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
923 return s;
924 default:
925 s.appendFormat("unknown mask, representation:%d bits:%#x",
926 representation, audio_channel_mask_get_bits(mask));
927 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800928 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800929}
930
Glenn Kasten0f11b512014-01-31 16:18:54 -0800931void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800932{
933 const size_t SIZE = 256;
934 char buffer[SIZE];
935 String8 result;
936
937 bool locked = AudioFlinger::dumpTryLock(mLock);
938 if (!locked) {
Glenn Kasten97b7b752014-09-28 13:04:24 -0700939 dprintf(fd, "thread %p may be deadlocked\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -0800940 }
941
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800942 dprintf(fd, " Thread name: %s\n", mThreadName);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700943 dprintf(fd, " I/O handle: %d\n", mId);
944 dprintf(fd, " TID: %d\n", getTid());
945 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700946 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700947 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700948 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat));
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700949 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700950 dprintf(fd, " Channel count: %u\n", mChannelCount);
951 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800952 channelMaskToString(mChannelMask, mType != RECORD).string());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700953 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat));
954 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700955 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800956 size_t numConfig = mConfigEvents.size();
957 if (numConfig) {
958 for (size_t i = 0; i < numConfig; i++) {
959 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700960 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800961 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700962 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800963 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700964 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800965 }
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800966 dprintf(fd, " Output device: %#x (%s)\n", mOutDevice, devicesToString(mOutDevice).string());
967 dprintf(fd, " Input device: %#x (%s)\n", mInDevice, devicesToString(mInDevice).string());
968 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, sourceToString(mAudioSource));
Eric Laurent81784c32012-11-19 14:55:58 -0800969
970 if (locked) {
971 mLock.unlock();
972 }
973}
974
975void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
976{
977 const size_t SIZE = 256;
978 char buffer[SIZE];
979 String8 result;
980
Marco Nelissenb2208842014-02-07 14:00:50 -0800981 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000982 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800983 write(fd, buffer, strlen(buffer));
984
Marco Nelissenb2208842014-02-07 14:00:50 -0800985 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800986 sp<EffectChain> chain = mEffectChains[i];
987 if (chain != 0) {
988 chain->dump(fd, args);
989 }
990 }
991}
992
Marco Nelissene14a5d62013-10-03 08:51:24 -0700993void AudioFlinger::ThreadBase::acquireWakeLock(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800994{
995 Mutex::Autolock _l(mLock);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700996 acquireWakeLock_l(uid);
Eric Laurent81784c32012-11-19 14:55:58 -0800997}
998
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100999String16 AudioFlinger::ThreadBase::getWakeLockTag()
1000{
1001 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -08001002 case MIXER:
1003 return String16("AudioMix");
1004 case DIRECT:
1005 return String16("AudioDirectOut");
1006 case DUPLICATING:
1007 return String16("AudioDup");
1008 case RECORD:
1009 return String16("AudioIn");
1010 case OFFLOAD:
1011 return String16("AudioOffload");
1012 default:
1013 ALOG_ASSERT(false);
1014 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001015 }
1016}
1017
Marco Nelissene14a5d62013-10-03 08:51:24 -07001018void AudioFlinger::ThreadBase::acquireWakeLock_l(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -08001019{
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001020 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001021 if (mPowerManager != 0) {
1022 sp<IBinder> binder = new BBinder();
Marco Nelissene14a5d62013-10-03 08:51:24 -07001023 status_t status;
1024 if (uid >= 0) {
Eric Laurent547789d2013-10-04 11:46:55 -07001025 status = mPowerManager->acquireWakeLockWithUid(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -07001026 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001027 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -07001028 String16("audioserver"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -07001029 uid,
1030 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -07001031 } else {
Eric Laurent547789d2013-10-04 11:46:55 -07001032 status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -07001033 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001034 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -07001035 String16("audioserver"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -07001036 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -07001037 }
Eric Laurent81784c32012-11-19 14:55:58 -08001038 if (status == NO_ERROR) {
1039 mWakeLockToken = binder;
1040 }
Glenn Kastend7dca052015-03-05 16:05:54 -08001041 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -08001042 }
Wei Jia3f273d12015-11-24 09:06:49 -08001043
1044 if (!mNotifiedBatteryStart) {
1045 BatteryNotifier::getInstance().noteStartAudio();
1046 mNotifiedBatteryStart = true;
1047 }
Andy Hung3f0c9022016-01-15 17:49:46 -08001048 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -08001049 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
1050 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -08001051}
1052
1053void AudioFlinger::ThreadBase::releaseWakeLock()
1054{
1055 Mutex::Autolock _l(mLock);
1056 releaseWakeLock_l();
1057}
1058
1059void AudioFlinger::ThreadBase::releaseWakeLock_l()
1060{
Andy Hung3f0c9022016-01-15 17:49:46 -08001061 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -08001062 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001063 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001064 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -07001065 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
1066 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -08001067 }
1068 mWakeLockToken.clear();
1069 }
Wei Jia3f273d12015-11-24 09:06:49 -08001070
1071 if (mNotifiedBatteryStart) {
1072 BatteryNotifier::getInstance().noteStopAudio();
1073 mNotifiedBatteryStart = false;
1074 }
Eric Laurent81784c32012-11-19 14:55:58 -08001075}
1076
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001077void AudioFlinger::ThreadBase::updateWakeLockUids(const SortedVector<int> &uids) {
1078 Mutex::Autolock _l(mLock);
1079 updateWakeLockUids_l(uids);
1080}
1081
1082void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -07001083 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001084 // use checkService() to avoid blocking if power service is not up yet
1085 sp<IBinder> binder =
1086 defaultServiceManager()->checkService(String16("power"));
1087 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001088 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001089 } else {
1090 mPowerManager = interface_cast<IPowerManager>(binder);
1091 binder->linkToDeath(mDeathRecipient);
1092 }
1093 }
1094}
1095
1096void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<int> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001097 getPowerManager_l();
Andy Hung438e7572015-12-14 15:51:17 -08001098 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
1099 if (mSystemReady) {
1100 ALOGE("no wake lock to update, but system ready!");
1101 } else {
1102 ALOGW("no wake lock to update, system not ready yet");
1103 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001104 return;
1105 }
1106 if (mPowerManager != 0) {
1107 sp<IBinder> binder = new BBinder();
1108 status_t status;
Glenn Kasten3abc2de2014-09-05 16:45:52 -07001109 status = mPowerManager->updateWakeLockUids(mWakeLockToken, uids.size(), uids.array(),
1110 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent4d231dc2016-03-11 18:38:23 -08001111 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001112 }
1113}
1114
Eric Laurent81784c32012-11-19 14:55:58 -08001115void AudioFlinger::ThreadBase::clearPowerManager()
1116{
1117 Mutex::Autolock _l(mLock);
1118 releaseWakeLock_l();
1119 mPowerManager.clear();
1120}
1121
Glenn Kasten0f11b512014-01-31 16:18:54 -08001122void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001123{
1124 sp<ThreadBase> thread = mThread.promote();
1125 if (thread != 0) {
1126 thread->clearPowerManager();
1127 }
1128 ALOGW("power manager service died !!!");
1129}
1130
1131void AudioFlinger::ThreadBase::setEffectSuspended(
Glenn Kastend848eb42016-03-08 13:42:11 -08001132 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001133{
1134 Mutex::Autolock _l(mLock);
1135 setEffectSuspended_l(type, suspend, sessionId);
1136}
1137
1138void AudioFlinger::ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001139 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001140{
1141 sp<EffectChain> chain = getEffectChain_l(sessionId);
1142 if (chain != 0) {
1143 if (type != NULL) {
1144 chain->setEffectSuspended_l(type, suspend);
1145 } else {
1146 chain->setEffectSuspendedAll_l(suspend);
1147 }
1148 }
1149
1150 updateSuspendedSessions_l(type, suspend, sessionId);
1151}
1152
1153void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1154{
1155 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1156 if (index < 0) {
1157 return;
1158 }
1159
1160 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1161 mSuspendedSessions.valueAt(index);
1162
1163 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001164 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001165 for (int j = 0; j < desc->mRefCount; j++) {
1166 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1167 chain->setEffectSuspendedAll_l(true);
1168 } else {
1169 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1170 desc->mType.timeLow);
1171 chain->setEffectSuspended_l(&desc->mType, true);
1172 }
1173 }
1174 }
1175}
1176
1177void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1178 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001179 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001180{
1181 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1182
1183 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1184
1185 if (suspend) {
1186 if (index >= 0) {
1187 sessionEffects = mSuspendedSessions.valueAt(index);
1188 } else {
1189 mSuspendedSessions.add(sessionId, sessionEffects);
1190 }
1191 } else {
1192 if (index < 0) {
1193 return;
1194 }
1195 sessionEffects = mSuspendedSessions.valueAt(index);
1196 }
1197
1198
1199 int key = EffectChain::kKeyForSuspendAll;
1200 if (type != NULL) {
1201 key = type->timeLow;
1202 }
1203 index = sessionEffects.indexOfKey(key);
1204
1205 sp<SuspendedSessionDesc> desc;
1206 if (suspend) {
1207 if (index >= 0) {
1208 desc = sessionEffects.valueAt(index);
1209 } else {
1210 desc = new SuspendedSessionDesc();
1211 if (type != NULL) {
1212 desc->mType = *type;
1213 }
1214 sessionEffects.add(key, desc);
1215 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1216 }
1217 desc->mRefCount++;
1218 } else {
1219 if (index < 0) {
1220 return;
1221 }
1222 desc = sessionEffects.valueAt(index);
1223 if (--desc->mRefCount == 0) {
1224 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1225 sessionEffects.removeItemsAt(index);
1226 if (sessionEffects.isEmpty()) {
1227 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1228 sessionId);
1229 mSuspendedSessions.removeItem(sessionId);
1230 }
1231 }
1232 }
1233 if (!sessionEffects.isEmpty()) {
1234 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1235 }
1236}
1237
1238void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1239 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001240 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001241{
1242 Mutex::Autolock _l(mLock);
1243 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1244}
1245
1246void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1247 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001248 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001249{
1250 if (mType != RECORD) {
1251 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1252 // another session. This gives the priority to well behaved effect control panels
1253 // and applications not using global effects.
1254 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1255 // global effects
1256 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1257 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1258 }
1259 }
1260
1261 sp<EffectChain> chain = getEffectChain_l(sessionId);
1262 if (chain != 0) {
1263 chain->checkSuspendOnEffectEnabled(effect, enabled);
1264 }
1265}
1266
Eric Laurent4c415062016-06-17 16:14:16 -07001267// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1268status_t AudioFlinger::RecordThread::checkEffectCompatibility_l(
1269 const effect_descriptor_t *desc, audio_session_t sessionId)
1270{
1271 // No global effect sessions on record threads
1272 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1273 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1274 desc->name, mThreadName);
1275 return BAD_VALUE;
1276 }
1277 // only pre processing effects on record thread
1278 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1279 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1280 desc->name, mThreadName);
1281 return BAD_VALUE;
1282 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001283
1284 // always allow effects without processing load or latency
1285 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1286 return NO_ERROR;
1287 }
1288
Eric Laurent4c415062016-06-17 16:14:16 -07001289 audio_input_flags_t flags = mInput->flags;
1290 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1291 if (flags & AUDIO_INPUT_FLAG_RAW) {
1292 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1293 desc->name, mThreadName);
1294 return BAD_VALUE;
1295 }
1296 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1297 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1298 desc->name, mThreadName);
1299 return BAD_VALUE;
1300 }
1301 }
1302 return NO_ERROR;
1303}
1304
1305// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1306status_t AudioFlinger::PlaybackThread::checkEffectCompatibility_l(
1307 const effect_descriptor_t *desc, audio_session_t sessionId)
1308{
1309 // no preprocessing on playback threads
1310 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
1311 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback"
1312 " thread %s", desc->name, mThreadName);
1313 return BAD_VALUE;
1314 }
1315
1316 switch (mType) {
1317 case MIXER: {
1318 // Reject any effect on mixer multichannel sinks.
1319 // TODO: fix both format and multichannel issues with effects.
1320 if (mChannelCount != FCC_2) {
1321 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d) on MIXER"
1322 " thread %s", desc->name, mChannelCount, mThreadName);
1323 return BAD_VALUE;
1324 }
1325 audio_output_flags_t flags = mOutput->flags;
1326 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1327 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1328 // global effects are applied only to non fast tracks if they are SW
1329 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1330 break;
1331 }
1332 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1333 // only post processing on output stage session
1334 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1335 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1336 " on output stage session", desc->name);
1337 return BAD_VALUE;
1338 }
1339 } else {
1340 // no restriction on effects applied on non fast tracks
1341 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1342 break;
1343 }
1344 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001345
1346 // always allow effects without processing load or latency
1347 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1348 break;
1349 }
Eric Laurent4c415062016-06-17 16:14:16 -07001350 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
1351 ALOGW("checkEffectCompatibility_l(): effect %s on playback thread in raw mode",
1352 desc->name);
1353 return BAD_VALUE;
1354 }
1355 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1356 ALOGW("checkEffectCompatibility_l(): non HW effect %s on playback thread"
1357 " in fast mode", desc->name);
1358 return BAD_VALUE;
1359 }
1360 }
1361 } break;
1362 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001363 // nothing actionable on offload threads, if the effect:
1364 // - is offloadable: the effect can be created
1365 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1366 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001367 break;
1368 case DIRECT:
1369 // Reject any effect on Direct output threads for now, since the format of
1370 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1371 ALOGW("checkEffectCompatibility_l(): effect %s on DIRECT output thread %s",
1372 desc->name, mThreadName);
1373 return BAD_VALUE;
1374 case DUPLICATING:
1375 // Reject any effect on mixer multichannel sinks.
1376 // TODO: fix both format and multichannel issues with effects.
1377 if (mChannelCount != FCC_2) {
1378 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d)"
1379 " on DUPLICATING thread %s", desc->name, mChannelCount, mThreadName);
1380 return BAD_VALUE;
1381 }
1382 if ((sessionId == AUDIO_SESSION_OUTPUT_STAGE) || (sessionId == AUDIO_SESSION_OUTPUT_MIX)) {
1383 ALOGW("checkEffectCompatibility_l(): global effect %s on DUPLICATING"
1384 " thread %s", desc->name, mThreadName);
1385 return BAD_VALUE;
1386 }
1387 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
1388 ALOGW("checkEffectCompatibility_l(): post processing effect %s on"
1389 " DUPLICATING thread %s", desc->name, mThreadName);
1390 return BAD_VALUE;
1391 }
1392 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1393 ALOGW("checkEffectCompatibility_l(): HW tunneled effect %s on"
1394 " DUPLICATING thread %s", desc->name, mThreadName);
1395 return BAD_VALUE;
1396 }
1397 break;
1398 default:
1399 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1400 }
1401
1402 return NO_ERROR;
1403}
1404
Eric Laurent81784c32012-11-19 14:55:58 -08001405// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1406sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1407 const sp<AudioFlinger::Client>& client,
1408 const sp<IEffectClient>& effectClient,
1409 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001410 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001411 effect_descriptor_t *desc,
1412 int *enabled,
Glenn Kasten9156ef32013-08-06 15:39:08 -07001413 status_t *status)
Eric Laurent81784c32012-11-19 14:55:58 -08001414{
1415 sp<EffectModule> effect;
1416 sp<EffectHandle> handle;
1417 status_t lStatus;
1418 sp<EffectChain> chain;
1419 bool chainCreated = false;
1420 bool effectCreated = false;
1421 bool effectRegistered = false;
1422
1423 lStatus = initCheck();
1424 if (lStatus != NO_ERROR) {
1425 ALOGW("createEffect_l() Audio driver not initialized.");
1426 goto Exit;
1427 }
1428
Eric Laurent81784c32012-11-19 14:55:58 -08001429 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1430
1431 { // scope for mLock
1432 Mutex::Autolock _l(mLock);
1433
Eric Laurent4c415062016-06-17 16:14:16 -07001434 lStatus = checkEffectCompatibility_l(desc, sessionId);
1435 if (lStatus != NO_ERROR) {
1436 goto Exit;
1437 }
1438
Eric Laurent81784c32012-11-19 14:55:58 -08001439 // check for existing effect chain with the requested audio session
1440 chain = getEffectChain_l(sessionId);
1441 if (chain == 0) {
1442 // create a new chain for this session
1443 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1444 chain = new EffectChain(this, sessionId);
1445 addEffectChain_l(chain);
1446 chain->setStrategy(getStrategyForSession_l(sessionId));
1447 chainCreated = true;
1448 } else {
1449 effect = chain->getEffectFromDesc_l(desc);
1450 }
1451
1452 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1453
1454 if (effect == 0) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08001455 audio_unique_id_t id = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001456 // Check CPU and memory usage
1457 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
1458 if (lStatus != NO_ERROR) {
1459 goto Exit;
1460 }
1461 effectRegistered = true;
1462 // create a new effect module if none present in the chain
1463 effect = new EffectModule(this, chain, desc, id, sessionId);
1464 lStatus = effect->status();
1465 if (lStatus != NO_ERROR) {
1466 goto Exit;
1467 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001468 effect->setOffloaded(mType == OFFLOAD, mId);
1469
Eric Laurent81784c32012-11-19 14:55:58 -08001470 lStatus = chain->addEffect_l(effect);
1471 if (lStatus != NO_ERROR) {
1472 goto Exit;
1473 }
1474 effectCreated = true;
1475
1476 effect->setDevice(mOutDevice);
1477 effect->setDevice(mInDevice);
1478 effect->setMode(mAudioFlinger->getMode());
1479 effect->setAudioSource(mAudioSource);
1480 }
1481 // create effect handle and connect it to effect module
1482 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001483 lStatus = handle->initCheck();
1484 if (lStatus == OK) {
1485 lStatus = effect->addHandle(handle.get());
1486 }
Eric Laurent81784c32012-11-19 14:55:58 -08001487 if (enabled != NULL) {
1488 *enabled = (int)effect->isEnabled();
1489 }
1490 }
1491
1492Exit:
1493 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1494 Mutex::Autolock _l(mLock);
1495 if (effectCreated) {
1496 chain->removeEffect_l(effect);
1497 }
1498 if (effectRegistered) {
1499 AudioSystem::unregisterEffect(effect->id());
1500 }
1501 if (chainCreated) {
1502 removeEffectChain_l(chain);
1503 }
1504 handle.clear();
1505 }
1506
Glenn Kasten9156ef32013-08-06 15:39:08 -07001507 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001508 return handle;
1509}
1510
Glenn Kastend848eb42016-03-08 13:42:11 -08001511sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1512 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001513{
1514 Mutex::Autolock _l(mLock);
1515 return getEffect_l(sessionId, effectId);
1516}
1517
Glenn Kastend848eb42016-03-08 13:42:11 -08001518sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1519 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001520{
1521 sp<EffectChain> chain = getEffectChain_l(sessionId);
1522 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1523}
1524
1525// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1526// PlaybackThread::mLock held
1527status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1528{
1529 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001530 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001531 sp<EffectChain> chain = getEffectChain_l(sessionId);
1532 bool chainCreated = false;
1533
Eric Laurent5baf2af2013-09-12 17:37:00 -07001534 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1535 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1536 this, effect->desc().name, effect->desc().flags);
1537
Eric Laurent81784c32012-11-19 14:55:58 -08001538 if (chain == 0) {
1539 // create a new chain for this session
1540 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1541 chain = new EffectChain(this, sessionId);
1542 addEffectChain_l(chain);
1543 chain->setStrategy(getStrategyForSession_l(sessionId));
1544 chainCreated = true;
1545 }
1546 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1547
1548 if (chain->getEffectFromId_l(effect->id()) != 0) {
1549 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1550 this, effect->desc().name, chain.get());
1551 return BAD_VALUE;
1552 }
1553
Eric Laurent5baf2af2013-09-12 17:37:00 -07001554 effect->setOffloaded(mType == OFFLOAD, mId);
1555
Eric Laurent81784c32012-11-19 14:55:58 -08001556 status_t status = chain->addEffect_l(effect);
1557 if (status != NO_ERROR) {
1558 if (chainCreated) {
1559 removeEffectChain_l(chain);
1560 }
1561 return status;
1562 }
1563
1564 effect->setDevice(mOutDevice);
1565 effect->setDevice(mInDevice);
1566 effect->setMode(mAudioFlinger->getMode());
1567 effect->setAudioSource(mAudioSource);
1568 return NO_ERROR;
1569}
1570
1571void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
1572
1573 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
1574 effect_descriptor_t desc = effect->desc();
1575 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1576 detachAuxEffect_l(effect->id());
1577 }
1578
1579 sp<EffectChain> chain = effect->chain().promote();
1580 if (chain != 0) {
1581 // remove effect chain if removing last effect
1582 if (chain->removeEffect_l(effect) == 0) {
1583 removeEffectChain_l(chain);
1584 }
1585 } else {
1586 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1587 }
1588}
1589
1590void AudioFlinger::ThreadBase::lockEffectChains_l(
1591 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1592{
1593 effectChains = mEffectChains;
1594 for (size_t i = 0; i < mEffectChains.size(); i++) {
1595 mEffectChains[i]->lock();
1596 }
1597}
1598
1599void AudioFlinger::ThreadBase::unlockEffectChains(
1600 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1601{
1602 for (size_t i = 0; i < effectChains.size(); i++) {
1603 effectChains[i]->unlock();
1604 }
1605}
1606
Glenn Kastend848eb42016-03-08 13:42:11 -08001607sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001608{
1609 Mutex::Autolock _l(mLock);
1610 return getEffectChain_l(sessionId);
1611}
1612
Glenn Kastend848eb42016-03-08 13:42:11 -08001613sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1614 const
Eric Laurent81784c32012-11-19 14:55:58 -08001615{
1616 size_t size = mEffectChains.size();
1617 for (size_t i = 0; i < size; i++) {
1618 if (mEffectChains[i]->sessionId() == sessionId) {
1619 return mEffectChains[i];
1620 }
1621 }
1622 return 0;
1623}
1624
1625void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1626{
1627 Mutex::Autolock _l(mLock);
1628 size_t size = mEffectChains.size();
1629 for (size_t i = 0; i < size; i++) {
1630 mEffectChains[i]->setMode_l(mode);
1631 }
1632}
1633
Eric Laurent83b88082014-06-20 18:31:16 -07001634void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1635{
1636 config->type = AUDIO_PORT_TYPE_MIX;
1637 config->ext.mix.handle = mId;
1638 config->sample_rate = mSampleRate;
1639 config->format = mFormat;
1640 config->channel_mask = mChannelMask;
1641 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1642 AUDIO_PORT_CONFIG_FORMAT;
1643}
1644
Eric Laurent72e3f392015-05-20 14:43:50 -07001645void AudioFlinger::ThreadBase::systemReady()
1646{
1647 Mutex::Autolock _l(mLock);
1648 if (mSystemReady) {
1649 return;
1650 }
1651 mSystemReady = true;
1652
1653 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1654 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1655 }
1656 mPendingConfigEvents.clear();
1657}
1658
Eric Laurent83b88082014-06-20 18:31:16 -07001659
Eric Laurent81784c32012-11-19 14:55:58 -08001660// ----------------------------------------------------------------------------
1661// Playback
1662// ----------------------------------------------------------------------------
1663
1664AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1665 AudioStreamOut* output,
1666 audio_io_handle_t id,
1667 audio_devices_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07001668 type_t type,
Eric Laurente93cc032016-05-05 10:15:10 -07001669 bool systemReady)
Eric Laurent72e3f392015-05-20 14:43:50 -07001670 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001671 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001672 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001673 mMixerBuffer(NULL),
1674 mMixerBufferSize(0),
1675 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1676 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001677 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001678 mEffectBuffer(NULL),
1679 mEffectBufferSize(0),
1680 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1681 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001682 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001683 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07001684 mSuspendedFrames(0),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001685 mActiveTracksGeneration(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001686 // mStreamTypes[] initialized in constructor body
1687 mOutput(output),
Andy Hung69488c42016-05-16 18:43:33 -07001688 mLastWriteTime(-1), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001689 mMixerStatus(MIXER_IDLE),
1690 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001691 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001692 mBytesRemaining(0),
1693 mCurrentWriteLength(0),
1694 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001695 mWriteAckSequence(0),
1696 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001697 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001698 mScreenState(AudioFlinger::mScreenState),
1699 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001700 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Andy Hunge10393e2015-06-12 13:59:33 -07001701 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001702{
Glenn Kastend7dca052015-03-05 16:05:54 -08001703 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1704 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001705
1706 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1707 // it would be safer to explicitly pass initial masterVolume/masterMute as
1708 // parameter.
1709 //
1710 // If the HAL we are using has support for master volume or master mute,
1711 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1712 // and the mute set to false).
1713 mMasterVolume = audioFlinger->masterVolume_l();
1714 mMasterMute = audioFlinger->masterMute_l();
1715 if (mOutput && mOutput->audioHwDev) {
1716 if (mOutput->audioHwDev->canSetMasterVolume()) {
1717 mMasterVolume = 1.0;
1718 }
1719
1720 if (mOutput->audioHwDev->canSetMasterMute()) {
1721 mMasterMute = false;
1722 }
1723 }
1724
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001725 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001726
Eric Laurent223fd5c2014-11-11 13:43:36 -08001727 // ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001728 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001729 stream = (audio_stream_type_t) (stream + 1)) {
1730 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1731 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1732 }
Eric Laurent81784c32012-11-19 14:55:58 -08001733}
1734
1735AudioFlinger::PlaybackThread::~PlaybackThread()
1736{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001737 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001738 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001739 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001740 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001741}
1742
1743void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1744{
1745 dumpInternals(fd, args);
1746 dumpTracks(fd, args);
1747 dumpEffectChains(fd, args);
1748}
1749
Glenn Kasten0f11b512014-01-31 16:18:54 -08001750void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001751{
1752 const size_t SIZE = 256;
1753 char buffer[SIZE];
1754 String8 result;
1755
Marco Nelissenb2208842014-02-07 14:00:50 -08001756 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001757 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1758 const stream_type_t *st = &mStreamTypes[i];
1759 if (i > 0) {
1760 result.appendFormat(", ");
1761 }
1762 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1763 if (st->mute) {
1764 result.append("M");
1765 }
1766 }
1767 result.append("\n");
1768 write(fd, result.string(), result.length());
1769 result.clear();
1770
Eric Laurent81784c32012-11-19 14:55:58 -08001771 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1772 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001773 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001774 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001775
1776 size_t numtracks = mTracks.size();
1777 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001778 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001779 size_t numactiveseen = 0;
1780 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001781 dprintf(fd, " of which %zu are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001782 Track::appendDumpHeader(result);
1783 for (size_t i = 0; i < numtracks; ++i) {
1784 sp<Track> track = mTracks[i];
1785 if (track != 0) {
1786 bool active = mActiveTracks.indexOf(track) >= 0;
1787 if (active) {
1788 numactiveseen++;
1789 }
1790 track->dump(buffer, SIZE, active);
1791 result.append(buffer);
1792 }
1793 }
1794 } else {
1795 result.append("\n");
1796 }
1797 if (numactiveseen != numactive) {
1798 // some tracks in the active list were not in the tracks list
1799 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1800 " not in the track list\n");
1801 result.append(buffer);
1802 Track::appendDumpHeader(result);
1803 for (size_t i = 0; i < numactive; ++i) {
1804 sp<Track> track = mActiveTracks[i].promote();
1805 if (track != 0 && mTracks.indexOf(track) < 0) {
1806 track->dump(buffer, SIZE, true);
1807 result.append(buffer);
1808 }
1809 }
1810 }
1811
1812 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001813}
1814
1815void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1816{
Glenn Kasten97b7b752014-09-28 13:04:24 -07001817 dprintf(fd, "\nOutput thread %p type %d (%s):\n", this, type(), threadTypeToString(type()));
Glenn Kasten44182c22015-03-05 17:12:23 -08001818
1819 dumpBase(fd, args);
1820
Elliott Hughes87cebad2014-05-22 10:14:43 -07001821 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001822 dprintf(fd, " Last write occurred (msecs): %llu\n",
1823 (unsigned long long) ns2ms(systemTime() - mLastWriteTime));
Elliott Hughes87cebad2014-05-22 10:14:43 -07001824 dprintf(fd, " Total writes: %d\n", mNumWrites);
1825 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1826 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1827 dprintf(fd, " Suspend count: %d\n", mSuspended);
1828 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1829 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1830 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1831 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08001832 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001833 AudioStreamOut *output = mOutput;
1834 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
1835 String8 flagsAsString = outputFlagsToString(flags);
1836 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n", output, flags, flagsAsString.string());
Andy Hungb54c8542016-09-21 12:55:15 -07001837 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
1838 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
1839 if (mPipeSink.get() != nullptr) {
1840 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
1841 }
1842 if (output != nullptr) {
1843 dprintf(fd, " Hal stream dump:\n");
1844 (void)output->stream->dump(fd);
1845 }
Eric Laurent81784c32012-11-19 14:55:58 -08001846}
1847
1848// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001849
1850void AudioFlinger::PlaybackThread::onFirstRef()
1851{
Glenn Kastend7dca052015-03-05 16:05:54 -08001852 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001853}
1854
1855// ThreadBase virtuals
1856void AudioFlinger::PlaybackThread::preExit()
1857{
1858 ALOGV(" preExit()");
1859 // FIXME this is using hard-coded strings but in the future, this functionality will be
1860 // converted to use audio HAL extensions required to support tunneling
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001861 status_t result = mOutput->stream->setParameters(String8("exiting=1"));
1862 ALOGE_IF(result != OK, "Error when setting parameters on exit: %d", result);
Eric Laurent81784c32012-11-19 14:55:58 -08001863}
1864
1865// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1866sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1867 const sp<AudioFlinger::Client>& client,
1868 audio_stream_type_t streamType,
1869 uint32_t sampleRate,
1870 audio_format_t format,
1871 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001872 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001873 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08001874 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07001875 audio_output_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08001876 pid_t tid,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001877 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -08001878 status_t *status)
1879{
Glenn Kasten74935e42013-12-19 08:56:45 -08001880 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001881 sp<Track> track;
1882 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07001883 audio_output_flags_t outputFlags = mOutput->flags;
1884
1885 // special case for FAST flag considered OK if fast mixer is present
1886 if (hasFastMixer()) {
1887 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
1888 }
1889
1890 // Check if requested flags are compatible with output stream flags
1891 if ((*flags & outputFlags) != *flags) {
1892 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
1893 *flags, outputFlags);
1894 *flags = (audio_output_flags_t)(*flags & outputFlags);
1895 }
Eric Laurent81784c32012-11-19 14:55:58 -08001896
Eric Laurent81784c32012-11-19 14:55:58 -08001897 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07001898 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08001899 if (
Eric Laurent81784c32012-11-19 14:55:58 -08001900 // PCM data
1901 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001902 // TODO: extract as a data library function that checks that a computationally
1903 // expensive downmixer is not required: isFastOutputChannelConversion()
Andy Hung9a592762014-07-21 21:56:01 -07001904 (channelMask == mChannelMask ||
Andy Hung1f439e12015-05-19 12:57:41 -07001905 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1906 (channelMask == AUDIO_CHANNEL_OUT_MONO
1907 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001908 // hardware sample rate
1909 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001910 // normal mixer has an associated fast mixer
1911 hasFastMixer() &&
1912 // there are sufficient fast track slots available
1913 (mFastTrackAvailMask != 0)
1914 // FIXME test that MixerThread for this fast track has a capable output HAL
1915 // FIXME add a permission test also?
1916 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07001917 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
1918 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001919 // read the fast track multiplier property the first time it is needed
1920 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1921 if (ok != 0) {
1922 ALOGE("%s pthread_once failed: %d", __func__, ok);
1923 }
Andy Hunge0a269a2016-03-23 15:13:42 -07001924 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08001925 }
Eric Laurent4c415062016-06-17 16:14:16 -07001926
1927 // check compatibility with audio effects.
1928 { // scope for mLock
1929 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07001930 for (audio_session_t session : {
1931 AUDIO_SESSION_OUTPUT_STAGE,
1932 AUDIO_SESSION_OUTPUT_MIX,
1933 sessionId,
1934 }) {
1935 sp<EffectChain> chain = getEffectChain_l(session);
1936 if (chain.get() != nullptr) {
1937 audio_output_flags_t old = *flags;
1938 chain->checkOutputFlagCompatibility(flags);
1939 if (old != *flags) {
1940 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
1941 (int)session, (int)old, (int)*flags);
1942 }
Eric Laurent4c415062016-06-17 16:14:16 -07001943 }
1944 }
1945 }
Eric Laurent122f7e72016-06-29 11:53:29 -07001946 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07001947 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
1948 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08001949 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001950 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
1951 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07001952 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001953 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08001954 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001955 audio_is_linear_pcm(format),
1956 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07001957 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08001958 }
1959 }
1960 // For normal PCM streaming tracks, update minimum frame count.
1961 // For compatibility with AudioTrack calculation, buffer depth is forced
1962 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1963 // This is probably too conservative, but legacy application code may depend on it.
1964 // If you change this calculation, also review the start threshold which is related.
Eric Laurent05067782016-06-01 18:27:28 -07001965 if (!(*flags & AUDIO_OUTPUT_FLAG_FAST)
Phil Burkfdb3c072016-02-09 10:47:02 -08001966 && audio_has_proportional_frames(format) && sharedBuffer == 0) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001967 // this must match AudioTrack.cpp calculateMinFrameCount().
1968 // TODO: Move to a common library
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001969 uint32_t latencyMs = 0;
1970 lStatus = mOutput->stream->getLatency(&latencyMs);
1971 if (lStatus != OK) {
1972 ALOGE("Error when retrieving output stream latency: %d", lStatus);
1973 goto Exit;
1974 }
Eric Laurent81784c32012-11-19 14:55:58 -08001975 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1976 if (minBufCount < 2) {
1977 minBufCount = 2;
1978 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07001979 // For normal mixing tracks, if speed is > 1.0f (normal), AudioTrack
1980 // or the client should compute and pass in a larger buffer request.
Andy Hung0e48d252015-01-26 11:43:15 -08001981 size_t minFrameCount =
Andy Hung8edb8dc2015-03-26 19:13:55 -07001982 minBufCount * sourceFramesNeededWithTimestretch(
1983 sampleRate, mNormalFrameCount,
1984 mSampleRate, AUDIO_TIMESTRETCH_SPEED_NORMAL /*speed*/);
Andy Hung0e48d252015-01-26 11:43:15 -08001985 if (frameCount < minFrameCount) { // including frameCount == 0
Eric Laurent81784c32012-11-19 14:55:58 -08001986 frameCount = minFrameCount;
1987 }
Eric Laurent81784c32012-11-19 14:55:58 -08001988 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001989 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001990
Glenn Kastenc3df8382014-03-13 15:05:25 -07001991 switch (mType) {
1992
1993 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08001994 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08001995 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001996 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1997 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001998 sampleRate, format, channelMask, mOutput, mFormat);
1999 lStatus = BAD_VALUE;
2000 goto Exit;
2001 }
2002 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002003 break;
2004
2005 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002006 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002007 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2008 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002009 sampleRate, format, channelMask, mOutput, mFormat);
2010 lStatus = BAD_VALUE;
2011 goto Exit;
2012 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002013 break;
2014
2015 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002016 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002017 ALOGE("createTrack_l() Bad parameter: format %#x \""
2018 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002019 format, mOutput, mFormat);
2020 lStatus = BAD_VALUE;
2021 goto Exit;
2022 }
Andy Hungcd044842014-08-07 11:04:34 -07002023 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002024 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2025 lStatus = BAD_VALUE;
2026 goto Exit;
2027 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002028 break;
2029
Eric Laurent81784c32012-11-19 14:55:58 -08002030 }
2031
2032 lStatus = initCheck();
2033 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002034 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002035 goto Exit;
2036 }
2037
2038 { // scope for mLock
2039 Mutex::Autolock _l(mLock);
2040
2041 // all tracks in same audio session must share the same routing strategy otherwise
2042 // conflicts will happen when tracks are moved from one output to another by audio policy
2043 // manager
2044 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
2045 for (size_t i = 0; i < mTracks.size(); ++i) {
2046 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002047 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002048 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
2049 if (sessionId == t->sessionId() && strategy != actual) {
2050 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2051 strategy, actual);
2052 lStatus = BAD_VALUE;
2053 goto Exit;
2054 }
2055 }
2056 }
2057
Glenn Kastend79072e2016-01-06 08:41:20 -08002058 track = new Track(this, client, streamType, sampleRate, format,
2059 channelMask, frameCount, NULL, sharedBuffer,
2060 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT);
Glenn Kasten03003332013-08-06 15:40:54 -07002061
Glenn Kasten03003332013-08-06 15:40:54 -07002062 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2063 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002064 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002065 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002066 goto Exit;
2067 }
2068 mTracks.add(track);
2069
2070 sp<EffectChain> chain = getEffectChain_l(sessionId);
2071 if (chain != 0) {
2072 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2073 track->setMainBuffer(chain->inBuffer());
2074 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
2075 chain->incTrackCnt();
2076 }
2077
Eric Laurent05067782016-06-01 18:27:28 -07002078 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002079 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2080 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2081 // so ask activity manager to do this on our behalf
2082 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
2083 }
2084 }
2085
2086 lStatus = NO_ERROR;
2087
2088Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002089 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002090 return track;
2091}
2092
2093uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2094{
2095 return latency;
2096}
2097
2098uint32_t AudioFlinger::PlaybackThread::latency() const
2099{
2100 Mutex::Autolock _l(mLock);
2101 return latency_l();
2102}
2103uint32_t AudioFlinger::PlaybackThread::latency_l() const
2104{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002105 uint32_t latency;
2106 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2107 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002108 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002109 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002110}
2111
2112void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2113{
2114 Mutex::Autolock _l(mLock);
2115 // Don't apply master volume in SW if our HAL can do it for us.
2116 if (mOutput && mOutput->audioHwDev &&
2117 mOutput->audioHwDev->canSetMasterVolume()) {
2118 mMasterVolume = 1.0;
2119 } else {
2120 mMasterVolume = value;
2121 }
2122}
2123
2124void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2125{
2126 Mutex::Autolock _l(mLock);
2127 // Don't apply master mute in SW if our HAL can do it for us.
2128 if (mOutput && mOutput->audioHwDev &&
2129 mOutput->audioHwDev->canSetMasterMute()) {
2130 mMasterMute = false;
2131 } else {
2132 mMasterMute = muted;
2133 }
2134}
2135
2136void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2137{
2138 Mutex::Autolock _l(mLock);
2139 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002140 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002141}
2142
2143void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2144{
2145 Mutex::Autolock _l(mLock);
2146 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002147 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002148}
2149
2150float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2151{
2152 Mutex::Autolock _l(mLock);
2153 return mStreamTypes[stream].volume;
2154}
2155
2156// addTrack_l() must be called with ThreadBase::mLock held
2157status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2158{
2159 status_t status = ALREADY_EXISTS;
2160
Eric Laurent81784c32012-11-19 14:55:58 -08002161 if (mActiveTracks.indexOf(track) < 0) {
2162 // the track is newly added, make sure it fills up all its
2163 // buffers before playing. This is to ensure the client will
2164 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002165 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002166 TrackBase::track_state state = track->mState;
2167 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002168 status = AudioSystem::startOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002169 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002170 mLock.lock();
2171 // abort track was stopped/paused while we released the lock
2172 if (state != track->mState) {
2173 if (status == NO_ERROR) {
2174 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002175 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002176 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002177 mLock.lock();
2178 }
2179 return INVALID_OPERATION;
2180 }
2181 // abort if start is rejected by audio policy manager
2182 if (status != NO_ERROR) {
2183 return PERMISSION_DENIED;
2184 }
2185#ifdef ADD_BATTERY_DATA
2186 // to track the speaker usage
2187 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2188#endif
2189 }
2190
Eric Laurent51716182016-02-29 18:00:56 -08002191 // set retry count for buffer fill
2192 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002193 if (track->isStopping_1()) {
2194 track->mRetryCount = kMaxTrackStopRetriesOffload;
2195 } else {
2196 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2197 }
2198 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002199 } else {
2200 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002201 track->mFillingUpStatus =
2202 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002203 }
2204
Eric Laurent81784c32012-11-19 14:55:58 -08002205 track->mResetDone = false;
2206 track->mPresentationCompleteFrames = 0;
2207 mActiveTracks.add(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002208 mWakeLockUids.add(track->uid());
2209 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07002210 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07002211 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2212 if (chain != 0) {
2213 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2214 track->sessionId());
2215 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002216 }
2217
2218 status = NO_ERROR;
2219 }
2220
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002221 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002222 return status;
2223}
2224
Eric Laurentbfb1b832013-01-07 09:53:42 -08002225bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002226{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002227 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002228 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002229 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2230 track->mState = TrackBase::STOPPED;
2231 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002232 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002233 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002234 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002235 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002236
2237 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002238}
2239
2240void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2241{
2242 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
2243 mTracks.remove(track);
2244 deleteTrackName_l(track->name());
2245 // redundant as track is about to be destroyed, for dumpsys only
2246 track->mName = -1;
2247 if (track->isFastTrack()) {
2248 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002249 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002250 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2251 mFastTrackAvailMask |= 1 << index;
2252 // redundant as track is about to be destroyed, for dumpsys only
2253 track->mFastIndex = -1;
2254 }
2255 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2256 if (chain != 0) {
2257 chain->decTrackCnt();
2258 }
2259}
2260
Eric Laurentede6c3b2013-09-19 14:37:46 -07002261void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002262{
2263 // Thread could be blocked waiting for async
2264 // so signal it to handle state changes immediately
2265 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
2266 // be lost so we also flag to prevent it blocking on mWaitWorkCV
2267 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002268 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002269}
2270
Eric Laurent81784c32012-11-19 14:55:58 -08002271String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2272{
Eric Laurent81784c32012-11-19 14:55:58 -08002273 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002274 String8 out_s8;
2275 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2276 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002277 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002278 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002279}
2280
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002281void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002282 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2283 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002284
Eric Laurent73e26b62015-04-27 16:55:58 -07002285 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002286
2287 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002288 case AUDIO_OUTPUT_OPENED:
2289 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002290 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002291 desc->mChannelMask = mChannelMask;
2292 desc->mSamplingRate = mSampleRate;
2293 desc->mFormat = mFormat;
2294 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002295 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002296 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002297 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002298 break;
2299
Eric Laurent73e26b62015-04-27 16:55:58 -07002300 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002301 default:
2302 break;
2303 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002304 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002305}
2306
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002307void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002308{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002309 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002310}
2311
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002312void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002313{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002314 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002315}
2316
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002317void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002318{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002319 mCallbackThread->setAsyncError();
2320}
2321
Eric Laurent3b4529e2013-09-05 18:09:19 -07002322void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002323{
2324 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002325 // reject out of sequence requests
2326 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2327 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002328 mWaitWorkCV.signal();
2329 }
2330}
2331
Eric Laurent3b4529e2013-09-05 18:09:19 -07002332void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002333{
2334 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002335 // reject out of sequence requests
2336 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
2337 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002338 mWaitWorkCV.signal();
2339 }
2340}
2341
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002342void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002343{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002344 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002345 mSampleRate = mOutput->getSampleRate();
2346 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002347 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002348 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002349 }
Andy Hung9a592762014-07-21 21:56:01 -07002350 if ((mType == MIXER || mType == DUPLICATING)
2351 && !isValidPcmSinkChannelMask(mChannelMask)) {
2352 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2353 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002354 }
Andy Hunge5412692014-05-16 11:25:07 -07002355 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002356
2357 // Get actual HAL format.
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002358 status_t result = mOutput->stream->getFormat(&mHALFormat);
2359 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002360 // Get format from the shim, which will be different than the HAL format
2361 // if playing compressed audio over HDMI passthrough.
2362 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002363 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002364 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002365 }
Andy Hung6146c082014-03-18 11:56:15 -07002366 if ((mType == MIXER || mType == DUPLICATING)
2367 && !isValidPcmSinkFormat(mFormat)) {
2368 LOG_FATAL("HAL format %#x not supported for mixed output",
2369 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002370 }
Phil Burk062e67a2015-02-11 13:40:50 -08002371 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002372 result = mOutput->stream->getBufferSize(&mBufferSize);
2373 LOG_ALWAYS_FATAL_IF(result != OK,
2374 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07002375 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002376 if (mFrameCount & 15) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002377 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002378 mFrameCount);
2379 }
2380
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002381 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
2382 if (mOutput->stream->setCallback(this) == OK) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002383 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002384 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002385 }
2386 }
2387
Eric Laurentd1f69b02014-12-15 14:33:13 -08002388 mHwSupportsPause = false;
2389 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002390 bool supportsPause = false, supportsResume = false;
2391 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
2392 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002393 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002394 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002395 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002396 } else if (supportsResume) {
2397 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08002398 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002399 }
2400 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002401 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2402 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2403 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002404
Andy Hungfbfc3952015-01-15 13:33:51 -08002405 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2406 // For best precision, we use float instead of the associated output
2407 // device format (typically PCM 16 bit).
2408
2409 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2410 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2411 mBufferSize = mFrameSize * mFrameCount;
2412
2413 // TODO: We currently use the associated output device channel mask and sample rate.
2414 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2415 // (if a valid mask) to avoid premature downmix.
2416 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2417 // instead of the output device sample rate to avoid loss of high frequency information.
2418 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2419 }
2420
Andy Hung09a50072014-02-27 14:30:47 -08002421 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002422 double multiplier = 1.0;
2423 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2424 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002425 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2426 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002427
Eric Laurent81784c32012-11-19 14:55:58 -08002428 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2429 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2430 maxNormalFrameCount = maxNormalFrameCount & ~15;
2431 if (maxNormalFrameCount < minNormalFrameCount) {
2432 maxNormalFrameCount = minNormalFrameCount;
2433 }
2434 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2435 if (multiplier <= 1.0) {
2436 multiplier = 1.0;
2437 } else if (multiplier <= 2.0) {
2438 if (2 * mFrameCount <= maxNormalFrameCount) {
2439 multiplier = 2.0;
2440 } else {
2441 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2442 }
2443 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002444 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002445 }
2446 }
2447 mNormalFrameCount = multiplier * mFrameCount;
2448 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002449 if (mType == MIXER || mType == DUPLICATING) {
2450 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2451 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002452 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002453 mNormalFrameCount);
2454
Andy Hung08fb1742015-05-31 23:22:10 -07002455 // Check if we want to throttle the processing to no more than 2x normal rate
2456 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002457 mThreadThrottleTimeMs = 0;
2458 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002459 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2460
Andy Hung010a1a12014-03-13 13:57:33 -07002461 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2462 // Originally this was int16_t[] array, need to remove legacy implications.
2463 free(mSinkBuffer);
2464 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002465 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2466 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2467 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002468 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002469
Andy Hung69aed5f2014-02-25 17:24:40 -08002470 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2471 // drives the output.
2472 free(mMixerBuffer);
2473 mMixerBuffer = NULL;
2474 if (mMixerBufferEnabled) {
2475 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2476 mMixerBufferSize = mNormalFrameCount * mChannelCount
2477 * audio_bytes_per_sample(mMixerBufferFormat);
2478 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2479 }
Andy Hung98ef9782014-03-04 14:46:50 -08002480 free(mEffectBuffer);
2481 mEffectBuffer = NULL;
2482 if (mEffectBufferEnabled) {
2483 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2484 mEffectBufferSize = mNormalFrameCount * mChannelCount
2485 * audio_bytes_per_sample(mEffectBufferFormat);
2486 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2487 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002488
Eric Laurent81784c32012-11-19 14:55:58 -08002489 // force reconfiguration of effect chains and engines to take new buffer size and audio
2490 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002491 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002492 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2493 // matter.
2494 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2495 Vector< sp<EffectChain> > effectChains = mEffectChains;
2496 for (size_t i = 0; i < effectChains.size(); i ++) {
2497 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2498 }
2499}
2500
2501
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002502status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002503{
2504 if (halFrames == NULL || dspFrames == NULL) {
2505 return BAD_VALUE;
2506 }
2507 Mutex::Autolock _l(mLock);
2508 if (initCheck() != NO_ERROR) {
2509 return INVALID_OPERATION;
2510 }
Andy Hung818e7a32016-02-16 18:08:07 -08002511 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002512 *halFrames = framesWritten;
2513
2514 if (isSuspended()) {
2515 // return an estimation of rendered frames when the output is suspended
2516 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002517 *dspFrames = (uint32_t)
2518 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002519 return NO_ERROR;
2520 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002521 status_t status;
2522 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002523 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002524 *dspFrames = (size_t)frames;
2525 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002526 }
2527}
2528
Eric Laurent4c415062016-06-17 16:14:16 -07002529// hasAudioSession_l() must be called with ThreadBase::mLock held
2530uint32_t AudioFlinger::PlaybackThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08002531{
Eric Laurent81784c32012-11-19 14:55:58 -08002532 uint32_t result = 0;
2533 if (getEffectChain_l(sessionId) != 0) {
2534 result = EFFECT_SESSION;
2535 }
2536
2537 for (size_t i = 0; i < mTracks.size(); ++i) {
2538 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002539 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002540 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07002541 if (track->isFastTrack()) {
2542 result |= FAST_SESSION;
2543 }
Eric Laurent81784c32012-11-19 14:55:58 -08002544 break;
2545 }
2546 }
2547
2548 return result;
2549}
2550
Glenn Kastend848eb42016-03-08 13:42:11 -08002551uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08002552{
2553 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2554 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2555 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2556 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2557 }
2558 for (size_t i = 0; i < mTracks.size(); i++) {
2559 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002560 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002561 return AudioSystem::getStrategyForStream(track->streamType());
2562 }
2563 }
2564 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2565}
2566
2567
Phil Burk062e67a2015-02-11 13:40:50 -08002568AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002569{
2570 Mutex::Autolock _l(mLock);
2571 return mOutput;
2572}
2573
Phil Burk062e67a2015-02-11 13:40:50 -08002574AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002575{
2576 Mutex::Autolock _l(mLock);
2577 AudioStreamOut *output = mOutput;
2578 mOutput = NULL;
2579 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2580 // must push a NULL and wait for ack
2581 mOutputSink.clear();
2582 mPipeSink.clear();
2583 mNormalSink.clear();
2584 return output;
2585}
2586
2587// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002588sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08002589{
2590 if (mOutput == NULL) {
2591 return NULL;
2592 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002593 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08002594}
2595
2596uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2597{
2598 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2599}
2600
2601status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2602{
2603 if (!isValidSyncEvent(event)) {
2604 return BAD_VALUE;
2605 }
2606
2607 Mutex::Autolock _l(mLock);
2608
2609 for (size_t i = 0; i < mTracks.size(); ++i) {
2610 sp<Track> track = mTracks[i];
2611 if (event->triggerSession() == track->sessionId()) {
2612 (void) track->setSyncEvent(event);
2613 return NO_ERROR;
2614 }
2615 }
2616
2617 return NAME_NOT_FOUND;
2618}
2619
2620bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2621{
2622 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2623}
2624
2625void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2626 const Vector< sp<Track> >& tracksToRemove)
2627{
2628 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002629 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002630 for (size_t i = 0 ; i < count ; i++) {
2631 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002632 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002633 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002634 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002635#ifdef ADD_BATTERY_DATA
2636 // to track the speaker usage
2637 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2638#endif
2639 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002640 AudioSystem::releaseOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002641 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002642 }
Eric Laurent81784c32012-11-19 14:55:58 -08002643 }
2644 }
2645 }
Eric Laurent81784c32012-11-19 14:55:58 -08002646}
2647
2648void AudioFlinger::PlaybackThread::checkSilentMode_l()
2649{
2650 if (!mMasterMute) {
2651 char value[PROPERTY_VALUE_MAX];
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07002652 if (mOutDevice == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) {
2653 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
2654 return;
2655 }
Eric Laurent81784c32012-11-19 14:55:58 -08002656 if (property_get("ro.audio.silent", value, "0") > 0) {
2657 char *endptr;
2658 unsigned long ul = strtoul(value, &endptr, 0);
2659 if (*endptr == '\0' && ul != 0) {
2660 ALOGD("Silence is golden");
2661 // The setprop command will not allow a property to be changed after
2662 // the first time it is set, so we don't have to worry about un-muting.
2663 setMasterMute_l(true);
2664 }
2665 }
2666 }
2667}
2668
2669// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002670ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002671{
Eric Laurent81784c32012-11-19 14:55:58 -08002672 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002673 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002674 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002675
2676 // If an NBAIO sink is present, use it to write the normal mixer's submix
2677 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002678
Andy Hung010a1a12014-03-13 13:57:33 -07002679 const size_t count = mBytesRemaining / mFrameSize;
2680
Simon Wilson2d590962012-11-29 15:18:50 -08002681 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002682 // update the setpoint when AudioFlinger::mScreenState changes
2683 uint32_t screenState = AudioFlinger::mScreenState;
2684 if (screenState != mScreenState) {
2685 mScreenState = screenState;
2686 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2687 if (pipe != NULL) {
2688 pipe->setAvgFrames((mScreenState & 1) ?
2689 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2690 }
2691 }
Andy Hung010a1a12014-03-13 13:57:33 -07002692 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002693 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002694 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002695 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002696 } else {
2697 bytesWritten = framesWritten;
2698 }
2699 // otherwise use the HAL / AudioStreamOut directly
2700 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002701 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002702
Eric Laurentbfb1b832013-01-07 09:53:42 -08002703 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002704 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2705 mWriteAckSequence += 2;
2706 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002707 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002708 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002709 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002710 // FIXME We should have an implementation of timestamps for direct output threads.
2711 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002712 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurent51716182016-02-29 18:00:56 -08002713
Eric Laurentbfb1b832013-01-07 09:53:42 -08002714 if (mUseAsyncWrite &&
2715 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2716 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002717 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002718 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002719 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002720 }
Eric Laurent81784c32012-11-19 14:55:58 -08002721 }
2722
Eric Laurent81784c32012-11-19 14:55:58 -08002723 mNumWrites++;
2724 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002725 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002726 return bytesWritten;
2727}
2728
2729void AudioFlinger::PlaybackThread::threadLoop_drain()
2730{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002731 bool supportsDrain = false;
2732 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002733 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2734 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002735 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2736 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002737 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002738 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002739 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07002740 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002741 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002742 }
2743}
2744
2745void AudioFlinger::PlaybackThread::threadLoop_exit()
2746{
Eric Laurent275e8e92014-11-30 15:14:47 -08002747 {
2748 Mutex::Autolock _l(mLock);
2749 for (size_t i = 0; i < mTracks.size(); i++) {
2750 sp<Track> track = mTracks[i];
2751 track->invalidate();
2752 }
2753 }
Eric Laurent81784c32012-11-19 14:55:58 -08002754}
2755
2756/*
2757The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002758 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002759 - mActiveSleepTimeUs from activeSleepTimeUs()
2760 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08002761 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
2762 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08002763 - maxPeriod from frame count and sample rate (MIXER only)
2764
2765The parameters that affect these derived values are:
2766 - frame count
2767 - frame size
2768 - sample rate
2769 - device type: A2DP or not
2770 - device latency
2771 - format: PCM or not
2772 - active sleep time
2773 - idle sleep time
2774*/
2775
2776void AudioFlinger::PlaybackThread::cacheParameters_l()
2777{
Andy Hung25c2dac2014-02-27 14:56:00 -08002778 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002779 mActiveSleepTimeUs = activeSleepTimeUs();
2780 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08002781
2782 // make sure standby delay is not too short when connected to an A2DP sink to avoid
2783 // truncating audio when going to standby.
2784 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
2785 if ((mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != 0) {
2786 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
2787 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
2788 }
2789 }
Eric Laurent81784c32012-11-19 14:55:58 -08002790}
2791
Eric Laurent13084622016-05-17 10:51:49 -07002792bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08002793{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002794 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08002795 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07002796 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002797 size_t size = mTracks.size();
2798 for (size_t i = 0; i < size; i++) {
2799 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07002800 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002801 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07002802 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002803 }
2804 }
Eric Laurent13084622016-05-17 10:51:49 -07002805 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08002806}
2807
Haynes Mathew George05317d22016-05-03 16:34:26 -07002808void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2809{
2810 Mutex::Autolock _l(mLock);
2811 invalidateTracks_l(streamType);
2812}
2813
Eric Laurent81784c32012-11-19 14:55:58 -08002814status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2815{
Glenn Kastend848eb42016-03-08 13:42:11 -08002816 audio_session_t session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002817 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2818 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002819 bool ownsBuffer = false;
2820
2821 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Glenn Kastend848eb42016-03-08 13:42:11 -08002822 if (session > AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002823 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002824 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002825 if (mType != DIRECT) {
2826 size_t numSamples = mNormalFrameCount * mChannelCount;
2827 buffer = new int16_t[numSamples];
2828 memset(buffer, 0, numSamples * sizeof(int16_t));
2829 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2830 ownsBuffer = true;
2831 }
2832
2833 // Attach all tracks with same session ID to this chain.
2834 for (size_t i = 0; i < mTracks.size(); ++i) {
2835 sp<Track> track = mTracks[i];
2836 if (session == track->sessionId()) {
2837 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2838 buffer);
2839 track->setMainBuffer(buffer);
2840 chain->incTrackCnt();
2841 }
2842 }
2843
2844 // indicate all active tracks in the chain
2845 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2846 sp<Track> track = mActiveTracks[i].promote();
2847 if (track == 0) {
2848 continue;
2849 }
2850 if (session == track->sessionId()) {
2851 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2852 chain->incActiveTrackCnt();
2853 }
2854 }
2855 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002856 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08002857 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002858 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2859 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002860 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Glenn Kastend848eb42016-03-08 13:42:11 -08002861 // chains list in order to be processed last as it contains output stage effects.
Eric Laurent81784c32012-11-19 14:55:58 -08002862 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2863 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08002864 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08002865 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08002866 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08002867 // Effect chain for other sessions are inserted at beginning of effect
2868 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08002869 // sessions is not important.
2870 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
2871 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX,
2872 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08002873 size_t size = mEffectChains.size();
2874 size_t i = 0;
2875 for (i = 0; i < size; i++) {
2876 if (mEffectChains[i]->sessionId() < session) {
2877 break;
2878 }
2879 }
2880 mEffectChains.insertAt(chain, i);
2881 checkSuspendOnAddEffectChain_l(chain);
2882
2883 return NO_ERROR;
2884}
2885
2886size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2887{
Glenn Kastend848eb42016-03-08 13:42:11 -08002888 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08002889
2890 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2891
2892 for (size_t i = 0; i < mEffectChains.size(); i++) {
2893 if (chain == mEffectChains[i]) {
2894 mEffectChains.removeAt(i);
2895 // detach all active tracks from the chain
2896 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2897 sp<Track> track = mActiveTracks[i].promote();
2898 if (track == 0) {
2899 continue;
2900 }
2901 if (session == track->sessionId()) {
2902 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2903 chain.get(), session);
2904 chain->decActiveTrackCnt();
2905 }
2906 }
2907
2908 // detach all tracks with same session ID from this chain
2909 for (size_t i = 0; i < mTracks.size(); ++i) {
2910 sp<Track> track = mTracks[i];
2911 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002912 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002913 chain->decTrackCnt();
2914 }
2915 }
2916 break;
2917 }
2918 }
2919 return mEffectChains.size();
2920}
2921
2922status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002923 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08002924{
2925 Mutex::Autolock _l(mLock);
2926 return attachAuxEffect_l(track, EffectId);
2927}
2928
2929status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002930 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08002931{
2932 status_t status = NO_ERROR;
2933
2934 if (EffectId == 0) {
2935 track->setAuxBuffer(0, NULL);
2936 } else {
2937 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2938 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2939 if (effect != 0) {
2940 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2941 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2942 } else {
2943 status = INVALID_OPERATION;
2944 }
2945 } else {
2946 status = BAD_VALUE;
2947 }
2948 }
2949 return status;
2950}
2951
2952void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2953{
2954 for (size_t i = 0; i < mTracks.size(); ++i) {
2955 sp<Track> track = mTracks[i];
2956 if (track->auxEffectId() == effectId) {
2957 attachAuxEffect_l(track, 0);
2958 }
2959 }
2960}
2961
2962bool AudioFlinger::PlaybackThread::threadLoop()
2963{
2964 Vector< sp<Track> > tracksToRemove;
2965
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002966 mStandbyTimeNs = systemTime();
Andy Hung69488c42016-05-16 18:43:33 -07002967 nsecs_t lastWriteFinished = -1; // time last server write completed
2968 int64_t lastFramesWritten = -1; // track changes in timestamp server frames written
Eric Laurent81784c32012-11-19 14:55:58 -08002969
2970 // MIXER
2971 nsecs_t lastWarning = 0;
2972
2973 // DUPLICATING
2974 // FIXME could this be made local to while loop?
2975 writeFrames = 0;
2976
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002977 int lastGeneration = 0;
2978
Eric Laurent81784c32012-11-19 14:55:58 -08002979 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002980 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002981
2982 if (mType == MIXER) {
2983 sleepTimeShift = 0;
2984 }
2985
2986 CpuStats cpuStats;
2987 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2988
2989 acquireWakeLock();
2990
Glenn Kasten9e58b552013-01-18 15:09:48 -08002991 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2992 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2993 // and then that string will be logged at the next convenient opportunity.
2994 const char *logString = NULL;
2995
Eric Laurent664539d2013-09-23 18:24:31 -07002996 checkSilentMode_l();
2997
Eric Laurent81784c32012-11-19 14:55:58 -08002998 while (!exitPending())
2999 {
3000 cpuStats.sample(myName);
3001
3002 Vector< sp<EffectChain> > effectChains;
3003
Eric Laurent81784c32012-11-19 14:55:58 -08003004 { // scope for mLock
3005
3006 Mutex::Autolock _l(mLock);
3007
Eric Laurent021cf962014-05-13 10:18:14 -07003008 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07003009
Glenn Kasten9e58b552013-01-18 15:09:48 -08003010 if (logString != NULL) {
3011 mNBLogWriter->logTimestamp();
3012 mNBLogWriter->log(logString);
3013 logString = NULL;
3014 }
3015
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003016 // Gather the framesReleased counters for all active tracks,
Andy Hunge10393e2015-06-12 13:59:33 -07003017 // and associate with the sink frames written out. We need
3018 // this to convert the sink timestamp to the track timestamp.
Andy Hung69488c42016-05-16 18:43:33 -07003019 bool kernelLocationUpdate = false;
Andy Hunge10393e2015-06-12 13:59:33 -07003020 if (mNormalSink != 0) {
Andy Hungc54b1ff2016-02-23 14:07:07 -08003021 // Note: The DuplicatingThread may not have a mNormalSink.
Andy Hung818e7a32016-02-16 18:08:07 -08003022 // We always fetch the timestamp here because often the downstream
Andy Hung69488c42016-05-16 18:43:33 -07003023 // sink will block while writing.
Andy Hung818e7a32016-02-16 18:08:07 -08003024 ExtendedTimestamp timestamp; // use private copy to fetch
3025 (void) mNormalSink->getTimestamp(timestamp);
Andy Hung6d7b1192016-05-07 22:59:48 -07003026
3027 // We keep track of the last valid kernel position in case we are in underrun
3028 // and the normal mixer period is the same as the fast mixer period, or there
3029 // is some error from the HAL.
3030 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3031 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3032 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
3033 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3034 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
3035
3036 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3037 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
3038 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3039 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
Andy Hung69488c42016-05-16 18:43:33 -07003040 }
3041
3042 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3043 kernelLocationUpdate = true;
Andy Hung6d7b1192016-05-07 22:59:48 -07003044 } else {
Eric Laurent122f7e72016-06-29 11:53:29 -07003045 ALOGVV("getTimestamp error - no valid kernel position");
Andy Hung6d7b1192016-05-07 22:59:48 -07003046 }
3047
Andy Hung818e7a32016-02-16 18:08:07 -08003048 // copy over kernel info
3049 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
Andy Hung238fa3d2016-07-28 10:53:22 -07003050 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3051 + mSuspendedFrames; // add frames discarded when suspended
Andy Hung818e7a32016-02-16 18:08:07 -08003052 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
3053 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hungc54b1ff2016-02-23 14:07:07 -08003054 }
3055 // mFramesWritten for non-offloaded tracks are contiguous
3056 // even after standby() is called. This is useful for the track frame
3057 // to sink frame mapping.
Andy Hung69488c42016-05-16 18:43:33 -07003058 bool serverLocationUpdate = false;
3059 if (mFramesWritten != lastFramesWritten) {
3060 serverLocationUpdate = true;
3061 lastFramesWritten = mFramesWritten;
3062 }
3063 // Only update timestamps if there is a meaningful change.
3064 // Either the kernel timestamp must be valid or we have written something.
3065 if (kernelLocationUpdate || serverLocationUpdate) {
3066 if (serverLocationUpdate) {
3067 // use the time before we called the HAL write - it is a bit more accurate
3068 // to when the server last read data than the current time here.
3069 //
3070 // If we haven't written anything, mLastWriteTime will be -1
3071 // and we use systemTime().
3072 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
3073 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastWriteTime == -1
3074 ? systemTime() : mLastWriteTime;
3075 }
3076 const size_t size = mActiveTracks.size();
3077 for (size_t i = 0; i < size; ++i) {
3078 sp<Track> t = mActiveTracks[i].promote();
3079 if (t != 0 && !t->isFastTrack()) {
3080 t->updateTrackFrameInfo(
3081 t->mAudioTrackServerProxy->framesReleased(),
3082 mFramesWritten,
3083 mTimestamp);
3084 }
Andy Hunge10393e2015-06-12 13:59:33 -07003085 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07003086 }
3087
Eric Laurent81784c32012-11-19 14:55:58 -08003088 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003089 if (mSignalPending) {
3090 // A signal was raised while we were unlocked
3091 mSignalPending = false;
3092 } else if (waitingAsyncCallback_l()) {
3093 if (exitPending()) {
3094 break;
3095 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003096 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003097 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003098 releaseWakeLock_l();
3099 released = true;
Mikhail Naganove94c27a2016-08-18 17:31:46 -07003100 mWakeLockUids.clear();
3101 mActiveTracksGeneration++;
Marco Nelissen078538c2015-05-12 09:17:57 -07003102 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003103 ALOGV("wait async completion");
3104 mWaitWorkCV.wait(mLock);
3105 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003106 if (released) {
3107 acquireWakeLock_l();
3108 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003109 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3110 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003111
3112 continue;
3113 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003114 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003115 isSuspended()) {
3116 // put audio hardware into standby after short delay
3117 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003118
3119 threadLoop_standby();
3120
3121 mStandby = true;
3122 }
3123
3124 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
3125 // we're about to wait, flush the binder command buffer
3126 IPCThreadState::self()->flushCommands();
3127
3128 clearOutputTracks();
3129
3130 if (exitPending()) {
3131 break;
3132 }
3133
3134 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003135 mWakeLockUids.clear();
3136 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08003137 // wait until we have something to do...
3138 ALOGV("%s going to sleep", myName.string());
3139 mWaitWorkCV.wait(mLock);
3140 ALOGV("%s waking up", myName.string());
3141 acquireWakeLock_l();
3142
3143 mMixerStatus = MIXER_IDLE;
3144 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3145 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003146 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003147 checkSilentMode_l();
3148
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003149 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3150 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003151 if (mType == MIXER) {
3152 sleepTimeShift = 0;
3153 }
3154
3155 continue;
3156 }
3157 }
Eric Laurent81784c32012-11-19 14:55:58 -08003158 // mMixerStatusIgnoringFastTracks is also updated internally
3159 mMixerStatus = prepareTracks_l(&tracksToRemove);
3160
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003161 // compare with previously applied list
3162 if (lastGeneration != mActiveTracksGeneration) {
3163 // update wakelock
3164 updateWakeLockUids_l(mWakeLockUids);
3165 lastGeneration = mActiveTracksGeneration;
3166 }
3167
Eric Laurent81784c32012-11-19 14:55:58 -08003168 // prevent any changes in effect chain list and in each effect chain
3169 // during mixing and effect process as the audio buffers could be deleted
3170 // or modified if an effect is created or deleted
3171 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003172 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003173
Eric Laurentbfb1b832013-01-07 09:53:42 -08003174 if (mBytesRemaining == 0) {
3175 mCurrentWriteLength = 0;
3176 if (mMixerStatus == MIXER_TRACKS_READY) {
3177 // threadLoop_mix() sets mCurrentWriteLength
3178 threadLoop_mix();
3179 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3180 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003181 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003182 // must be written to HAL
3183 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003184 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003185 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003186 }
3187 }
Andy Hung98ef9782014-03-04 14:46:50 -08003188 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003189 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003190 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3191 // or mSinkBuffer (if there are no effects).
3192 //
3193 // This is done pre-effects computation; if effects change to
3194 // support higher precision, this needs to move.
3195 //
3196 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003197 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003198 if (mMixerBufferValid) {
3199 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3200 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3201
Andy Hung2ddee192015-12-18 17:34:44 -08003202 // mono blend occurs for mixer threads only (not direct or offloaded)
3203 // and is handled here if we're going directly to the sink.
3204 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003205 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3206 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003207 }
3208
Andy Hung98ef9782014-03-04 14:46:50 -08003209 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
3210 mNormalFrameCount * mChannelCount);
3211 }
3212
Eric Laurentbfb1b832013-01-07 09:53:42 -08003213 mBytesRemaining = mCurrentWriteLength;
3214 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003215 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3216 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3217 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3218 mBytesWritten += mBytesRemaining;
3219 mFramesWritten += framesRemaining;
3220 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003221 mBytesRemaining = 0;
3222 }
Eric Laurent81784c32012-11-19 14:55:58 -08003223
Eric Laurentbfb1b832013-01-07 09:53:42 -08003224 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003225 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003226 for (size_t i = 0; i < effectChains.size(); i ++) {
3227 effectChains[i]->process_l();
3228 }
Eric Laurent81784c32012-11-19 14:55:58 -08003229 }
3230 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003231 // Process effect chains for offloaded thread even if no audio
3232 // was read from audio track: process only updates effect state
3233 // and thus does have to be synchronized with audio writes but may have
3234 // to be called while waiting for async write callback
3235 if (mType == OFFLOAD) {
3236 for (size_t i = 0; i < effectChains.size(); i ++) {
3237 effectChains[i]->process_l();
3238 }
3239 }
Eric Laurent81784c32012-11-19 14:55:58 -08003240
Andy Hung98ef9782014-03-04 14:46:50 -08003241 // Only if the Effects buffer is enabled and there is data in the
3242 // Effects buffer (buffer valid), we need to
3243 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003244 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003245 if (mEffectBufferValid) {
3246 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003247
3248 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003249 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3250 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003251 }
3252
Andy Hung98ef9782014-03-04 14:46:50 -08003253 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
3254 mNormalFrameCount * mChannelCount);
3255 }
3256
Eric Laurent81784c32012-11-19 14:55:58 -08003257 // enable changes in effect chain
3258 unlockEffectChains(effectChains);
3259
Eric Laurentbfb1b832013-01-07 09:53:42 -08003260 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003261 // mSleepTimeUs == 0 means we must write to audio hardware
3262 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003263 ssize_t ret = 0;
Andy Hung69488c42016-05-16 18:43:33 -07003264 // We save lastWriteFinished here, as previousLastWriteFinished,
3265 // for throttling. On thread start, previousLastWriteFinished will be
3266 // set to -1, which properly results in no throttling after the first write.
3267 nsecs_t previousLastWriteFinished = lastWriteFinished;
3268 nsecs_t delta = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003269 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003270 // FIXME rewrite to reduce number of system calls
3271 mLastWriteTime = systemTime(); // also used for dumpsys
Andy Hung08fb1742015-05-31 23:22:10 -07003272 ret = threadLoop_write();
Andy Hung69488c42016-05-16 18:43:33 -07003273 lastWriteFinished = systemTime();
3274 delta = lastWriteFinished - mLastWriteTime;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003275 if (ret < 0) {
3276 mBytesRemaining = 0;
3277 } else {
3278 mBytesWritten += ret;
3279 mBytesRemaining -= ret;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003280 mFramesWritten += ret / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003281 }
3282 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3283 (mMixerStatus == MIXER_DRAIN_ALL)) {
3284 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003285 }
Andy Hung08fb1742015-05-31 23:22:10 -07003286 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003287 // write blocked detection
Andy Hung08fb1742015-05-31 23:22:10 -07003288 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003289 mNumDelayedWrites++;
Andy Hung69488c42016-05-16 18:43:33 -07003290 if ((lastWriteFinished - lastWarning) > kWarningThrottleNs) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003291 ATRACE_NAME("underrun");
3292 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003293 (unsigned long long) ns2ms(delta), mNumDelayedWrites, this);
Andy Hung69488c42016-05-16 18:43:33 -07003294 lastWarning = lastWriteFinished;
Glenn Kasten4944acb2013-08-19 08:39:20 -07003295 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003296 }
Andy Hung08fb1742015-05-31 23:22:10 -07003297
3298 if (mThreadThrottle
3299 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
3300 && ret > 0) { // we wrote something
3301 // Limit MixerThread data processing to no more than twice the
3302 // expected processing rate.
3303 //
3304 // This helps prevent underruns with NuPlayer and other applications
3305 // which may set up buffers that are close to the minimum size, or use
3306 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3307 //
3308 // The throttle smooths out sudden large data drains from the device,
3309 // e.g. when it comes out of standby, which often causes problems with
3310 // (1) mixer threads without a fast mixer (which has its own warm-up)
3311 // (2) minimum buffer sized tracks (even if the track is full,
3312 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07003313 //
3314 // Total time spent in last processing cycle equals time spent in
3315 // 1. threadLoop_write, as well as time spent in
3316 // 2. threadLoop_mix (significant for heavy mixing, especially
3317 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07003318
Andy Hung69488c42016-05-16 18:43:33 -07003319 // it's OK if deltaMs is an overestimate.
3320 const int32_t deltaMs =
3321 (lastWriteFinished - previousLastWriteFinished) / 1000000;
Andy Hung08fb1742015-05-31 23:22:10 -07003322 const int32_t throttleMs = mHalfBufferMs - deltaMs;
3323 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3324 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003325 // notify of throttle start on verbose log
3326 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3327 "mixer(%p) throttle begin:"
3328 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003329 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003330 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07003331 // Throttle must be attributed to the previous mixer loop's write time
3332 // to allow back-to-back throttling.
3333 lastWriteFinished += throttleMs * 1000000;
Andy Hung40eb1a12015-06-18 13:42:02 -07003334 } else {
3335 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3336 if (diff > 0) {
3337 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07003338 // but prevent spamming for bluetooth
3339 ALOGD_IF(!audio_is_a2dp_out_device(outDevice()),
3340 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07003341 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3342 }
Andy Hung08fb1742015-05-31 23:22:10 -07003343 }
3344 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003345 }
Eric Laurent81784c32012-11-19 14:55:58 -08003346
Eric Laurentbfb1b832013-01-07 09:53:42 -08003347 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003348 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07003349 Mutex::Autolock _l(mLock);
3350 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
3351 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08003352 }
Glenn Kastene7754022014-10-31 12:11:26 -07003353 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003354 }
Eric Laurent81784c32012-11-19 14:55:58 -08003355 }
3356
3357 // Finally let go of removed track(s), without the lock held
3358 // since we can't guarantee the destructors won't acquire that
3359 // same lock. This will also mutate and push a new fast mixer state.
3360 threadLoop_removeTracks(tracksToRemove);
3361 tracksToRemove.clear();
3362
3363 // FIXME I don't understand the need for this here;
3364 // it was in the original code but maybe the
3365 // assignment in saveOutputTracks() makes this unnecessary?
3366 clearOutputTracks();
3367
3368 // Effect chains will be actually deleted here if they were removed from
3369 // mEffectChains list during mixing or effects processing
3370 effectChains.clear();
3371
3372 // FIXME Note that the above .clear() is no longer necessary since effectChains
3373 // is now local to this block, but will keep it for now (at least until merge done).
3374 }
3375
Eric Laurentbfb1b832013-01-07 09:53:42 -08003376 threadLoop_exit();
3377
Eric Laurentcf817a22014-08-04 20:36:31 -07003378 if (!mStandby) {
3379 threadLoop_standby();
3380 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003381 }
3382
3383 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003384 mWakeLockUids.clear();
3385 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08003386
3387 ALOGV("Thread %p type %d exiting", this, mType);
3388 return false;
3389}
3390
Eric Laurentbfb1b832013-01-07 09:53:42 -08003391// removeTracks_l() must be called with ThreadBase::mLock held
3392void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3393{
3394 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003395 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003396 for (size_t i=0 ; i<count ; i++) {
3397 const sp<Track>& track = tracksToRemove.itemAt(i);
3398 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003399 mWakeLockUids.remove(track->uid());
3400 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003401 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3402 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3403 if (chain != 0) {
3404 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3405 track->sessionId());
3406 chain->decActiveTrackCnt();
3407 }
3408 if (track->isTerminated()) {
3409 removeTrack_l(track);
3410 }
3411 }
3412 }
3413
3414}
Eric Laurent81784c32012-11-19 14:55:58 -08003415
Eric Laurentaccc1472013-09-20 09:36:34 -07003416status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3417{
3418 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08003419 ExtendedTimestamp ets;
3420 status_t status = mNormalSink->getTimestamp(ets);
3421 if (status == NO_ERROR) {
3422 status = ets.getBestTimestamp(&timestamp);
3423 }
3424 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07003425 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003426 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003427 uint64_t position64;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003428 if (mOutput->getPresentationPosition(&position64, &timestamp.mTime) == OK) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003429 timestamp.mPosition = (uint32_t)position64;
3430 return NO_ERROR;
3431 }
3432 }
3433 return INVALID_OPERATION;
3434}
Eric Laurent1c333e22014-05-20 10:48:17 -07003435
Eric Laurent054d9d32015-04-24 08:48:48 -07003436status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3437 audio_patch_handle_t *handle)
3438{
Andy Hungf60abce2016-08-26 11:37:54 -07003439 status_t status;
3440 if (property_get_bool("af.patch_park", false /* default_value */)) {
3441 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3442 // or if HAL does not properly lock against access.
3443 AutoPark<FastMixer> park(mFastMixer);
3444 status = PlaybackThread::createAudioPatch_l(patch, handle);
3445 } else {
3446 status = PlaybackThread::createAudioPatch_l(patch, handle);
3447 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003448 return status;
3449}
3450
Eric Laurent1c333e22014-05-20 10:48:17 -07003451status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3452 audio_patch_handle_t *handle)
3453{
3454 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003455
3456 // store new device and send to effects
3457 audio_devices_t type = AUDIO_DEVICE_NONE;
3458 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3459 type |= patch->sinks[i].ext.device.type;
3460 }
3461
3462#ifdef ADD_BATTERY_DATA
3463 // when changing the audio output device, call addBatteryData to notify
3464 // the change
3465 if (mOutDevice != type) {
3466 uint32_t params = 0;
3467 // check whether speaker is on
3468 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3469 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003470 }
3471
Eric Laurent054d9d32015-04-24 08:48:48 -07003472 audio_devices_t deviceWithoutSpeaker
3473 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3474 // check if any other device (except speaker) is on
3475 if (type & deviceWithoutSpeaker) {
3476 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3477 }
3478
3479 if (params != 0) {
3480 addBatteryData(params);
3481 }
3482 }
3483#endif
3484
3485 for (size_t i = 0; i < mEffectChains.size(); i++) {
3486 mEffectChains[i]->setDevice_l(type);
3487 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003488
3489 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3490 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3491 bool configChanged = mPrevOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003492 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003493 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003494
3495 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003496 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3497 status = hwDevice->createAudioPatch(patch->num_sources,
3498 patch->sources,
3499 patch->num_sinks,
3500 patch->sinks,
3501 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003502 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003503 char *address;
3504 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3505 //FIXME: we only support address on first sink with HAL version < 3.0
3506 address = audio_device_address_to_parameter(
3507 patch->sinks[0].ext.device.type,
3508 patch->sinks[0].ext.device.address);
3509 } else {
3510 address = (char *)calloc(1, 1);
3511 }
3512 AudioParameter param = AudioParameter(String8(address));
3513 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07003514 param.addInt(String8(AudioParameter::keyRouting), (int)type);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003515 status = mOutput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07003516 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003517 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003518 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003519 mPrevOutDevice = type;
Eric Laurente8726fe2015-06-26 09:39:24 -07003520 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3521 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003522 return status;
3523}
3524
Eric Laurent054d9d32015-04-24 08:48:48 -07003525status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3526{
Andy Hungf60abce2016-08-26 11:37:54 -07003527 status_t status;
3528 if (property_get_bool("af.patch_park", false /* default_value */)) {
3529 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3530 // or if HAL does not properly lock against access.
3531 AutoPark<FastMixer> park(mFastMixer);
3532 status = PlaybackThread::releaseAudioPatch_l(handle);
3533 } else {
3534 status = PlaybackThread::releaseAudioPatch_l(handle);
3535 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003536 return status;
3537}
3538
Eric Laurent1c333e22014-05-20 10:48:17 -07003539status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3540{
3541 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003542
3543 mOutDevice = AUDIO_DEVICE_NONE;
3544
Eric Laurent1c333e22014-05-20 10:48:17 -07003545 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003546 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3547 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003548 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003549 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07003550 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003551 status = mOutput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07003552 }
3553 return status;
3554}
3555
Eric Laurent83b88082014-06-20 18:31:16 -07003556void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3557{
3558 Mutex::Autolock _l(mLock);
3559 mTracks.add(track);
3560}
3561
3562void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3563{
3564 Mutex::Autolock _l(mLock);
3565 destroyTrack_l(track);
3566}
3567
3568void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3569{
3570 ThreadBase::getAudioPortConfig(config);
3571 config->role = AUDIO_PORT_ROLE_SOURCE;
3572 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3573 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3574}
3575
Eric Laurent81784c32012-11-19 14:55:58 -08003576// ----------------------------------------------------------------------------
3577
3578AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003579 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3580 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003581 // mAudioMixer below
3582 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08003583 mFastMixerFutex(0),
3584 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08003585 // mOutputSink below
3586 // mPipeSink below
3587 // mNormalSink below
3588{
3589 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003590 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%zu, "
3591 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003592 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3593 mNormalFrameCount);
3594 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3595
Andy Hungfbfc3952015-01-15 13:33:51 -08003596 if (type == DUPLICATING) {
3597 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3598 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3599 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3600 return;
3601 }
Eric Laurent81784c32012-11-19 14:55:58 -08003602 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07003603 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08003604 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003605 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003606#if !LOG_NDEBUG
3607 ssize_t index =
3608#else
3609 (void)
3610#endif
3611 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003612 ALOG_ASSERT(index == 0);
3613
3614 // initialize fast mixer depending on configuration
3615 bool initFastMixer;
3616 switch (kUseFastMixer) {
3617 case FastMixer_Never:
3618 initFastMixer = false;
3619 break;
3620 case FastMixer_Always:
3621 initFastMixer = true;
3622 break;
3623 case FastMixer_Static:
3624 case FastMixer_Dynamic:
3625 initFastMixer = mFrameCount < mNormalFrameCount;
3626 break;
3627 }
3628 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003629 audio_format_t fastMixerFormat;
3630 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3631 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3632 } else {
3633 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3634 }
3635 if (mFormat != fastMixerFormat) {
3636 // change our Sink format to accept our intermediate precision
3637 mFormat = fastMixerFormat;
3638 free(mSinkBuffer);
3639 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3640 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3641 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3642 }
Eric Laurent81784c32012-11-19 14:55:58 -08003643
3644 // create a MonoPipe to connect our submix to FastMixer
3645 NBAIO_Format format = mOutputSink->format();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003646#ifdef TEE_SINK
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003647 NBAIO_Format origformat = format;
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003648#endif
Andy Hung1258c1a2014-05-23 21:22:17 -07003649 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07003650 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003651 format.mFormat = fastMixerFormat;
3652 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3653
Eric Laurent81784c32012-11-19 14:55:58 -08003654 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3655 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3656 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3657 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3658 const NBAIO_Format offers[1] = {format};
3659 size_t numCounterOffers = 0;
Glenn Kastenfc302fd2016-04-11 14:11:26 -07003660#if !LOG_NDEBUG || defined(TEE_SINK)
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003661 ssize_t index =
3662#else
3663 (void)
3664#endif
3665 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003666 ALOG_ASSERT(index == 0);
3667 monoPipe->setAvgFrames((mScreenState & 1) ?
3668 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3669 mPipeSink = monoPipe;
3670
Glenn Kasten46909e72013-02-26 09:20:22 -08003671#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003672 if (mTeeSinkOutputEnabled) {
3673 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003674 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3675 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003676 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003677 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003678 ALOG_ASSERT(index == 0);
3679 mTeeSink = teeSink;
3680 PipeReader *teeSource = new PipeReader(*teeSink);
3681 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003682 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003683 ALOG_ASSERT(index == 0);
3684 mTeeSource = teeSource;
3685 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003686#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003687
3688 // create fast mixer and configure it initially with just one fast track for our submix
3689 mFastMixer = new FastMixer();
3690 FastMixerStateQueue *sq = mFastMixer->sq();
3691#ifdef STATE_QUEUE_DUMP
3692 sq->setObserverDump(&mStateQueueObserverDump);
3693 sq->setMutatorDump(&mStateQueueMutatorDump);
3694#endif
3695 FastMixerState *state = sq->begin();
3696 FastTrack *fastTrack = &state->mFastTracks[0];
3697 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3698 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3699 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003700 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3701 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003702 fastTrack->mGeneration++;
3703 state->mFastTracksGen++;
3704 state->mTrackMask = 1;
3705 // fast mixer will use the HAL output sink
3706 state->mOutputSink = mOutputSink.get();
3707 state->mOutputSinkGen++;
3708 state->mFrameCount = mFrameCount;
3709 state->mCommand = FastMixerState::COLD_IDLE;
3710 // already done in constructor initialization list
3711 //mFastMixerFutex = 0;
3712 state->mColdFutexAddr = &mFastMixerFutex;
3713 state->mColdGen++;
3714 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003715#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003716 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003717#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003718 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3719 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003720 sq->end();
3721 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3722
3723 // start the fast mixer
3724 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3725 pid_t tid = mFastMixer->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003726 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003727
3728#ifdef AUDIO_WATCHDOG
3729 // create and start the watchdog
3730 mAudioWatchdog = new AudioWatchdog();
3731 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3732 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3733 tid = mAudioWatchdog->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003734 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003735#endif
3736
Eric Laurent81784c32012-11-19 14:55:58 -08003737 }
3738
3739 switch (kUseFastMixer) {
3740 case FastMixer_Never:
3741 case FastMixer_Dynamic:
3742 mNormalSink = mOutputSink;
3743 break;
3744 case FastMixer_Always:
3745 mNormalSink = mPipeSink;
3746 break;
3747 case FastMixer_Static:
3748 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3749 break;
3750 }
3751}
3752
3753AudioFlinger::MixerThread::~MixerThread()
3754{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003755 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003756 FastMixerStateQueue *sq = mFastMixer->sq();
3757 FastMixerState *state = sq->begin();
3758 if (state->mCommand == FastMixerState::COLD_IDLE) {
3759 int32_t old = android_atomic_inc(&mFastMixerFutex);
3760 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003761 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003762 }
3763 }
3764 state->mCommand = FastMixerState::EXIT;
3765 sq->end();
3766 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3767 mFastMixer->join();
3768 // Though the fast mixer thread has exited, it's state queue is still valid.
3769 // We'll use that extract the final state which contains one remaining fast track
3770 // corresponding to our sub-mix.
3771 state = sq->begin();
3772 ALOG_ASSERT(state->mTrackMask == 1);
3773 FastTrack *fastTrack = &state->mFastTracks[0];
3774 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3775 delete fastTrack->mBufferProvider;
3776 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003777 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003778#ifdef AUDIO_WATCHDOG
3779 if (mAudioWatchdog != 0) {
3780 mAudioWatchdog->requestExit();
3781 mAudioWatchdog->requestExitAndWait();
3782 mAudioWatchdog.clear();
3783 }
3784#endif
3785 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003786 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003787 delete mAudioMixer;
3788}
3789
3790
3791uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3792{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003793 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003794 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3795 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3796 }
3797 return latency;
3798}
3799
3800
3801void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3802{
3803 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3804}
3805
Eric Laurentbfb1b832013-01-07 09:53:42 -08003806ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003807{
3808 // FIXME we should only do one push per cycle; confirm this is true
3809 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003810 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003811 FastMixerStateQueue *sq = mFastMixer->sq();
3812 FastMixerState *state = sq->begin();
3813 if (state->mCommand != FastMixerState::MIX_WRITE &&
3814 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3815 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07003816
3817 // FIXME workaround for first HAL write being CPU bound on some devices
3818 ATRACE_BEGIN("write");
3819 mOutput->write((char *)mSinkBuffer, 0);
3820 ATRACE_END();
3821
Eric Laurent81784c32012-11-19 14:55:58 -08003822 int32_t old = android_atomic_inc(&mFastMixerFutex);
3823 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003824 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003825 }
3826#ifdef AUDIO_WATCHDOG
3827 if (mAudioWatchdog != 0) {
3828 mAudioWatchdog->resume();
3829 }
3830#endif
3831 }
3832 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003833#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003834 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003835 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003836#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003837 sq->end();
3838 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3839 if (kUseFastMixer == FastMixer_Dynamic) {
3840 mNormalSink = mPipeSink;
3841 }
3842 } else {
3843 sq->end(false /*didModify*/);
3844 }
3845 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003846 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003847}
3848
3849void AudioFlinger::MixerThread::threadLoop_standby()
3850{
3851 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003852 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003853 FastMixerStateQueue *sq = mFastMixer->sq();
3854 FastMixerState *state = sq->begin();
3855 if (!(state->mCommand & FastMixerState::IDLE)) {
3856 state->mCommand = FastMixerState::COLD_IDLE;
3857 state->mColdFutexAddr = &mFastMixerFutex;
3858 state->mColdGen++;
3859 mFastMixerFutex = 0;
3860 sq->end();
3861 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3862 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3863 if (kUseFastMixer == FastMixer_Dynamic) {
3864 mNormalSink = mOutputSink;
3865 }
3866#ifdef AUDIO_WATCHDOG
3867 if (mAudioWatchdog != 0) {
3868 mAudioWatchdog->pause();
3869 }
3870#endif
3871 } else {
3872 sq->end(false /*didModify*/);
3873 }
3874 }
3875 PlaybackThread::threadLoop_standby();
3876}
3877
Eric Laurentbfb1b832013-01-07 09:53:42 -08003878bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3879{
3880 return false;
3881}
3882
3883bool AudioFlinger::PlaybackThread::shouldStandby_l()
3884{
3885 return !mStandby;
3886}
3887
3888bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3889{
3890 Mutex::Autolock _l(mLock);
3891 return waitingAsyncCallback_l();
3892}
3893
Eric Laurent81784c32012-11-19 14:55:58 -08003894// shared by MIXER and DIRECT, overridden by DUPLICATING
3895void AudioFlinger::PlaybackThread::threadLoop_standby()
3896{
3897 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08003898 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003899 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003900 // discard any pending drain or write ack by incrementing sequence
3901 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3902 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003903 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003904 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3905 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003906 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003907 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003908}
3909
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003910void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3911{
3912 ALOGV("signal playback thread");
3913 broadcast_l();
3914}
3915
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003916void AudioFlinger::PlaybackThread::onAsyncError()
3917{
3918 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
3919 invalidateTracks((audio_stream_type_t)i);
3920 }
3921}
3922
Eric Laurent81784c32012-11-19 14:55:58 -08003923void AudioFlinger::MixerThread::threadLoop_mix()
3924{
Eric Laurent81784c32012-11-19 14:55:58 -08003925 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08003926 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08003927 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003928 // increase sleep time progressively when application underrun condition clears.
3929 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3930 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3931 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003932 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003933 sleepTimeShift--;
3934 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003935 mSleepTimeUs = 0;
3936 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08003937 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003938
Eric Laurent81784c32012-11-19 14:55:58 -08003939}
3940
3941void AudioFlinger::MixerThread::threadLoop_sleepTime()
3942{
3943 // If no tracks are ready, sleep once for the duration of an output
3944 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003945 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003946 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003947 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
3948 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
3949 mSleepTimeUs = kMinThreadSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003950 }
3951 // reduce sleep time in case of consecutive application underruns to avoid
3952 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3953 // duration we would end up writing less data than needed by the audio HAL if
3954 // the condition persists.
3955 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3956 sleepTimeShift++;
3957 }
3958 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003959 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003960 }
3961 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003962 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3963 // before effects processing or output.
3964 if (mMixerBufferValid) {
3965 memset(mMixerBuffer, 0, mMixerBufferSize);
3966 } else {
3967 memset(mSinkBuffer, 0, mSinkBufferSize);
3968 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003969 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003970 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3971 "anticipated start");
3972 }
3973 // TODO add standby time extension fct of effect tail
3974}
3975
3976// prepareTracks_l() must be called with ThreadBase::mLock held
3977AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3978 Vector< sp<Track> > *tracksToRemove)
3979{
3980
3981 mixer_state mixerStatus = MIXER_IDLE;
3982 // find out which tracks need to be processed
3983 size_t count = mActiveTracks.size();
3984 size_t mixedTracks = 0;
3985 size_t tracksWithEffect = 0;
3986 // counts only _active_ fast tracks
3987 size_t fastTracks = 0;
3988 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3989
3990 float masterVolume = mMasterVolume;
3991 bool masterMute = mMasterMute;
3992
3993 if (masterMute) {
3994 masterVolume = 0;
3995 }
3996 // Delegate master volume control to effect in output mix effect chain if needed
3997 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3998 if (chain != 0) {
3999 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
4000 chain->setVolume_l(&v, &v);
4001 masterVolume = (float)((v + (1 << 23)) >> 24);
4002 chain.clear();
4003 }
4004
4005 // prepare a new state to push
4006 FastMixerStateQueue *sq = NULL;
4007 FastMixerState *state = NULL;
4008 bool didModify = false;
4009 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004010 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004011 sq = mFastMixer->sq();
4012 state = sq->begin();
4013 }
4014
Andy Hung69aed5f2014-02-25 17:24:40 -08004015 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08004016 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08004017
Eric Laurent81784c32012-11-19 14:55:58 -08004018 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07004019 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08004020 if (t == 0) {
4021 continue;
4022 }
4023
4024 // this const just means the local variable doesn't change
4025 Track* const track = t.get();
4026
4027 // process fast tracks
4028 if (track->isFastTrack()) {
4029
4030 // It's theoretically possible (though unlikely) for a fast track to be created
4031 // and then removed within the same normal mix cycle. This is not a problem, as
4032 // the track never becomes active so it's fast mixer slot is never touched.
4033 // The converse, of removing an (active) track and then creating a new track
4034 // at the identical fast mixer slot within the same normal mix cycle,
4035 // is impossible because the slot isn't marked available until the end of each cycle.
4036 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07004037 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08004038 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
4039 FastTrack *fastTrack = &state->mFastTracks[j];
4040
4041 // Determine whether the track is currently in underrun condition,
4042 // and whether it had a recent underrun.
4043 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
4044 FastTrackUnderruns underruns = ftDump->mUnderruns;
4045 uint32_t recentFull = (underruns.mBitFields.mFull -
4046 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
4047 uint32_t recentPartial = (underruns.mBitFields.mPartial -
4048 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
4049 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
4050 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
4051 uint32_t recentUnderruns = recentPartial + recentEmpty;
4052 track->mObservedUnderruns = underruns;
4053 // don't count underruns that occur while stopping or pausing
4054 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07004055 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
4056 recentUnderruns > 0) {
4057 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
4058 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Phil Burk2812d9e2016-01-04 10:34:30 -08004059 } else {
4060 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Eric Laurent81784c32012-11-19 14:55:58 -08004061 }
4062
4063 // This is similar to the state machine for normal tracks,
4064 // with a few modifications for fast tracks.
4065 bool isActive = true;
4066 switch (track->mState) {
4067 case TrackBase::STOPPING_1:
4068 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08004069 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004070 track->mState = TrackBase::STOPPING_2;
4071 }
4072 break;
4073 case TrackBase::PAUSING:
4074 // ramp down is not yet implemented
4075 track->setPaused();
4076 break;
4077 case TrackBase::RESUMING:
4078 // ramp up is not yet implemented
4079 track->mState = TrackBase::ACTIVE;
4080 break;
4081 case TrackBase::ACTIVE:
4082 if (recentFull > 0 || recentPartial > 0) {
4083 // track has provided at least some frames recently: reset retry count
4084 track->mRetryCount = kMaxTrackRetries;
4085 }
4086 if (recentUnderruns == 0) {
4087 // no recent underruns: stay active
4088 break;
4089 }
4090 // there has recently been an underrun of some kind
4091 if (track->sharedBuffer() == 0) {
4092 // were any of the recent underruns "empty" (no frames available)?
4093 if (recentEmpty == 0) {
4094 // no, then ignore the partial underruns as they are allowed indefinitely
4095 break;
4096 }
4097 // there has recently been an "empty" underrun: decrement the retry counter
4098 if (--(track->mRetryCount) > 0) {
4099 break;
4100 }
4101 // indicate to client process that the track was disabled because of underrun;
4102 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004103 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004104 // remove from active list, but state remains ACTIVE [confusing but true]
4105 isActive = false;
4106 break;
4107 }
4108 // fall through
4109 case TrackBase::STOPPING_2:
4110 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08004111 case TrackBase::STOPPED:
4112 case TrackBase::FLUSHED: // flush() while active
4113 // Check for presentation complete if track is inactive
4114 // We have consumed all the buffers of this track.
4115 // This would be incomplete if we auto-paused on underrun
4116 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004117 uint32_t latency = 0;
4118 status_t result = mOutput->stream->getLatency(&latency);
4119 ALOGE_IF(result != OK,
4120 "Error when retrieving output stream latency: %d", result);
4121 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004122 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004123 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
4124 // track stays in active list until presentation is complete
4125 break;
4126 }
4127 }
4128 if (track->isStopping_2()) {
4129 track->mState = TrackBase::STOPPED;
4130 }
4131 if (track->isStopped()) {
4132 // Can't reset directly, as fast mixer is still polling this track
4133 // track->reset();
4134 // So instead mark this track as needing to be reset after push with ack
4135 resetMask |= 1 << i;
4136 }
4137 isActive = false;
4138 break;
4139 case TrackBase::IDLE:
4140 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08004141 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08004142 }
4143
4144 if (isActive) {
4145 // was it previously inactive?
4146 if (!(state->mTrackMask & (1 << j))) {
4147 ExtendedAudioBufferProvider *eabp = track;
4148 VolumeProvider *vp = track;
4149 fastTrack->mBufferProvider = eabp;
4150 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08004151 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07004152 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08004153 fastTrack->mGeneration++;
4154 state->mTrackMask |= 1 << j;
4155 didModify = true;
4156 // no acknowledgement required for newly active tracks
4157 }
4158 // cache the combined master volume and stream type volume for fast mixer; this
4159 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08004160 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08004161 ++fastTracks;
4162 } else {
4163 // was it previously active?
4164 if (state->mTrackMask & (1 << j)) {
4165 fastTrack->mBufferProvider = NULL;
4166 fastTrack->mGeneration++;
4167 state->mTrackMask &= ~(1 << j);
4168 didModify = true;
4169 // If any fast tracks were removed, we must wait for acknowledgement
4170 // because we're about to decrement the last sp<> on those tracks.
4171 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4172 } else {
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08004173 LOG_ALWAYS_FATAL("fast track %d should have been active; "
4174 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
4175 j, track->mState, state->mTrackMask, recentUnderruns,
4176 track->sharedBuffer() != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004177 }
4178 tracksToRemove->add(track);
4179 // Avoids a misleading display in dumpsys
4180 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
4181 }
4182 continue;
4183 }
4184
4185 { // local variable scope to avoid goto warning
4186
4187 audio_track_cblk_t* cblk = track->cblk();
4188
4189 // The first time a track is added we wait
4190 // for all its buffers to be filled before processing it
4191 int name = track->name();
4192 // make sure that we have enough frames to mix one full buffer.
4193 // enforce this condition only once to enable draining the buffer in case the client
4194 // app does not call stop() and relies on underrun to stop:
4195 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
4196 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004197 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07004198 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004199 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004200
4201 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004202 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004203 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
4204 // add frames already consumed but not yet released by the resampler
4205 // because mAudioTrackServerProxy->framesReady() will include these frames
4206 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
4207
Eric Laurent81784c32012-11-19 14:55:58 -08004208 uint32_t minFrames = 1;
4209 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
4210 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004211 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08004212 }
Eric Laurent13e4c962013-12-20 17:36:01 -08004213
4214 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07004215 if (ATRACE_ENABLED()) {
4216 // I wish we had formatted trace names
4217 char traceName[16];
4218 strcpy(traceName, "nRdy");
4219 int name = track->name();
4220 if (AudioMixer::TRACK0 <= name &&
4221 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
4222 name -= AudioMixer::TRACK0;
4223 traceName[4] = (name / 10) + '0';
4224 traceName[5] = (name % 10) + '0';
4225 } else {
4226 traceName[4] = '?';
4227 traceName[5] = '?';
4228 }
4229 traceName[6] = '\0';
4230 ATRACE_INT(traceName, framesReady);
4231 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004232 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08004233 !track->isPaused() && !track->isTerminated())
4234 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004235 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004236
4237 mixedTracks++;
4238
Andy Hung69aed5f2014-02-25 17:24:40 -08004239 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
4240 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08004241 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08004242 if (track->mainBuffer() != mSinkBuffer &&
4243 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004244 if (mEffectBufferEnabled) {
4245 mEffectBufferValid = true; // Later can set directly.
4246 }
Eric Laurent81784c32012-11-19 14:55:58 -08004247 chain = getEffectChain_l(track->sessionId());
4248 // Delegate volume control to effect in track effect chain if needed
4249 if (chain != 0) {
4250 tracksWithEffect++;
4251 } else {
4252 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
4253 "session %d",
4254 name, track->sessionId());
4255 }
4256 }
4257
4258
4259 int param = AudioMixer::VOLUME;
4260 if (track->mFillingUpStatus == Track::FS_FILLED) {
4261 // no ramp for the first volume setting
4262 track->mFillingUpStatus = Track::FS_ACTIVE;
4263 if (track->mState == TrackBase::RESUMING) {
4264 track->mState = TrackBase::ACTIVE;
4265 param = AudioMixer::RAMP_VOLUME;
4266 }
4267 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004268 // FIXME should not make a decision based on mServer
4269 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004270 // If the track is stopped before the first frame was mixed,
4271 // do not apply ramp
4272 param = AudioMixer::RAMP_VOLUME;
4273 }
4274
4275 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07004276 uint32_t vl, vr; // in U8.24 integer format
4277 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08004278 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07004279 vl = vr = 0;
4280 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08004281 if (track->isPausing()) {
4282 track->setPaused();
4283 }
4284 } else {
4285
4286 // read original volumes with volume control
4287 float typeVolume = mStreamTypes[track->streamType()].volume;
4288 float v = masterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07004289 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004290 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07004291 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
4292 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08004293 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07004294 if (vlf > GAIN_FLOAT_UNITY) {
4295 ALOGV("Track left volume out of range: %.3g", vlf);
4296 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004297 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07004298 if (vrf > GAIN_FLOAT_UNITY) {
4299 ALOGV("Track right volume out of range: %.3g", vrf);
4300 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004301 }
4302 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07004303 vlf *= v;
4304 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08004305 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07004306 // then derive vl and vr as U8.24 versions for the effect chain
4307 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
4308 vl = (uint32_t) (scaleto8_24 * vlf);
4309 vr = (uint32_t) (scaleto8_24 * vrf);
4310 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08004311 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08004312 // send level comes from shared memory and so may be corrupt
4313 if (sendLevel > MAX_GAIN_INT) {
4314 ALOGV("Track send level out of range: %04X", sendLevel);
4315 sendLevel = MAX_GAIN_INT;
4316 }
Andy Hung6be49402014-05-30 10:42:03 -07004317 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4318 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08004319 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004320
Eric Laurent81784c32012-11-19 14:55:58 -08004321 // Delegate volume control to effect in track effect chain if needed
4322 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4323 // Do not ramp volume if volume is controlled by effect
4324 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08004325 // Update remaining floating point volume levels
4326 vlf = (float)vl / (1 << 24);
4327 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004328 track->mHasVolumeController = true;
4329 } else {
4330 // force no volume ramp when volume controller was just disabled or removed
4331 // from effect chain to avoid volume spike
4332 if (track->mHasVolumeController) {
4333 param = AudioMixer::VOLUME;
4334 }
4335 track->mHasVolumeController = false;
4336 }
4337
Eric Laurent81784c32012-11-19 14:55:58 -08004338 // XXX: these things DON'T need to be done each time
4339 mAudioMixer->setBufferProvider(name, track);
4340 mAudioMixer->enable(name);
4341
Andy Hung6be49402014-05-30 10:42:03 -07004342 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
4343 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
4344 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004345 mAudioMixer->setParameter(
4346 name,
4347 AudioMixer::TRACK,
4348 AudioMixer::FORMAT, (void *)track->format());
4349 mAudioMixer->setParameter(
4350 name,
4351 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004352 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004353 mAudioMixer->setParameter(
4354 name,
4355 AudioMixer::TRACK,
4356 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004357 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004358 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004359 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004360 if (reqSampleRate == 0) {
4361 reqSampleRate = mSampleRate;
4362 } else if (reqSampleRate > maxSampleRate) {
4363 reqSampleRate = maxSampleRate;
4364 }
Eric Laurent81784c32012-11-19 14:55:58 -08004365 mAudioMixer->setParameter(
4366 name,
4367 AudioMixer::RESAMPLE,
4368 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004369 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004370
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004371 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004372 mAudioMixer->setParameter(
4373 name,
4374 AudioMixer::TIMESTRETCH,
4375 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004376 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004377
Andy Hung69aed5f2014-02-25 17:24:40 -08004378 /*
4379 * Select the appropriate output buffer for the track.
4380 *
Andy Hung98ef9782014-03-04 14:46:50 -08004381 * Tracks with effects go into their own effects chain buffer
4382 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004383 *
4384 * Other tracks can use mMixerBuffer for higher precision
4385 * channel accumulation. If this buffer is enabled
4386 * (mMixerBufferEnabled true), then selected tracks will accumulate
4387 * into it.
4388 *
4389 */
4390 if (mMixerBufferEnabled
4391 && (track->mainBuffer() == mSinkBuffer
4392 || track->mainBuffer() == mMixerBuffer)) {
4393 mAudioMixer->setParameter(
4394 name,
4395 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004396 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004397 mAudioMixer->setParameter(
4398 name,
4399 AudioMixer::TRACK,
4400 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4401 // TODO: override track->mainBuffer()?
4402 mMixerBufferValid = true;
4403 } else {
4404 mAudioMixer->setParameter(
4405 name,
4406 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004407 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004408 mAudioMixer->setParameter(
4409 name,
4410 AudioMixer::TRACK,
4411 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4412 }
Eric Laurent81784c32012-11-19 14:55:58 -08004413 mAudioMixer->setParameter(
4414 name,
4415 AudioMixer::TRACK,
4416 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4417
4418 // reset retry count
4419 track->mRetryCount = kMaxTrackRetries;
4420
4421 // If one track is ready, set the mixer ready if:
4422 // - the mixer was not ready during previous round OR
4423 // - no other track is not ready
4424 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4425 mixerStatus != MIXER_TRACKS_ENABLED) {
4426 mixerStatus = MIXER_TRACKS_READY;
4427 }
4428 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004429 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hung08fb1742015-05-31 23:22:10 -07004430 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)",
4431 track, framesReady, desiredFrames);
Glenn Kasten82aaf942013-07-17 16:05:07 -07004432 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08004433 } else {
4434 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004435 }
Phil Burk2812d9e2016-01-04 10:34:30 -08004436
Eric Laurent81784c32012-11-19 14:55:58 -08004437 // clear effect chain input buffer if an active track underruns to avoid sending
4438 // previous audio buffer again to effects
4439 chain = getEffectChain_l(track->sessionId());
4440 if (chain != 0) {
4441 chain->clearInputBuffer();
4442 }
4443
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004444 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004445 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4446 track->isStopped() || track->isPaused()) {
4447 // We have consumed all the buffers of this track.
4448 // Remove it from the list of active tracks.
4449 // TODO: use actual buffer filling status instead of latency when available from
4450 // audio HAL
4451 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004452 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004453 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4454 if (track->isStopped()) {
4455 track->reset();
4456 }
4457 tracksToRemove->add(track);
4458 }
4459 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004460 // No buffers for this track. Give it a few chances to
4461 // fill a buffer, then remove it from active list.
4462 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004463 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004464 tracksToRemove->add(track);
4465 // indicate to client process that the track was disabled because of underrun;
4466 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004467 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004468 // If one track is not ready, mark the mixer also not ready if:
4469 // - the mixer was ready during previous round OR
4470 // - no other track is ready
4471 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4472 mixerStatus != MIXER_TRACKS_READY) {
4473 mixerStatus = MIXER_TRACKS_ENABLED;
4474 }
4475 }
4476 mAudioMixer->disable(name);
4477 }
4478
4479 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08004480
4481 }
4482
4483 // Push the new FastMixer state if necessary
4484 bool pauseAudioWatchdog = false;
4485 if (didModify) {
4486 state->mFastTracksGen++;
4487 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4488 if (kUseFastMixer == FastMixer_Dynamic &&
4489 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4490 state->mCommand = FastMixerState::COLD_IDLE;
4491 state->mColdFutexAddr = &mFastMixerFutex;
4492 state->mColdGen++;
4493 mFastMixerFutex = 0;
4494 if (kUseFastMixer == FastMixer_Dynamic) {
4495 mNormalSink = mOutputSink;
4496 }
4497 // If we go into cold idle, need to wait for acknowledgement
4498 // so that fast mixer stops doing I/O.
4499 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4500 pauseAudioWatchdog = true;
4501 }
Eric Laurent81784c32012-11-19 14:55:58 -08004502 }
4503 if (sq != NULL) {
4504 sq->end(didModify);
4505 sq->push(block);
4506 }
4507#ifdef AUDIO_WATCHDOG
4508 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4509 mAudioWatchdog->pause();
4510 }
4511#endif
4512
4513 // Now perform the deferred reset on fast tracks that have stopped
4514 while (resetMask != 0) {
4515 size_t i = __builtin_ctz(resetMask);
4516 ALOG_ASSERT(i < count);
4517 resetMask &= ~(1 << i);
4518 sp<Track> t = mActiveTracks[i].promote();
4519 if (t == 0) {
4520 continue;
4521 }
4522 Track* track = t.get();
4523 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4524 track->reset();
4525 }
4526
4527 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004528 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004529
Eric Laurent97d547d2014-09-02 14:45:53 -07004530 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4531 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004532 }
4533
4534 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004535 // as long as there are effects we should clear the effects buffer, to avoid
4536 // passing a non-clean buffer to the effect chain
4537 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004538 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004539 // sink or mix buffer must be cleared if all tracks are connected to an
4540 // effect chain as in this case the mixer will not write to the sink or mix buffer
4541 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004542 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4543 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004544 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004545 if (mMixerBufferValid) {
4546 memset(mMixerBuffer, 0, mMixerBufferSize);
4547 // TODO: In testing, mSinkBuffer below need not be cleared because
4548 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4549 // after mixing.
4550 //
4551 // To enforce this guarantee:
4552 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4553 // (mixedTracks == 0 && fastTracks > 0))
4554 // must imply MIXER_TRACKS_READY.
4555 // Later, we may clear buffers regardless, and skip much of this logic.
4556 }
Andy Hung98ef9782014-03-04 14:46:50 -08004557 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004558 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004559 }
4560
4561 // if any fast tracks, then status is ready
4562 mMixerStatusIgnoringFastTracks = mixerStatus;
4563 if (fastTracks > 0) {
4564 mixerStatus = MIXER_TRACKS_READY;
4565 }
4566 return mixerStatus;
4567}
4568
Eric Laurentad7dd962016-09-22 12:38:37 -07004569// trackCountForUid_l() must be called with ThreadBase::mLock held
4570uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid)
4571{
4572 uint32_t trackCount = 0;
4573 for (size_t i = 0; i < mTracks.size() ; i++) {
4574 if (mTracks[i]->uid() == (int)uid) {
4575 trackCount++;
4576 }
4577 }
4578 return trackCount;
4579}
4580
Eric Laurent81784c32012-11-19 14:55:58 -08004581// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07004582int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
Eric Laurentad7dd962016-09-22 12:38:37 -07004583 audio_format_t format, audio_session_t sessionId, uid_t uid)
Eric Laurent81784c32012-11-19 14:55:58 -08004584{
Eric Laurentad7dd962016-09-22 12:38:37 -07004585 if (trackCountForUid_l(uid) > (PlaybackThread::kMaxTracksPerUid - 1)) {
4586 return -1;
4587 }
Andy Hunge8a1ced2014-05-09 15:02:21 -07004588 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08004589}
4590
4591// deleteTrackName_l() must be called with ThreadBase::mLock held
4592void AudioFlinger::MixerThread::deleteTrackName_l(int name)
4593{
4594 ALOGV("remove track (%d) and delete from mixer", name);
4595 mAudioMixer->deleteTrackName(name);
4596}
4597
Eric Laurent10351942014-05-08 18:49:52 -07004598// checkForNewParameter_l() must be called with ThreadBase::mLock held
4599bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4600 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004601{
Eric Laurent81784c32012-11-19 14:55:58 -08004602 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08004603 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004604
Eric Laurent10351942014-05-08 18:49:52 -07004605 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004606
Glenn Kastenc05b8d72016-03-24 09:48:17 -07004607 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004608
Eric Laurent10351942014-05-08 18:49:52 -07004609 AudioParameter param = AudioParameter(keyValuePair);
4610 int value;
4611 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4612 reconfig = true;
4613 }
4614 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004615 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004616 status = BAD_VALUE;
4617 } else {
4618 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004619 reconfig = true;
4620 }
Eric Laurent10351942014-05-08 18:49:52 -07004621 }
4622 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004623 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004624 status = BAD_VALUE;
4625 } else {
4626 // no need to save value, since it's constant
4627 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004628 }
Eric Laurent10351942014-05-08 18:49:52 -07004629 }
4630 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4631 // do not accept frame count changes if tracks are open as the track buffer
4632 // size depends on frame count and correct behavior would not be guaranteed
4633 // if frame count is changed after track creation
4634 if (!mTracks.isEmpty()) {
4635 status = INVALID_OPERATION;
4636 } else {
4637 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004638 }
Eric Laurent10351942014-05-08 18:49:52 -07004639 }
4640 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004641#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004642 // when changing the audio output device, call addBatteryData to notify
4643 // the change
4644 if (mOutDevice != value) {
4645 uint32_t params = 0;
4646 // check whether speaker is on
4647 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4648 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004649 }
Eric Laurent10351942014-05-08 18:49:52 -07004650
4651 audio_devices_t deviceWithoutSpeaker
4652 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4653 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07004654 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07004655 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4656 }
4657
4658 if (params != 0) {
4659 addBatteryData(params);
4660 }
4661 }
Eric Laurent81784c32012-11-19 14:55:58 -08004662#endif
4663
Eric Laurent10351942014-05-08 18:49:52 -07004664 // forward device change to effects that have requested to be
4665 // aware of attached audio device.
4666 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08004667 a2dpDeviceChanged =
4668 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07004669 mOutDevice = value;
4670 for (size_t i = 0; i < mEffectChains.size(); i++) {
4671 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004672 }
4673 }
Eric Laurent10351942014-05-08 18:49:52 -07004674 }
Eric Laurent81784c32012-11-19 14:55:58 -08004675
Eric Laurent10351942014-05-08 18:49:52 -07004676 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004677 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07004678 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004679 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004680 mStandby = true;
4681 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004682 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08004683 }
Eric Laurent10351942014-05-08 18:49:52 -07004684 if (status == NO_ERROR && reconfig) {
4685 readOutputParameters_l();
4686 delete mAudioMixer;
4687 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4688 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004689 int name = getTrackName_l(mTracks[i]->mChannelMask,
Eric Laurentad7dd962016-09-22 12:38:37 -07004690 mTracks[i]->mFormat, mTracks[i]->mSessionId, mTracks[i]->uid());
Eric Laurent10351942014-05-08 18:49:52 -07004691 if (name < 0) {
4692 break;
4693 }
4694 mTracks[i]->mName = name;
4695 }
Eric Laurent73e26b62015-04-27 16:55:58 -07004696 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004697 }
Eric Laurent81784c32012-11-19 14:55:58 -08004698 }
4699
Eric Laurent42537be2016-01-08 17:16:42 -08004700 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08004701}
4702
4703
4704void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4705{
Eric Laurent81784c32012-11-19 14:55:58 -08004706 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07004707 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Elliott Hughes87cebad2014-05-22 10:14:43 -07004708 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Andy Hung2ddee192015-12-18 17:34:44 -08004709 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent81784c32012-11-19 14:55:58 -08004710
4711 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten2f90c512015-12-02 11:40:09 -08004712 // while we are dumping it. It may be inconsistent, but it won't mutate!
4713 // This is a large object so we place it on the heap.
4714 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
4715 const FastMixerDumpState *copy = new FastMixerDumpState(mFastMixerDumpState);
4716 copy->dump(fd);
4717 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08004718
4719#ifdef STATE_QUEUE_DUMP
4720 // Similar for state queue
4721 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4722 observerCopy.dump(fd);
4723 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4724 mutatorCopy.dump(fd);
4725#endif
4726
Glenn Kasten46909e72013-02-26 09:20:22 -08004727#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004728 // Write the tee output to a .wav file
4729 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08004730#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004731
4732#ifdef AUDIO_WATCHDOG
4733 if (mAudioWatchdog != 0) {
4734 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4735 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4736 wdCopy.dump(fd);
4737 }
4738#endif
4739}
4740
4741uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4742{
4743 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4744}
4745
4746uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4747{
4748 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4749}
4750
4751void AudioFlinger::MixerThread::cacheParameters_l()
4752{
4753 PlaybackThread::cacheParameters_l();
4754
4755 // FIXME: Relaxed timing because of a certain device that can't meet latency
4756 // Should be reduced to 2x after the vendor fixes the driver issue
4757 // increase threshold again due to low power audio mode. The way this warning
4758 // threshold is calculated and its usefulness should be reconsidered anyway.
4759 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4760}
4761
4762// ----------------------------------------------------------------------------
4763
4764AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07004765 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady)
4766 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08004767 // mLeftVolFloat, mRightVolFloat
4768{
4769}
4770
Eric Laurentbfb1b832013-01-07 09:53:42 -08004771AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4772 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurente93cc032016-05-05 10:15:10 -07004773 ThreadBase::type_t type, bool systemReady)
4774 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004775 // mLeftVolFloat, mRightVolFloat
4776{
4777}
4778
Eric Laurent81784c32012-11-19 14:55:58 -08004779AudioFlinger::DirectOutputThread::~DirectOutputThread()
4780{
4781}
4782
Eric Laurentbfb1b832013-01-07 09:53:42 -08004783void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
4784{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004785 float left, right;
4786
4787 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4788 left = right = 0;
4789 } else {
4790 float typeVolume = mStreamTypes[track->streamType()].volume;
4791 float v = mMasterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07004792 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004793 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4794 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4795 if (left > GAIN_FLOAT_UNITY) {
4796 left = GAIN_FLOAT_UNITY;
4797 }
4798 left *= v;
4799 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4800 if (right > GAIN_FLOAT_UNITY) {
4801 right = GAIN_FLOAT_UNITY;
4802 }
4803 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004804 }
4805
4806 if (lastTrack) {
4807 if (left != mLeftVolFloat || right != mRightVolFloat) {
4808 mLeftVolFloat = left;
4809 mRightVolFloat = right;
4810
4811 // Convert volumes from float to 8.24
4812 uint32_t vl = (uint32_t)(left * (1 << 24));
4813 uint32_t vr = (uint32_t)(right * (1 << 24));
4814
4815 // Delegate volume control to effect in track effect chain if needed
4816 // only one effect chain can be present on DirectOutputThread, so if
4817 // there is one, the track is connected to it
4818 if (!mEffectChains.isEmpty()) {
4819 mEffectChains[0]->setVolume_l(&vl, &vr);
4820 left = (float)vl / (1 << 24);
4821 right = (float)vr / (1 << 24);
4822 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004823 status_t result = mOutput->stream->setVolume(left, right);
4824 ALOGE_IF(result != OK, "Error when setting output stream volume: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004825 }
4826 }
4827}
4828
Phil Burk43b4dcc2015-06-09 16:53:44 -07004829void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
4830{
4831 sp<Track> previousTrack = mPreviousTrack.promote();
4832 sp<Track> latestTrack = mLatestActiveTrack.promote();
4833
Eric Laurent0f0631e2015-07-06 18:01:25 -07004834 if (previousTrack != 0 && latestTrack != 0) {
4835 if (mType == DIRECT) {
4836 if (previousTrack.get() != latestTrack.get()) {
4837 mFlushPending = true;
4838 }
4839 } else /* mType == OFFLOAD */ {
4840 if (previousTrack->sessionId() != latestTrack->sessionId()) {
4841 mFlushPending = true;
4842 }
4843 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004844 }
4845 PlaybackThread::onAddNewTrack_l();
4846}
Eric Laurentbfb1b832013-01-07 09:53:42 -08004847
Eric Laurent81784c32012-11-19 14:55:58 -08004848AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4849 Vector< sp<Track> > *tracksToRemove
4850)
4851{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004852 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004853 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004854 bool doHwPause = false;
4855 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004856
4857 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07004858 for (size_t i = 0; i < count; i++) {
4859 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08004860 // The track died recently
4861 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004862 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08004863 }
4864
Phil Burk43b4dcc2015-06-09 16:53:44 -07004865 if (t->isInvalid()) {
4866 ALOGW("An invalidated track shouldn't be in active list");
4867 tracksToRemove->add(t);
4868 continue;
4869 }
4870
Eric Laurent81784c32012-11-19 14:55:58 -08004871 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004872#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08004873 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004874#endif
Eric Laurentfd477972013-10-25 18:10:40 -07004875 // Only consider last track started for volume and mixer state control.
4876 // In theory an older track could underrun and restart after the new one starts
4877 // but as we only care about the transition phase between two tracks on a
4878 // direct output, it is not a problem to ignore the underrun case.
4879 sp<Track> l = mLatestActiveTrack.promote();
4880 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004881
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004882 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004883 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004884 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004885 doHwPause = true;
4886 mHwPaused = true;
4887 }
4888 tracksToRemove->add(track);
4889 } else if (track->isFlushPending()) {
4890 track->flushAck();
4891 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004892 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004893 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004894 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004895 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07004896 if (last) {
4897 mLeftVolFloat = mRightVolFloat = -1.0;
4898 if (mHwPaused) {
4899 doHwResume = true;
4900 mHwPaused = false;
4901 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004902 }
4903 }
4904
Eric Laurent81784c32012-11-19 14:55:58 -08004905 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004906 // for all its buffers to be filled before processing it.
4907 // Allow draining the buffer in case the client
4908 // app does not call stop() and relies on underrun to stop:
4909 // hence the test on (track->mRetryCount > 1).
4910 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07004911 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08004912 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004913 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08004914 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004915 minFrames = mNormalFrameCount;
4916 } else {
4917 minFrames = 1;
4918 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004919
Eric Laurentab5cdba2014-06-09 17:22:27 -07004920 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4921 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004922 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004923 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004924
4925 if (track->mFillingUpStatus == Track::FS_FILLED) {
4926 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07004927 if (last) {
4928 // make sure processVolume_l() will apply new volume even if 0
4929 mLeftVolFloat = mRightVolFloat = -1.0;
4930 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004931 if (!mHwSupportsPause) {
4932 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004933 }
4934 }
4935
4936 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004937 processVolume_l(track, last);
4938 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004939 sp<Track> previousTrack = mPreviousTrack.promote();
4940 if (previousTrack != 0) {
4941 if (track != previousTrack.get()) {
4942 // Flush any data still being written from last track
4943 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07004944 // Invalidate previous track to force a seek when resuming.
4945 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004946 }
4947 }
4948 mPreviousTrack = track;
4949
Eric Laurentd595b7c2013-04-03 17:27:56 -07004950 // reset retry count
4951 track->mRetryCount = kMaxTrackRetriesDirect;
4952 mActiveTrack = t;
4953 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07004954 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004955 doHwResume = true;
4956 mHwPaused = false;
4957 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004958 }
Eric Laurent81784c32012-11-19 14:55:58 -08004959 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004960 // clear effect chain input buffer if the last active track started underruns
4961 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004962 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004963 mEffectChains[0]->clearInputBuffer();
4964 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004965 if (track->isStopping_1()) {
4966 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07004967 if (last && mHwPaused) {
4968 doHwResume = true;
4969 mHwPaused = false;
4970 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004971 }
4972 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4973 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004974 // We have consumed all the buffers of this track.
4975 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004976 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08004977 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004978 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4979 } else {
4980 audioHALFrames = 0;
4981 }
4982
Andy Hung818e7a32016-02-16 18:08:07 -08004983 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004984 if (mStandby || !last ||
4985 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004986 if (track->isStopping_2()) {
4987 track->mState = TrackBase::STOPPED;
4988 }
Eric Laurent81784c32012-11-19 14:55:58 -08004989 if (track->isStopped()) {
4990 track->reset();
4991 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004992 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004993 }
4994 } else {
4995 // No buffers for this track. Give it a few chances to
4996 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004997 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004998 if (--(track->mRetryCount) <= 0) {
4999 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07005000 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005001 // indicate to client process that the track was disabled because of underrun;
5002 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005003 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005004 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07005005 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
5006 "minFrames = %u, mFormat = %#x",
5007 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08005008 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07005009 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005010 doHwPause = true;
5011 mHwPaused = true;
5012 }
Eric Laurent81784c32012-11-19 14:55:58 -08005013 }
5014 }
5015 }
5016 }
5017
Eric Laurentd1f69b02014-12-15 14:33:13 -08005018 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07005019 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005020 for (size_t i = 0; i < mTracks.size(); i++) {
5021 if (mTracks[i]->isFlushPending()) {
5022 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005023 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005024 }
5025 }
5026 }
5027
5028 // make sure the pause/flush/resume sequence is executed in the right order.
5029 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5030 // before flush and then resume HW. This can happen in case of pause/flush/resume
5031 // if resume is received before pause is executed.
5032 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07005033 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005034 status_t result = mOutput->stream->pause();
5035 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005036 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005037 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005038 flushHw_l();
5039 }
5040 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005041 status_t result = mOutput->stream->resume();
5042 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005043 }
Eric Laurent81784c32012-11-19 14:55:58 -08005044 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005045 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005046
5047 return mixerStatus;
5048}
5049
5050void AudioFlinger::DirectOutputThread::threadLoop_mix()
5051{
Eric Laurent81784c32012-11-19 14:55:58 -08005052 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08005053 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005054 // output audio to hardware
5055 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07005056 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005057 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08005058 status_t status = mActiveTrack->getNextBuffer(&buffer);
5059 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08005060 // no need to pad with 0 for compressed audio
5061 if (audio_has_proportional_frames(mFormat)) {
5062 memset(curBuf, 0, frameCount * mFrameSize);
5063 }
Eric Laurent81784c32012-11-19 14:55:58 -08005064 break;
5065 }
5066 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
5067 frameCount -= buffer.frameCount;
5068 curBuf += buffer.frameCount * mFrameSize;
5069 mActiveTrack->releaseBuffer(&buffer);
5070 }
Andy Hung2098f272014-02-27 14:00:06 -08005071 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005072 mSleepTimeUs = 0;
5073 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005074 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005075}
5076
5077void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
5078{
Eric Laurentd1f69b02014-12-15 14:33:13 -08005079 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005080 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005081 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005082 return;
5083 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005084 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005085 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurente93cc032016-05-05 10:15:10 -07005086 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005087 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005088 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005089 }
Phil Burkfdb3c072016-02-09 10:47:02 -08005090 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08005091 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005092 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005093 }
5094}
5095
Eric Laurentd1f69b02014-12-15 14:33:13 -08005096void AudioFlinger::DirectOutputThread::threadLoop_exit()
5097{
5098 {
5099 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005100 for (size_t i = 0; i < mTracks.size(); i++) {
5101 if (mTracks[i]->isFlushPending()) {
5102 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005103 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005104 }
5105 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005106 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005107 flushHw_l();
5108 }
5109 }
5110 PlaybackThread::threadLoop_exit();
5111}
5112
5113// must be called with thread mutex locked
5114bool AudioFlinger::DirectOutputThread::shouldStandby_l()
5115{
5116 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07005117 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005118
vivek mehta9cd7ad12016-03-17 00:18:29 -07005119 if ((mType == DIRECT) && audio_is_linear_pcm(mFormat) && !usesHwAvSync()) {
5120 return !mStandby;
5121 }
5122
Eric Laurentd1f69b02014-12-15 14:33:13 -08005123 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
5124 // after a timeout and we will enter standby then.
5125 if (mTracks.size() > 0) {
5126 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07005127 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
5128 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005129 }
5130
Eric Laurent5cff4032015-05-26 13:49:58 -07005131 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08005132}
5133
Eric Laurent81784c32012-11-19 14:55:58 -08005134// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005135int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Eric Laurentad7dd962016-09-22 12:38:37 -07005136 audio_format_t format __unused, audio_session_t sessionId __unused, uid_t uid)
Eric Laurent81784c32012-11-19 14:55:58 -08005137{
Eric Laurentad7dd962016-09-22 12:38:37 -07005138 if (trackCountForUid_l(uid) > (PlaybackThread::kMaxTracksPerUid - 1)) {
5139 return -1;
5140 }
Eric Laurent81784c32012-11-19 14:55:58 -08005141 return 0;
5142}
5143
5144// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005145void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005146{
5147}
5148
Eric Laurent10351942014-05-08 18:49:52 -07005149// checkForNewParameter_l() must be called with ThreadBase::mLock held
5150bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
5151 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005152{
5153 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005154 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005155
Eric Laurent10351942014-05-08 18:49:52 -07005156 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005157
Eric Laurent10351942014-05-08 18:49:52 -07005158 AudioParameter param = AudioParameter(keyValuePair);
5159 int value;
5160 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5161 // forward device change to effects that have requested to be
5162 // aware of attached audio device.
5163 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005164 a2dpDeviceChanged =
5165 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005166 mOutDevice = value;
5167 for (size_t i = 0; i < mEffectChains.size(); i++) {
5168 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07005169 }
5170 }
Eric Laurent81784c32012-11-19 14:55:58 -08005171 }
Eric Laurent10351942014-05-08 18:49:52 -07005172 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5173 // do not accept frame count changes if tracks are open as the track buffer
5174 // size depends on frame count and correct behavior would not be garantied
5175 // if frame count is changed after track creation
5176 if (!mTracks.isEmpty()) {
5177 status = INVALID_OPERATION;
5178 } else {
5179 reconfig = true;
5180 }
5181 }
5182 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005183 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005184 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005185 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005186 mStandby = true;
5187 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005188 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005189 }
5190 if (status == NO_ERROR && reconfig) {
5191 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07005192 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005193 }
5194 }
5195
Eric Laurent42537be2016-01-08 17:16:42 -08005196 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005197}
5198
5199uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
5200{
5201 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005202 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005203 time = PlaybackThread::activeSleepTimeUs();
5204 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005205 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005206 }
5207 return time;
5208}
5209
5210uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
5211{
5212 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005213 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005214 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
5215 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005216 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005217 }
5218 return time;
5219}
5220
5221uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
5222{
5223 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005224 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005225 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
5226 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005227 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005228 }
5229 return time;
5230}
5231
5232void AudioFlinger::DirectOutputThread::cacheParameters_l()
5233{
5234 PlaybackThread::cacheParameters_l();
5235
5236 // use shorter standby delay as on normal output to release
5237 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07005238 // no delay on outputs with HW A/V sync
5239 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005240 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08005241 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005242 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07005243 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005244 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07005245 }
Eric Laurent81784c32012-11-19 14:55:58 -08005246}
5247
Eric Laurente659ef42014-09-29 13:06:46 -07005248void AudioFlinger::DirectOutputThread::flushHw_l()
5249{
Phil Burk062e67a2015-02-11 13:40:50 -08005250 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08005251 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005252 mFlushPending = false;
Eric Laurente659ef42014-09-29 13:06:46 -07005253}
5254
Eric Laurent81784c32012-11-19 14:55:58 -08005255// ----------------------------------------------------------------------------
5256
Eric Laurentbfb1b832013-01-07 09:53:42 -08005257AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07005258 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005259 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07005260 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07005261 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005262 mDrainSequence(0),
5263 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005264{
5265}
5266
5267AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
5268{
5269}
5270
5271void AudioFlinger::AsyncCallbackThread::onFirstRef()
5272{
5273 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
5274}
5275
5276bool AudioFlinger::AsyncCallbackThread::threadLoop()
5277{
5278 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005279 uint32_t writeAckSequence;
5280 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005281 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005282
5283 {
5284 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005285 while (!((mWriteAckSequence & 1) ||
5286 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005287 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005288 exitPending())) {
5289 mWaitWorkCV.wait(mLock);
5290 }
5291
Eric Laurentbfb1b832013-01-07 09:53:42 -08005292 if (exitPending()) {
5293 break;
5294 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005295 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
5296 mWriteAckSequence, mDrainSequence);
5297 writeAckSequence = mWriteAckSequence;
5298 mWriteAckSequence &= ~1;
5299 drainSequence = mDrainSequence;
5300 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005301 asyncError = mAsyncError;
5302 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005303 }
5304 {
Eric Laurent4de95592013-09-26 15:28:21 -07005305 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
5306 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005307 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005308 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005309 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005310 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005311 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005312 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005313 if (asyncError) {
5314 playbackThread->onAsyncError();
5315 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005316 }
5317 }
5318 }
5319 return false;
5320}
5321
5322void AudioFlinger::AsyncCallbackThread::exit()
5323{
5324 ALOGV("AsyncCallbackThread::exit");
5325 Mutex::Autolock _l(mLock);
5326 requestExit();
5327 mWaitWorkCV.broadcast();
5328}
5329
Eric Laurent3b4529e2013-09-05 18:09:19 -07005330void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005331{
5332 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005333 // bit 0 is cleared
5334 mWriteAckSequence = sequence << 1;
5335}
5336
5337void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5338{
5339 Mutex::Autolock _l(mLock);
5340 // ignore unexpected callbacks
5341 if (mWriteAckSequence & 2) {
5342 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005343 mWaitWorkCV.signal();
5344 }
5345}
5346
Eric Laurent3b4529e2013-09-05 18:09:19 -07005347void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005348{
5349 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005350 // bit 0 is cleared
5351 mDrainSequence = sequence << 1;
5352}
5353
5354void AudioFlinger::AsyncCallbackThread::resetDraining()
5355{
5356 Mutex::Autolock _l(mLock);
5357 // ignore unexpected callbacks
5358 if (mDrainSequence & 2) {
5359 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005360 mWaitWorkCV.signal();
5361 }
5362}
5363
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005364void AudioFlinger::AsyncCallbackThread::setAsyncError()
5365{
5366 Mutex::Autolock _l(mLock);
5367 mAsyncError = true;
5368 mWaitWorkCV.signal();
5369}
5370
Eric Laurentbfb1b832013-01-07 09:53:42 -08005371
5372// ----------------------------------------------------------------------------
5373AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07005374 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
5375 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07005376 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
5377 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005378{
Eric Laurentfd477972013-10-25 18:10:40 -07005379 //FIXME: mStandby should be set to true by ThreadBase constructor
5380 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07005381 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005382}
5383
Eric Laurentbfb1b832013-01-07 09:53:42 -08005384void AudioFlinger::OffloadThread::threadLoop_exit()
5385{
5386 if (mFlushPending || mHwPaused) {
5387 // If a flush is pending or track was paused, just discard buffered data
5388 flushHw_l();
5389 } else {
5390 mMixerStatus = MIXER_DRAIN_ALL;
5391 threadLoop_drain();
5392 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005393 if (mUseAsyncWrite) {
5394 ALOG_ASSERT(mCallbackThread != 0);
5395 mCallbackThread->exit();
5396 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005397 PlaybackThread::threadLoop_exit();
5398}
5399
5400AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5401 Vector< sp<Track> > *tracksToRemove
5402)
5403{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005404 size_t count = mActiveTracks.size();
5405
5406 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005407 bool doHwPause = false;
5408 bool doHwResume = false;
5409
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005410 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07005411
Eric Laurentbfb1b832013-01-07 09:53:42 -08005412 // find out which tracks need to be processed
5413 for (size_t i = 0; i < count; i++) {
5414 sp<Track> t = mActiveTracks[i].promote();
5415 // The track died recently
5416 if (t == 0) {
5417 continue;
5418 }
5419 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005420#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08005421 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005422#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005423 // Only consider last track started for volume and mixer state control.
5424 // In theory an older track could underrun and restart after the new one starts
5425 // but as we only care about the transition phase between two tracks on a
5426 // direct output, it is not a problem to ignore the underrun case.
5427 sp<Track> l = mLatestActiveTrack.promote();
5428 bool last = l.get() == track;
5429
Haynes Mathew George7844f672014-01-15 12:32:55 -08005430 if (track->isInvalid()) {
5431 ALOGW("An invalidated track shouldn't be in active list");
5432 tracksToRemove->add(track);
5433 continue;
5434 }
5435
5436 if (track->mState == TrackBase::IDLE) {
5437 ALOGW("An idle track shouldn't be in active list");
5438 continue;
5439 }
5440
Eric Laurentbfb1b832013-01-07 09:53:42 -08005441 if (track->isPausing()) {
5442 track->setPaused();
5443 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005444 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005445 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005446 mHwPaused = true;
5447 }
5448 // If we were part way through writing the mixbuffer to
5449 // the HAL we must save this until we resume
5450 // BUG - this will be wrong if a different track is made active,
5451 // in that case we want to discard the pending data in the
5452 // mixbuffer and tell the client to present it again when the
5453 // track is resumed
5454 mPausedWriteLength = mCurrentWriteLength;
5455 mPausedBytesRemaining = mBytesRemaining;
5456 mBytesRemaining = 0; // stop writing
5457 }
5458 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005459 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005460 if (track->isStopping_1()) {
5461 track->mRetryCount = kMaxTrackStopRetriesOffload;
5462 } else {
5463 track->mRetryCount = kMaxTrackRetriesOffload;
5464 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08005465 track->flushAck();
5466 if (last) {
5467 mFlushPending = true;
5468 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005469 } else if (track->isResumePending()){
5470 track->resumeAck();
5471 if (last) {
5472 if (mPausedBytesRemaining) {
5473 // Need to continue write that was interrupted
5474 mCurrentWriteLength = mPausedWriteLength;
5475 mBytesRemaining = mPausedBytesRemaining;
5476 mPausedBytesRemaining = 0;
5477 }
5478 if (mHwPaused) {
5479 doHwResume = true;
5480 mHwPaused = false;
5481 // threadLoop_mix() will handle the case that we need to
5482 // resume an interrupted write
5483 }
5484 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005485 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005486
Eric Laurent3df841a2016-07-15 15:15:40 -07005487 mLeftVolFloat = mRightVolFloat = -1.0;
5488
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005489 // Do not handle new data in this iteration even if track->framesReady()
5490 mixerStatus = MIXER_TRACKS_ENABLED;
5491 }
5492 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005493 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005494 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005495 if (track->mFillingUpStatus == Track::FS_FILLED) {
5496 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005497 if (last) {
5498 // make sure processVolume_l() will apply new volume even if 0
5499 mLeftVolFloat = mRightVolFloat = -1.0;
5500 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005501 }
5502
5503 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005504 sp<Track> previousTrack = mPreviousTrack.promote();
5505 if (previousTrack != 0) {
5506 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005507 // Flush any data still being written from last track
5508 mBytesRemaining = 0;
5509 if (mPausedBytesRemaining) {
5510 // Last track was paused so we also need to flush saved
5511 // mixbuffer state and invalidate track so that it will
5512 // re-submit that unwritten data when it is next resumed
5513 mPausedBytesRemaining = 0;
5514 // Invalidate is a bit drastic - would be more efficient
5515 // to have a flag to tell client that some of the
5516 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005517 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005518 }
5519 // flush data already sent to the DSP if changing audio session as audio
5520 // comes from a different source. Also invalidate previous track to force a
5521 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005522 if (previousTrack->sessionId() != track->sessionId()) {
5523 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005524 }
5525 }
5526 }
5527 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005528 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07005529 if (track->isStopping_1()) {
5530 track->mRetryCount = kMaxTrackStopRetriesOffload;
5531 } else {
5532 track->mRetryCount = kMaxTrackRetriesOffload;
5533 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005534 mActiveTrack = t;
5535 mixerStatus = MIXER_TRACKS_READY;
5536 }
5537 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005538 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005539 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005540 if (--(track->mRetryCount) <= 0) {
5541 // Hardware buffer can hold a large amount of audio so we must
5542 // wait for all current track's data to drain before we say
5543 // that the track is stopped.
5544 if (mBytesRemaining == 0) {
5545 // Only start draining when all data in mixbuffer
5546 // has been written
5547 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5548 track->mState = TrackBase::STOPPING_2; // so presentation completes after
5549 // drain do not drain if no data was ever sent to HAL (mStandby == true)
5550 if (last && !mStandby) {
5551 // do not modify drain sequence if we are already draining. This happens
5552 // when resuming from pause after drain.
5553 if ((mDrainSequence & 1) == 0) {
5554 mSleepTimeUs = 0;
5555 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
5556 mixerStatus = MIXER_DRAIN_TRACK;
5557 mDrainSequence += 2;
5558 }
5559 if (mHwPaused) {
5560 // It is possible to move from PAUSED to STOPPING_1 without
5561 // a resume so we must ensure hardware is running
5562 doHwResume = true;
5563 mHwPaused = false;
5564 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005565 }
5566 }
Eric Laurente93cc032016-05-05 10:15:10 -07005567 } else if (last) {
5568 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
5569 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005570 }
5571 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005572 // Drain has completed or we are in standby, signal presentation complete
5573 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005574 track->mState = TrackBase::STOPPED;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005575 uint32_t latency = 0;
5576 status_t result = mOutput->stream->getLatency(&latency);
5577 ALOGE_IF(result != OK,
5578 "Error when retrieving output stream latency: %d", result);
5579 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005580 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005581 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005582 track->presentationComplete(framesWritten, audioHALFrames);
5583 track->reset();
5584 tracksToRemove->add(track);
5585 }
5586 } else {
5587 // No buffers for this track. Give it a few chances to
5588 // fill a buffer, then remove it from active list.
5589 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07005590 bool running = false;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005591 uint64_t position = 0;
5592 struct timespec unused;
5593 // The running check restarts the retry counter at least once.
5594 status_t ret = mOutput->stream->getPresentationPosition(&position, &unused);
5595 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
5596 running = true;
5597 mOffloadUnderrunPosition = position;
5598 }
5599 if (ret == NO_ERROR) {
Andy Hungf8044752016-07-27 14:58:11 -07005600 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
5601 (long long)position, (long long)mOffloadUnderrunPosition);
5602 }
5603 if (running) { // still running, give us more time.
5604 track->mRetryCount = kMaxTrackRetriesOffload;
5605 } else {
5606 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5607 track->name());
5608 tracksToRemove->add(track);
5609 // indicate to client process that the track was disabled because of underrun;
5610 // it will then automatically call start() when data is available
5611 track->disable();
5612 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005613 } else if (last){
5614 mixerStatus = MIXER_TRACKS_ENABLED;
5615 }
5616 }
5617 }
5618 // compute volume for this track
5619 processVolume_l(track, last);
5620 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005621
Eric Laurentea0fade2013-10-04 16:23:48 -07005622 // make sure the pause/flush/resume sequence is executed in the right order.
5623 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5624 // before flush and then resume HW. This can happen in case of pause/flush/resume
5625 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07005626 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005627 status_t result = mOutput->stream->pause();
5628 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07005629 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005630 if (mFlushPending) {
5631 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005632 }
Eric Laurentfd477972013-10-25 18:10:40 -07005633 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005634 status_t result = mOutput->stream->resume();
5635 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07005636 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005637
Eric Laurentbfb1b832013-01-07 09:53:42 -08005638 // remove all the tracks that need to be...
5639 removeTracks_l(*tracksToRemove);
5640
5641 return mixerStatus;
5642}
5643
Eric Laurentbfb1b832013-01-07 09:53:42 -08005644// must be called with thread mutex locked
5645bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5646{
Eric Laurent3b4529e2013-09-05 18:09:19 -07005647 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5648 mWriteAckSequence, mDrainSequence);
5649 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005650 return true;
5651 }
5652 return false;
5653}
5654
Eric Laurentbfb1b832013-01-07 09:53:42 -08005655bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5656{
5657 Mutex::Autolock _l(mLock);
5658 return waitingAsyncCallback_l();
5659}
5660
5661void AudioFlinger::OffloadThread::flushHw_l()
5662{
Eric Laurente659ef42014-09-29 13:06:46 -07005663 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005664 // Flush anything still waiting in the mixbuffer
5665 mCurrentWriteLength = 0;
5666 mBytesRemaining = 0;
5667 mPausedWriteLength = 0;
5668 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07005669 // reset bytes written count to reflect that DSP buffers are empty after flush.
5670 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07005671 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08005672
Eric Laurentbfb1b832013-01-07 09:53:42 -08005673 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005674 // discard any pending drain or write ack by incrementing sequence
5675 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5676 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005677 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005678 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5679 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005680 }
5681}
5682
Haynes Mathew George05317d22016-05-03 16:34:26 -07005683void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
5684{
5685 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07005686 if (PlaybackThread::invalidateTracks_l(streamType)) {
5687 mFlushPending = true;
5688 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07005689}
5690
Eric Laurentbfb1b832013-01-07 09:53:42 -08005691// ----------------------------------------------------------------------------
5692
Eric Laurent81784c32012-11-19 14:55:58 -08005693AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005694 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005695 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07005696 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08005697 mWaitTimeMs(UINT_MAX)
5698{
5699 addOutputTrack(mainThread);
5700}
5701
5702AudioFlinger::DuplicatingThread::~DuplicatingThread()
5703{
5704 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5705 mOutputTracks[i]->destroy();
5706 }
5707}
5708
5709void AudioFlinger::DuplicatingThread::threadLoop_mix()
5710{
5711 // mix buffers...
5712 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08005713 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08005714 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005715 if (mMixerBufferValid) {
5716 memset(mMixerBuffer, 0, mMixerBufferSize);
5717 } else {
5718 memset(mSinkBuffer, 0, mSinkBufferSize);
5719 }
Eric Laurent81784c32012-11-19 14:55:58 -08005720 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005721 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005722 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005723 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005724 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005725}
5726
5727void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5728{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005729 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005730 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005731 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005732 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005733 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005734 }
5735 } else if (mBytesWritten != 0) {
5736 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5737 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005738 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005739 } else {
5740 // flush remaining overflow buffers in output tracks
5741 writeFrames = 0;
5742 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005743 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005744 }
5745}
5746
Eric Laurentbfb1b832013-01-07 09:53:42 -08005747ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005748{
5749 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005750 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005751 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005752 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005753 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005754}
5755
5756void AudioFlinger::DuplicatingThread::threadLoop_standby()
5757{
5758 // DuplicatingThread implements standby by stopping all tracks
5759 for (size_t i = 0; i < outputTracks.size(); i++) {
5760 outputTracks[i]->stop();
5761 }
5762}
5763
5764void AudioFlinger::DuplicatingThread::saveOutputTracks()
5765{
5766 outputTracks = mOutputTracks;
5767}
5768
5769void AudioFlinger::DuplicatingThread::clearOutputTracks()
5770{
5771 outputTracks.clear();
5772}
5773
5774void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5775{
5776 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005777 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5778 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5779 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5780 const size_t frameCount =
5781 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5782 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5783 // from different OutputTracks and their associated MixerThreads (e.g. one may
5784 // nearly empty and the other may be dropping data).
5785
5786 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005787 this,
5788 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005789 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005790 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005791 frameCount,
5792 IPCThreadState::self()->getCallingUid());
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07005793 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
5794 if (status != NO_ERROR) {
5795 ALOGE("addOutputTrack() initCheck failed %d", status);
5796 return;
Eric Laurent81784c32012-11-19 14:55:58 -08005797 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07005798 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
5799 mOutputTracks.add(outputTrack);
5800 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
5801 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005802}
5803
5804void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5805{
5806 Mutex::Autolock _l(mLock);
5807 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5808 if (mOutputTracks[i]->thread() == thread) {
5809 mOutputTracks[i]->destroy();
5810 mOutputTracks.removeAt(i);
5811 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07005812 if (thread->getOutput() == mOutput) {
5813 mOutput = NULL;
5814 }
Eric Laurent81784c32012-11-19 14:55:58 -08005815 return;
5816 }
5817 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07005818 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005819}
5820
5821// caller must hold mLock
5822void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5823{
5824 mWaitTimeMs = UINT_MAX;
5825 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5826 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5827 if (strong != 0) {
5828 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5829 if (waitTimeMs < mWaitTimeMs) {
5830 mWaitTimeMs = waitTimeMs;
5831 }
5832 }
5833 }
5834}
5835
5836
5837bool AudioFlinger::DuplicatingThread::outputsReady(
5838 const SortedVector< sp<OutputTrack> > &outputTracks)
5839{
5840 for (size_t i = 0; i < outputTracks.size(); i++) {
5841 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5842 if (thread == 0) {
5843 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5844 outputTracks[i].get());
5845 return false;
5846 }
5847 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5848 // see note at standby() declaration
5849 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5850 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5851 thread.get());
5852 return false;
5853 }
5854 }
5855 return true;
5856}
5857
5858uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5859{
5860 return (mWaitTimeMs * 1000) / 2;
5861}
5862
5863void AudioFlinger::DuplicatingThread::cacheParameters_l()
5864{
5865 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5866 updateWaitTime_l();
5867
5868 MixerThread::cacheParameters_l();
5869}
5870
5871// ----------------------------------------------------------------------------
5872// Record
5873// ----------------------------------------------------------------------------
5874
5875AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5876 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005877 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005878 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07005879 audio_devices_t inDevice,
5880 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08005881#ifdef TEE_SINK
5882 , const sp<NBAIO_Sink>& teeSink
5883#endif
5884 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07005885 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005886 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07005887 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005888 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005889#ifdef TEE_SINK
5890 , mTeeSink(teeSink)
5891#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005892 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5893 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005894 // mFastCapture below
5895 , mFastCaptureFutex(0)
5896 // mInputSource
5897 // mPipeSink
5898 // mPipeSource
5899 , mPipeFramesP2(0)
5900 // mPipeMemory
5901 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005902 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005903{
Glenn Kastend7dca052015-03-05 16:05:54 -08005904 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5905 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08005906
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005907 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005908
5909 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07005910 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005911 size_t numCounterOffers = 0;
5912 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005913#if !LOG_NDEBUG
5914 ssize_t index =
5915#else
5916 (void)
5917#endif
5918 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005919 ALOG_ASSERT(index == 0);
5920
5921 // initialize fast capture depending on configuration
5922 bool initFastCapture;
5923 switch (kUseFastCapture) {
5924 case FastCapture_Never:
5925 initFastCapture = false;
5926 break;
5927 case FastCapture_Always:
5928 initFastCapture = true;
5929 break;
5930 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07005931 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005932 break;
5933 // case FastCapture_Dynamic:
5934 }
5935
5936 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07005937 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005938 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07005939 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
5940 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005941 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5942 void *pipeBuffer;
5943 const sp<MemoryDealer> roHeap(readOnlyHeap());
5944 sp<IMemory> pipeMemory;
5945 if ((roHeap == 0) ||
5946 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5947 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5948 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5949 goto failed;
5950 }
5951 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5952 memset(pipeBuffer, 0, pipeSize);
5953 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5954 const NBAIO_Format offers[1] = {format};
5955 size_t numCounterOffers = 0;
5956 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5957 ALOG_ASSERT(index == 0);
5958 mPipeSink = pipe;
5959 PipeReader *pipeReader = new PipeReader(*pipe);
5960 numCounterOffers = 0;
5961 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5962 ALOG_ASSERT(index == 0);
5963 mPipeSource = pipeReader;
5964 mPipeFramesP2 = pipeFramesP2;
5965 mPipeMemory = pipeMemory;
5966
5967 // create fast capture
5968 mFastCapture = new FastCapture();
5969 FastCaptureStateQueue *sq = mFastCapture->sq();
5970#ifdef STATE_QUEUE_DUMP
5971 // FIXME
5972#endif
5973 FastCaptureState *state = sq->begin();
5974 state->mCblk = NULL;
5975 state->mInputSource = mInputSource.get();
5976 state->mInputSourceGen++;
5977 state->mPipeSink = pipe;
5978 state->mPipeSinkGen++;
5979 state->mFrameCount = mFrameCount;
5980 state->mCommand = FastCaptureState::COLD_IDLE;
5981 // already done in constructor initialization list
5982 //mFastCaptureFutex = 0;
5983 state->mColdFutexAddr = &mFastCaptureFutex;
5984 state->mColdGen++;
5985 state->mDumpState = &mFastCaptureDumpState;
5986#ifdef TEE_SINK
5987 // FIXME
5988#endif
5989 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
5990 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
5991 sq->end();
5992 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5993
5994 // start the fast capture
5995 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
5996 pid_t tid = mFastCapture->getTid();
Glenn Kasten8379b722016-03-18 14:54:17 -07005997 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005998#ifdef AUDIO_WATCHDOG
5999 // FIXME
6000#endif
6001
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006002 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006003 }
6004failed: ;
6005
6006 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08006007}
6008
Eric Laurent81784c32012-11-19 14:55:58 -08006009AudioFlinger::RecordThread::~RecordThread()
6010{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006011 if (mFastCapture != 0) {
6012 FastCaptureStateQueue *sq = mFastCapture->sq();
6013 FastCaptureState *state = sq->begin();
6014 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6015 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6016 if (old == -1) {
6017 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6018 }
6019 }
6020 state->mCommand = FastCaptureState::EXIT;
6021 sq->end();
6022 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6023 mFastCapture->join();
6024 mFastCapture.clear();
6025 }
6026 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07006027 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07006028 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08006029}
6030
6031void AudioFlinger::RecordThread::onFirstRef()
6032{
Glenn Kastend7dca052015-03-05 16:05:54 -08006033 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08006034}
6035
Eric Laurent81784c32012-11-19 14:55:58 -08006036bool AudioFlinger::RecordThread::threadLoop()
6037{
Eric Laurent81784c32012-11-19 14:55:58 -08006038 nsecs_t lastWarning = 0;
6039
6040 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006041
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006042reacquire_wakelock:
6043 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08006044 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006045 {
6046 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006047 size_t size = mActiveTracks.size();
6048 activeTracksGen = mActiveTracksGen;
6049 if (size > 0) {
6050 // FIXME an arbitrary choice
6051 activeTrack = mActiveTracks[0];
6052 acquireWakeLock_l(activeTrack->uid());
6053 if (size > 1) {
6054 SortedVector<int> tmp;
6055 for (size_t i = 0; i < size; i++) {
6056 tmp.add(mActiveTracks[i]->uid());
6057 }
6058 updateWakeLockUids_l(tmp);
6059 }
6060 } else {
6061 acquireWakeLock_l(-1);
6062 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006063 }
6064
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006065 // used to request a deferred sleep, to be executed later while mutex is unlocked
6066 uint32_t sleepUs = 0;
6067
6068 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006069 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006070 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07006071
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006072 // activeTracks accumulates a copy of a subset of mActiveTracks
6073 Vector< sp<RecordTrack> > activeTracks;
6074
Glenn Kasten735f45f2014-08-18 15:51:59 -07006075 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006076 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07006077
Glenn Kasten735f45f2014-08-18 15:51:59 -07006078 // reference to a fast track which is about to be removed
6079 sp<RecordTrack> fastTrackToRemove;
6080
Eric Laurent81784c32012-11-19 14:55:58 -08006081 { // scope for mLock
6082 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08006083
Eric Laurent021cf962014-05-13 10:18:14 -07006084 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006085
Eric Laurent000a4192014-01-29 15:17:32 -08006086 // check exitPending here because checkForNewParameters_l() and
6087 // checkForNewParameters_l() can temporarily release mLock
6088 if (exitPending()) {
6089 break;
6090 }
6091
Eric Laurent5c25d562016-07-13 17:17:45 -07006092 // sleep with mutex unlocked
6093 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07006094 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07006095 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
6096 ATRACE_END();
6097 sleepUs = 0;
6098 continue;
6099 }
6100
Glenn Kasten2b806402013-11-20 16:37:38 -08006101 // if no active track(s), then standby and release wakelock
6102 size_t size = mActiveTracks.size();
6103 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07006104 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006105 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08006106 releaseWakeLock_l();
6107 ALOGV("RecordThread: loop stopping");
6108 // go to sleep
6109 mWaitWorkCV.wait(mLock);
6110 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006111 goto reacquire_wakelock;
6112 }
6113
Glenn Kasten2b806402013-11-20 16:37:38 -08006114 if (mActiveTracksGen != activeTracksGen) {
6115 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006116 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08006117 for (size_t i = 0; i < size; i++) {
6118 tmp.add(mActiveTracks[i]->uid());
6119 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006120 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08006121 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006122
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006123 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07006124 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006125 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07006126
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006127 activeTrack = mActiveTracks[i];
6128 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07006129 if (activeTrack->isFastTrack()) {
6130 ALOG_ASSERT(fastTrackToRemove == 0);
6131 fastTrackToRemove = activeTrack;
6132 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006133 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08006134 mActiveTracks.remove(activeTrack);
6135 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006136 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07006137 continue;
6138 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006139
6140 TrackBase::track_state activeTrackState = activeTrack->mState;
6141 switch (activeTrackState) {
6142
6143 case TrackBase::PAUSING:
6144 mActiveTracks.remove(activeTrack);
6145 mActiveTracksGen++;
6146 doBroadcast = true;
6147 size--;
6148 continue;
6149
6150 case TrackBase::STARTING_1:
6151 sleepUs = 10000;
6152 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07006153 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006154 continue;
6155
6156 case TrackBase::STARTING_2:
6157 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006158 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07006159 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07006160 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006161 break;
6162
6163 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07006164 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006165 break;
6166
6167 case TrackBase::IDLE:
6168 i++;
6169 continue;
6170
6171 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08006172 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07006173 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006174
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006175 activeTracks.add(activeTrack);
6176 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07006177
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006178 if (activeTrack->isFastTrack()) {
6179 ALOG_ASSERT(!mFastTrackAvail);
6180 ALOG_ASSERT(fastTrack == 0);
6181 fastTrack = activeTrack;
6182 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006183 }
Eric Laurent5c25d562016-07-13 17:17:45 -07006184
6185 if (allStopped) {
6186 standbyIfNotAlreadyInStandby();
6187 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006188 if (doBroadcast) {
6189 mStartStopCond.broadcast();
6190 }
6191
6192 // sleep if there are no active tracks to process
6193 if (activeTracks.size() == 0) {
6194 if (sleepUs == 0) {
6195 sleepUs = kRecordThreadSleepUs;
6196 }
6197 continue;
6198 }
6199 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07006200
Eric Laurent81784c32012-11-19 14:55:58 -08006201 lockEffectChains_l(effectChains);
6202 }
6203
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006204 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07006205
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006206 size_t size = effectChains.size();
6207 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006208 // thread mutex is not locked, but effect chain is locked
6209 effectChains[i]->process_l();
6210 }
6211
Glenn Kasten735f45f2014-08-18 15:51:59 -07006212 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006213 if (mFastCapture != 0) {
6214 FastCaptureStateQueue *sq = mFastCapture->sq();
6215 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07006216 bool didModify = false;
6217 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006218 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
6219 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
6220 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6221 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6222 if (old == -1) {
6223 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6224 }
6225 }
6226 state->mCommand = FastCaptureState::READ_WRITE;
6227#if 0 // FIXME
6228 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08006229 FastThreadDumpState::kSamplingNforLowRamDevice :
6230 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006231#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07006232 didModify = true;
6233 }
6234 audio_track_cblk_t *cblkOld = state->mCblk;
6235 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
6236 if (cblkNew != cblkOld) {
6237 state->mCblk = cblkNew;
6238 // block until acked if removing a fast track
6239 if (cblkOld != NULL) {
6240 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
6241 }
6242 didModify = true;
6243 }
6244 sq->end(didModify);
6245 if (didModify) {
6246 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006247#if 0
6248 if (kUseFastCapture == FastCapture_Dynamic) {
6249 mNormalSource = mPipeSource;
6250 }
6251#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006252 }
6253 }
6254
Glenn Kasten735f45f2014-08-18 15:51:59 -07006255 // now run the fast track destructor with thread mutex unlocked
6256 fastTrackToRemove.clear();
6257
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006258 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
6259 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
6260 // slow, then this RecordThread will overrun by not calling HAL read often enough.
6261 // If destination is non-contiguous, first read past the nominal end of buffer, then
6262 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006263
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006264 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006265 ssize_t framesRead;
6266
6267 // If an NBAIO source is present, use it to read the normal capture's data
6268 if (mPipeSource != 0) {
6269 size_t framesToRead = mBufferSize / mFrameSize;
Glenn Kasten1b291842016-07-18 14:55:21 -07006270 framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hung57446612015-04-19 23:56:46 -07006271 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
Glenn Kastend79072e2016-01-06 08:41:20 -08006272 framesToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07006273 // since pipe is non-blocking, simulate blocking input by waiting for 1/2 of
6274 // buffer size or at least for 20ms.
6275 size_t sleepFrames = max(
6276 min(mPipeFramesP2, mRsmpInFramesP2) / 2, FMS_20 * mSampleRate / 1000);
6277 if (framesRead <= (ssize_t) sleepFrames) {
6278 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
6279 }
6280 if (framesRead < 0) {
6281 status_t status = (status_t) framesRead;
6282 switch (status) {
6283 case OVERRUN:
6284 ALOGW("overrun on read from pipe");
6285 framesRead = 0;
6286 break;
6287 case NEGOTIATE:
6288 ALOGE("re-negotiation is needed");
6289 framesRead = -1; // Will cause an attempt to recover.
6290 break;
6291 default:
6292 ALOGE("unknown error %d on read from pipe", status);
6293 break;
6294 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006295 }
6296 // otherwise use the HAL / AudioStreamIn directly
6297 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07006298 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006299 size_t bytesRead;
6300 status_t result = mInput->stream->read(
6301 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07006302 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006303 if (result < 0) {
6304 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006305 } else {
6306 framesRead = bytesRead / mFrameSize;
6307 }
6308 }
6309
Andy Hung3f0c9022016-01-15 17:49:46 -08006310 // Update server timestamp with server stats
6311 // systemTime() is optional if the hardware supports timestamps.
6312 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
6313 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6314
6315 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006316 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08006317 int64_t position, time;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006318 int ret = mInput->stream->getCapturePosition(&position, &time);
Andy Hung3f0c9022016-01-15 17:49:46 -08006319 if (ret == NO_ERROR) {
6320 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
6321 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
6322 // Note: In general record buffers should tend to be empty in
6323 // a properly running pipeline.
6324 //
6325 // Also, it is not advantageous to call get_presentation_position during the read
6326 // as the read obtains a lock, preventing the timestamp call from executing.
6327 }
6328 }
6329 // Use this to track timestamp information
6330 // ALOGD("%s", mTimestamp.toString().c_str());
6331
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006332 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006333 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006334 // Force input into standby so that it tries to recover at next read attempt
6335 inputStandBy();
6336 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006337 }
6338 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006339 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006340 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006341 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006342
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006343 if (mTeeSink != 0) {
Andy Hung57446612015-04-19 23:56:46 -07006344 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006345 }
6346 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006347 {
6348 size_t part1 = mRsmpInFramesP2 - rear;
6349 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07006350 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006351 (framesRead - part1) * mFrameSize);
6352 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006353 }
6354 rear = mRsmpInRear += framesRead;
6355
6356 size = activeTracks.size();
6357 // loop over each active track
6358 for (size_t i = 0; i < size; i++) {
6359 activeTrack = activeTracks[i];
6360
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006361 // skip fast tracks, as those are handled directly by FastCapture
6362 if (activeTrack->isFastTrack()) {
6363 continue;
6364 }
6365
Andy Hung73c02e42015-03-29 01:13:58 -07006366 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07006367 // TODO: Update the activeTrack buffer converter in case of reconfigure.
6368
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006369 enum {
6370 OVERRUN_UNKNOWN,
6371 OVERRUN_TRUE,
6372 OVERRUN_FALSE
6373 } overrun = OVERRUN_UNKNOWN;
6374
6375 // loop over getNextBuffer to handle circular sink
6376 for (;;) {
6377
6378 activeTrack->mSink.frameCount = ~0;
6379 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
6380 size_t framesOut = activeTrack->mSink.frameCount;
6381 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
6382
Andy Hung73c02e42015-03-29 01:13:58 -07006383 // check available frames and handle overrun conditions
6384 // if the record track isn't draining fast enough.
6385 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006386 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07006387 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
6388 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006389 overrun = OVERRUN_TRUE;
6390 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006391 if (framesOut == 0 || framesIn == 0) {
6392 break;
6393 }
6394
Andy Hung6770c6f2015-04-07 13:43:36 -07006395 // Don't allow framesOut to be larger than what is possible with resampling
6396 // from framesIn.
6397 // This isn't strictly necessary but helps limit buffer resizing in
6398 // RecordBufferConverter. TODO: remove when no longer needed.
6399 framesOut = min(framesOut,
6400 destinationFramesPossible(
6401 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07006402 // process frames from the RecordThread buffer provider to the RecordTrack buffer
6403 framesOut = activeTrack->mRecordBufferConverter->convert(
6404 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006405
6406 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
6407 overrun = OVERRUN_FALSE;
6408 }
6409
6410 if (activeTrack->mFramesToDrop == 0) {
6411 if (framesOut > 0) {
6412 activeTrack->mSink.frameCount = framesOut;
6413 activeTrack->releaseBuffer(&activeTrack->mSink);
6414 }
6415 } else {
6416 // FIXME could do a partial drop of framesOut
6417 if (activeTrack->mFramesToDrop > 0) {
6418 activeTrack->mFramesToDrop -= framesOut;
6419 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006420 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006421 }
6422 } else {
6423 activeTrack->mFramesToDrop += framesOut;
6424 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
6425 activeTrack->mSyncStartEvent->isCancelled()) {
6426 ALOGW("Synced record %s, session %d, trigger session %d",
6427 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
6428 activeTrack->sessionId(),
6429 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08006430 activeTrack->mSyncStartEvent->triggerSession() :
6431 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006432 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006433 }
6434 }
6435 }
6436
6437 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006438 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006439 }
6440 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006441
6442 switch (overrun) {
6443 case OVERRUN_TRUE:
6444 // client isn't retrieving buffers fast enough
6445 if (!activeTrack->setOverflow()) {
6446 nsecs_t now = systemTime();
6447 // FIXME should lastWarning per track?
6448 if ((now - lastWarning) > kWarningThrottleNs) {
6449 ALOGW("RecordThread: buffer overflow");
6450 lastWarning = now;
6451 }
6452 }
6453 break;
6454 case OVERRUN_FALSE:
6455 activeTrack->clearOverflow();
6456 break;
6457 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006458 break;
6459 }
6460
Andy Hung3f0c9022016-01-15 17:49:46 -08006461 // update frame information and push timestamp out
6462 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08006463 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08006464 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
6465 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006466 }
6467
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006468unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08006469 // enable changes in effect chain
6470 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006471 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08006472 }
6473
Glenn Kasten93e471f2013-08-19 08:40:07 -07006474 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08006475
6476 {
6477 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07006478 for (size_t i = 0; i < mTracks.size(); i++) {
6479 sp<RecordTrack> track = mTracks[i];
6480 track->invalidate();
6481 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006482 mActiveTracks.clear();
6483 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08006484 mStartStopCond.broadcast();
6485 }
6486
6487 releaseWakeLock();
6488
6489 ALOGV("RecordThread %p exiting", this);
6490 return false;
6491}
6492
Glenn Kasten93e471f2013-08-19 08:40:07 -07006493void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08006494{
6495 if (!mStandby) {
6496 inputStandBy();
6497 mStandby = true;
6498 }
6499}
6500
6501void AudioFlinger::RecordThread::inputStandBy()
6502{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006503 // Idle the fast capture if it's currently running
6504 if (mFastCapture != 0) {
6505 FastCaptureStateQueue *sq = mFastCapture->sq();
6506 FastCaptureState *state = sq->begin();
6507 if (!(state->mCommand & FastCaptureState::IDLE)) {
6508 state->mCommand = FastCaptureState::COLD_IDLE;
6509 state->mColdFutexAddr = &mFastCaptureFutex;
6510 state->mColdGen++;
6511 mFastCaptureFutex = 0;
6512 sq->end();
6513 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
6514 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
6515#if 0
6516 if (kUseFastCapture == FastCapture_Dynamic) {
6517 // FIXME
6518 }
6519#endif
6520#ifdef AUDIO_WATCHDOG
6521 // FIXME
6522#endif
6523 } else {
6524 sq->end(false /*didModify*/);
6525 }
6526 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006527 status_t result = mInput->stream->standby();
6528 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07006529
6530 // If going into standby, flush the pipe source.
6531 if (mPipeSource.get() != nullptr) {
6532 const ssize_t flushed = mPipeSource->flush();
6533 if (flushed > 0) {
6534 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
6535 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
6536 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6537 }
6538 }
Eric Laurent81784c32012-11-19 14:55:58 -08006539}
6540
Glenn Kasten05997e22014-03-13 15:08:33 -07006541// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07006542sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08006543 const sp<AudioFlinger::Client>& client,
6544 uint32_t sampleRate,
6545 audio_format_t format,
6546 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08006547 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08006548 audio_session_t sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07006549 size_t *notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006550 int uid,
Eric Laurent05067782016-06-01 18:27:28 -07006551 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08006552 pid_t tid,
6553 status_t *status)
6554{
Glenn Kasten74935e42013-12-19 08:56:45 -08006555 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08006556 sp<RecordTrack> track;
6557 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07006558 audio_input_flags_t inputFlags = mInput->flags;
6559
6560 // special case for FAST flag considered OK if fast capture is present
6561 if (hasFastCapture()) {
6562 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
6563 }
6564
6565 // Check if requested flags are compatible with output stream flags
6566 if ((*flags & inputFlags) != *flags) {
6567 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
6568 " input flags (%08x)",
6569 *flags, inputFlags);
6570 *flags = (audio_input_flags_t)(*flags & inputFlags);
6571 }
Eric Laurent81784c32012-11-19 14:55:58 -08006572
Glenn Kasten90e58b12013-07-31 16:16:02 -07006573 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07006574 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006575 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07006576 // we formerly checked for a callback handler (non-0 tid),
6577 // but that is no longer required for TRANSFER_OBTAIN mode
6578 //
Glenn Kasten74105912014-07-03 12:28:53 -07006579 // frame count is not specified, or is exactly the pipe depth
6580 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006581 // PCM data
6582 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006583 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006584 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006585 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006586 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006587 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07006588 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006589 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006590 hasFastCapture() &&
6591 // there are sufficient fast track slots available
6592 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07006593 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07006594 // check compatibility with audio effects.
6595 Mutex::Autolock _l(mLock);
6596 // Do not accept FAST flag if the session has software effects
6597 sp<EffectChain> chain = getEffectChain_l(sessionId);
6598 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07006599 audio_input_flags_t old = *flags;
6600 chain->checkInputFlagCompatibility(flags);
6601 if (old != *flags) {
6602 ALOGV("AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
6603 (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07006604 }
6605 }
Eric Laurent122f7e72016-06-29 11:53:29 -07006606 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07006607 "AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
6608 frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006609 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006610 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
Glenn Kasten74105912014-07-03 12:28:53 -07006611 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006612 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07006613 frameCount, mFrameCount, mPipeFramesP2,
6614 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
6615 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07006616 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07006617 }
6618 }
6619
6620 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07006621 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07006622 // fast track: frame count is exactly the pipe depth
6623 frameCount = mPipeFramesP2;
6624 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
6625 *notificationFrames = mFrameCount;
6626 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006627 // not fast track: max notification period is resampled equivalent of one HAL buffer time
6628 // or 20 ms if there is a fast capture
6629 // TODO This could be a roundupRatio inline, and const
6630 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
6631 * sampleRate + mSampleRate - 1) / mSampleRate;
6632 // minimum number of notification periods is at least kMinNotifications,
6633 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
6634 static const size_t kMinNotifications = 3;
6635 static const uint32_t kMinMs = 30;
6636 // TODO This could be a roundupRatio inline
6637 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
6638 // TODO This could be a roundupRatio inline
6639 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
6640 maxNotificationFrames;
6641 const size_t minFrameCount = maxNotificationFrames *
6642 max(kMinNotifications, minNotificationsByMs);
6643 frameCount = max(frameCount, minFrameCount);
6644 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
6645 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07006646 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07006647 }
Glenn Kasten74935e42013-12-19 08:56:45 -08006648 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07006649
Glenn Kasten15e57982013-09-24 11:52:37 -07006650 lStatus = initCheck();
6651 if (lStatus != NO_ERROR) {
6652 ALOGE("createRecordTrack_l() audio driver not initialized");
6653 goto Exit;
6654 }
Eric Laurent81784c32012-11-19 14:55:58 -08006655
6656 { // scope for mLock
6657 Mutex::Autolock _l(mLock);
6658
6659 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07006660 format, channelMask, frameCount, NULL, sessionId, uid,
6661 *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08006662
Glenn Kasten03003332013-08-06 15:40:54 -07006663 lStatus = track->initCheck();
6664 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07006665 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08006666 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08006667 goto Exit;
6668 }
6669 mTracks.add(track);
6670
6671 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6672 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6673 mAudioFlinger->btNrecIsOff();
6674 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6675 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006676
Eric Laurent05067782016-06-01 18:27:28 -07006677 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006678 pid_t callingPid = IPCThreadState::self()->getCallingPid();
6679 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
6680 // so ask activity manager to do this on our behalf
6681 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
6682 }
Eric Laurent81784c32012-11-19 14:55:58 -08006683 }
Glenn Kasten05997e22014-03-13 15:08:33 -07006684
Eric Laurent81784c32012-11-19 14:55:58 -08006685 lStatus = NO_ERROR;
6686
6687Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07006688 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08006689 return track;
6690}
6691
6692status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6693 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08006694 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08006695{
6696 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6697 sp<ThreadBase> strongMe = this;
6698 status_t status = NO_ERROR;
6699
6700 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006701 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006702 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006703 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08006704 triggerSession,
6705 recordTrack->sessionId(),
6706 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006707 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08006708 // Sync event can be cancelled by the trigger session if the track is not in a
6709 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006710 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006711 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006712 } else {
6713 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006714 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006715 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08006716 }
6717 }
6718
6719 {
Glenn Kasten47c20702013-08-13 15:37:35 -07006720 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08006721 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006722 if (mActiveTracks.indexOf(recordTrack) >= 0) {
6723 if (recordTrack->mState == TrackBase::PAUSING) {
6724 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006725 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006726 } else {
6727 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08006728 }
6729 return status;
6730 }
6731
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006732 // TODO consider other ways of handling this, such as changing the state to :STARTING and
6733 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6734 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006735 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08006736 mActiveTracks.add(recordTrack);
6737 mActiveTracksGen++;
Eric Laurent83b88082014-06-20 18:31:16 -07006738 status_t status = NO_ERROR;
6739 if (recordTrack->isExternalTrack()) {
6740 mLock.unlock();
Glenn Kastend848eb42016-03-08 13:42:11 -08006741 status = AudioSystem::startInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006742 mLock.lock();
6743 // FIXME should verify that recordTrack is still in mActiveTracks
6744 if (status != NO_ERROR) {
6745 mActiveTracks.remove(recordTrack);
6746 mActiveTracksGen++;
6747 recordTrack->clearSyncStartEvent();
6748 ALOGV("RecordThread::start error %d", status);
6749 return status;
6750 }
Eric Laurent81784c32012-11-19 14:55:58 -08006751 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006752 // Catch up with current buffer indices if thread is already running.
6753 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
6754 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6755 // see previously buffered data before it called start(), but with greater risk of overrun.
6756
Andy Hung73c02e42015-03-29 01:13:58 -07006757 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07006758 // clear any converter state as new data will be discontinuous
6759 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006760 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08006761 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08006762 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08006763 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006764 ALOGV("Record failed to start");
6765 status = BAD_VALUE;
6766 goto startError;
6767 }
Eric Laurent81784c32012-11-19 14:55:58 -08006768 return status;
6769 }
Glenn Kasten7c027242012-12-26 14:43:16 -08006770
Eric Laurent81784c32012-11-19 14:55:58 -08006771startError:
Eric Laurent83b88082014-06-20 18:31:16 -07006772 if (recordTrack->isExternalTrack()) {
Glenn Kastend848eb42016-03-08 13:42:11 -08006773 AudioSystem::stopInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006774 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006775 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006776 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08006777 return status;
6778}
6779
Eric Laurent81784c32012-11-19 14:55:58 -08006780void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6781{
6782 sp<SyncEvent> strongEvent = event.promote();
6783
6784 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08006785 sp<RefBase> ptr = strongEvent->cookie().promote();
6786 if (ptr != 0) {
6787 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6788 recordTrack->handleSyncStartEvent(strongEvent);
6789 }
Eric Laurent81784c32012-11-19 14:55:58 -08006790 }
6791}
6792
Glenn Kastena8356f62013-07-25 14:37:52 -07006793bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08006794 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07006795 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006796 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08006797 return false;
6798 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006799 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006800 recordTrack->mState = TrackBase::PAUSING;
Eric Laurent5c25d562016-07-13 17:17:45 -07006801 // signal thread to stop
6802 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08006803 // do not wait for mStartStopCond if exiting
6804 if (exitPending()) {
6805 return true;
6806 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006807 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08006808 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006809 // if we have been restarted, recordTrack is in mActiveTracks here
6810 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006811 ALOGV("Record stopped OK");
6812 return true;
6813 }
6814 return false;
6815}
6816
Glenn Kasten0f11b512014-01-31 16:18:54 -08006817bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08006818{
6819 return false;
6820}
6821
Glenn Kasten0f11b512014-01-31 16:18:54 -08006822status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006823{
6824#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6825 if (!isValidSyncEvent(event)) {
6826 return BAD_VALUE;
6827 }
6828
Glenn Kastend848eb42016-03-08 13:42:11 -08006829 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08006830 status_t ret = NAME_NOT_FOUND;
6831
6832 Mutex::Autolock _l(mLock);
6833
6834 for (size_t i = 0; i < mTracks.size(); i++) {
6835 sp<RecordTrack> track = mTracks[i];
6836 if (eventSession == track->sessionId()) {
6837 (void) track->setSyncEvent(event);
6838 ret = NO_ERROR;
6839 }
6840 }
6841 return ret;
6842#else
6843 return BAD_VALUE;
6844#endif
6845}
6846
6847// destroyTrack_l() must be called with ThreadBase::mLock held
6848void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6849{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006850 track->terminate();
6851 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006852 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006853 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006854 removeTrack_l(track);
6855 }
6856}
6857
6858void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6859{
6860 mTracks.remove(track);
6861 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006862 if (track->isFastTrack()) {
6863 ALOG_ASSERT(!mFastTrackAvail);
6864 mFastTrackAvail = true;
6865 }
Eric Laurent81784c32012-11-19 14:55:58 -08006866}
6867
6868void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6869{
6870 dumpInternals(fd, args);
6871 dumpTracks(fd, args);
6872 dumpEffectChains(fd, args);
6873}
6874
6875void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6876{
Elliott Hughes87cebad2014-05-22 10:14:43 -07006877 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08006878
Glenn Kasten44182c22015-03-05 17:12:23 -08006879 dumpBase(fd, args);
6880
6881 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006882 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006883 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006884 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006885 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08006886
Glenn Kasten2f90c512015-12-02 11:40:09 -08006887 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
6888 // while we are dumping it. It may be inconsistent, but it won't mutate!
6889 // This is a large object so we place it on the heap.
6890 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
6891 const FastCaptureDumpState *copy = new FastCaptureDumpState(mFastCaptureDumpState);
6892 copy->dump(fd);
6893 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08006894}
6895
Glenn Kasten0f11b512014-01-31 16:18:54 -08006896void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006897{
6898 const size_t SIZE = 256;
6899 char buffer[SIZE];
6900 String8 result;
6901
Marco Nelissenb2208842014-02-07 14:00:50 -08006902 size_t numtracks = mTracks.size();
6903 size_t numactive = mActiveTracks.size();
6904 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006905 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006906 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006907 dprintf(fd, " of which %zu are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006908 RecordTrack::appendDumpHeader(result);
6909 for (size_t i = 0; i < numtracks ; ++i) {
6910 sp<RecordTrack> track = mTracks[i];
6911 if (track != 0) {
6912 bool active = mActiveTracks.indexOf(track) >= 0;
6913 if (active) {
6914 numactiveseen++;
6915 }
6916 track->dump(buffer, SIZE, active);
6917 result.append(buffer);
6918 }
Eric Laurent81784c32012-11-19 14:55:58 -08006919 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006920 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006921 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006922 }
6923
Marco Nelissenb2208842014-02-07 14:00:50 -08006924 if (numactiveseen != numactive) {
6925 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6926 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006927 result.append(buffer);
6928 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006929 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006930 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006931 if (mTracks.indexOf(track) < 0) {
6932 track->dump(buffer, SIZE, true);
6933 result.append(buffer);
6934 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006935 }
Eric Laurent81784c32012-11-19 14:55:58 -08006936
6937 }
6938 write(fd, result.string(), result.size());
6939}
6940
Andy Hung73c02e42015-03-29 01:13:58 -07006941
6942void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
6943{
6944 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6945 RecordThread *recordThread = (RecordThread *) threadBase.get();
6946 mRsmpInFront = recordThread->mRsmpInRear;
6947 mRsmpInUnrel = 0;
6948}
6949
6950void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
6951 size_t *framesAvailable, bool *hasOverrun)
6952{
6953 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6954 RecordThread *recordThread = (RecordThread *) threadBase.get();
6955 const int32_t rear = recordThread->mRsmpInRear;
6956 const int32_t front = mRsmpInFront;
6957 const ssize_t filled = rear - front;
6958
6959 size_t framesIn;
6960 bool overrun = false;
6961 if (filled < 0) {
6962 // should not happen, but treat like a massive overrun and re-sync
6963 framesIn = 0;
6964 mRsmpInFront = rear;
6965 overrun = true;
6966 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
6967 framesIn = (size_t) filled;
6968 } else {
6969 // client is not keeping up with server, but give it latest data
6970 framesIn = recordThread->mRsmpInFrames;
6971 mRsmpInFront = /* front = */ rear - framesIn;
6972 overrun = true;
6973 }
6974 if (framesAvailable != NULL) {
6975 *framesAvailable = framesIn;
6976 }
6977 if (hasOverrun != NULL) {
6978 *hasOverrun = overrun;
6979 }
6980}
6981
Eric Laurent81784c32012-11-19 14:55:58 -08006982// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006983status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08006984 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006985{
Andy Hung73c02e42015-03-29 01:13:58 -07006986 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006987 if (threadBase == 0) {
6988 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006989 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006990 return NOT_ENOUGH_DATA;
6991 }
6992 RecordThread *recordThread = (RecordThread *) threadBase.get();
6993 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07006994 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07006995 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006996 // FIXME should not be P2 (don't want to increase latency)
6997 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006998 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07006999 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007000 front &= recordThread->mRsmpInFramesP2 - 1;
7001 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07007002 if (part1 > (size_t) filled) {
7003 part1 = filled;
7004 }
7005 size_t ask = buffer->frameCount;
7006 ALOG_ASSERT(ask > 0);
7007 if (part1 > ask) {
7008 part1 = ask;
7009 }
7010 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07007011 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07007012 buffer->raw = NULL;
7013 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07007014 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07007015 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08007016 }
7017
Andy Hung57446612015-04-19 23:56:46 -07007018 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07007019 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07007020 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08007021 return NO_ERROR;
7022}
7023
7024// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007025void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
7026 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08007027{
Glenn Kasten85948432013-08-19 12:09:05 -07007028 size_t stepCount = buffer->frameCount;
7029 if (stepCount == 0) {
7030 return;
7031 }
Andy Hung73c02e42015-03-29 01:13:58 -07007032 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
7033 mRsmpInUnrel -= stepCount;
7034 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07007035 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08007036 buffer->frameCount = 0;
7037}
7038
Andy Hung97a893e2015-03-29 01:03:07 -07007039AudioFlinger::RecordThread::RecordBufferConverter::RecordBufferConverter(
7040 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
7041 uint32_t srcSampleRate,
7042 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
7043 uint32_t dstSampleRate) :
7044 mSrcChannelMask(AUDIO_CHANNEL_INVALID), // updateParameters will set following vars
7045 // mSrcFormat
7046 // mSrcSampleRate
7047 // mDstChannelMask
7048 // mDstFormat
7049 // mDstSampleRate
7050 // mSrcChannelCount
7051 // mDstChannelCount
7052 // mDstFrameSize
7053 mBuf(NULL), mBufFrames(0), mBufFrameSize(0),
Andy Hungd330ee42015-04-20 13:23:41 -07007054 mResampler(NULL),
7055 mIsLegacyDownmix(false),
7056 mIsLegacyUpmix(false),
7057 mRequiresFloat(false),
7058 mInputConverterProvider(NULL)
Andy Hung97a893e2015-03-29 01:03:07 -07007059{
7060 (void)updateParameters(srcChannelMask, srcFormat, srcSampleRate,
7061 dstChannelMask, dstFormat, dstSampleRate);
7062}
7063
7064AudioFlinger::RecordThread::RecordBufferConverter::~RecordBufferConverter() {
7065 free(mBuf);
7066 delete mResampler;
Andy Hungd330ee42015-04-20 13:23:41 -07007067 delete mInputConverterProvider;
Andy Hung97a893e2015-03-29 01:03:07 -07007068}
7069
7070size_t AudioFlinger::RecordThread::RecordBufferConverter::convert(void *dst,
7071 AudioBufferProvider *provider, size_t frames)
7072{
Andy Hungd330ee42015-04-20 13:23:41 -07007073 if (mInputConverterProvider != NULL) {
7074 mInputConverterProvider->setBufferProvider(provider);
7075 provider = mInputConverterProvider;
7076 }
7077
7078 if (mResampler == NULL) {
Andy Hung97a893e2015-03-29 01:03:07 -07007079 ALOGVV("NO RESAMPLING sampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
7080 mSrcSampleRate, mSrcFormat, mDstFormat);
7081
7082 AudioBufferProvider::Buffer buffer;
7083 for (size_t i = frames; i > 0; ) {
7084 buffer.frameCount = i;
Glenn Kastend79072e2016-01-06 08:41:20 -08007085 status_t status = provider->getNextBuffer(&buffer);
Andy Hung97a893e2015-03-29 01:03:07 -07007086 if (status != OK || buffer.frameCount == 0) {
7087 frames -= i; // cannot fill request.
7088 break;
7089 }
Andy Hungd330ee42015-04-20 13:23:41 -07007090 // format convert to destination buffer
7091 convertNoResampler(dst, buffer.raw, buffer.frameCount);
Andy Hung97a893e2015-03-29 01:03:07 -07007092
7093 dst = (int8_t*)dst + buffer.frameCount * mDstFrameSize;
7094 i -= buffer.frameCount;
7095 provider->releaseBuffer(&buffer);
7096 }
7097 } else {
7098 ALOGVV("RESAMPLING mSrcSampleRate:%u mDstSampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
7099 mSrcSampleRate, mDstSampleRate, mSrcFormat, mDstFormat);
7100
Andy Hungd330ee42015-04-20 13:23:41 -07007101 // reallocate buffer if needed
7102 if (mBufFrameSize != 0 && mBufFrames < frames) {
7103 free(mBuf);
7104 mBufFrames = frames;
7105 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
7106 }
Andy Hung97a893e2015-03-29 01:03:07 -07007107 // resampler accumulates, but we only have one source track
Andy Hungd330ee42015-04-20 13:23:41 -07007108 memset(mBuf, 0, frames * mBufFrameSize);
7109 frames = mResampler->resample((int32_t*)mBuf, frames, provider);
7110 // format convert to destination buffer
7111 convertResampler(dst, mBuf, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07007112 }
7113 return frames;
7114}
7115
7116status_t AudioFlinger::RecordThread::RecordBufferConverter::updateParameters(
7117 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
7118 uint32_t srcSampleRate,
7119 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
7120 uint32_t dstSampleRate)
7121{
7122 // quick evaluation if there is any change.
7123 if (mSrcFormat == srcFormat
7124 && mSrcChannelMask == srcChannelMask
7125 && mSrcSampleRate == srcSampleRate
7126 && mDstFormat == dstFormat
7127 && mDstChannelMask == dstChannelMask
7128 && mDstSampleRate == dstSampleRate) {
7129 return NO_ERROR;
7130 }
7131
Andy Hungdb4c0312015-05-06 08:46:52 -07007132 ALOGV("RecordBufferConverter updateParameters srcMask:%#x dstMask:%#x"
7133 " srcFormat:%#x dstFormat:%#x srcRate:%u dstRate:%u",
7134 srcChannelMask, dstChannelMask, srcFormat, dstFormat, srcSampleRate, dstSampleRate);
Andy Hung97a893e2015-03-29 01:03:07 -07007135 const bool valid =
7136 audio_is_input_channel(srcChannelMask)
7137 && audio_is_input_channel(dstChannelMask)
7138 && audio_is_valid_format(srcFormat) && audio_is_linear_pcm(srcFormat)
7139 && audio_is_valid_format(dstFormat) && audio_is_linear_pcm(dstFormat)
7140 && (srcSampleRate <= dstSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX)
7141 ; // no upsampling checks for now
7142 if (!valid) {
7143 return BAD_VALUE;
7144 }
7145
7146 mSrcFormat = srcFormat;
7147 mSrcChannelMask = srcChannelMask;
7148 mSrcSampleRate = srcSampleRate;
7149 mDstFormat = dstFormat;
7150 mDstChannelMask = dstChannelMask;
7151 mDstSampleRate = dstSampleRate;
7152
7153 // compute derived parameters
7154 mSrcChannelCount = audio_channel_count_from_in_mask(srcChannelMask);
7155 mDstChannelCount = audio_channel_count_from_in_mask(dstChannelMask);
7156 mDstFrameSize = mDstChannelCount * audio_bytes_per_sample(mDstFormat);
7157
Andy Hungd330ee42015-04-20 13:23:41 -07007158 // do we need to resample?
7159 delete mResampler;
7160 mResampler = NULL;
7161 if (mSrcSampleRate != mDstSampleRate) {
7162 mResampler = AudioResampler::create(AUDIO_FORMAT_PCM_FLOAT,
7163 mSrcChannelCount, mDstSampleRate);
7164 mResampler->setSampleRate(mSrcSampleRate);
7165 mResampler->setVolume(AudioMixer::UNITY_GAIN_FLOAT, AudioMixer::UNITY_GAIN_FLOAT);
7166 }
7167
7168 // are we running legacy channel conversion modes?
7169 mIsLegacyDownmix = (mSrcChannelMask == AUDIO_CHANNEL_IN_STEREO
7170 || mSrcChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK)
7171 && mDstChannelMask == AUDIO_CHANNEL_IN_MONO;
7172 mIsLegacyUpmix = mSrcChannelMask == AUDIO_CHANNEL_IN_MONO
7173 && (mDstChannelMask == AUDIO_CHANNEL_IN_STEREO
7174 || mDstChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK);
7175
7176 // do we need to process in float?
7177 mRequiresFloat = mResampler != NULL || mIsLegacyDownmix || mIsLegacyUpmix;
7178
7179 // do we need a staging buffer to convert for destination (we can still optimize this)?
7180 // we use mBufFrameSize > 0 to indicate both frame size as well as buffer necessity
7181 if (mResampler != NULL) {
7182 mBufFrameSize = max(mSrcChannelCount, FCC_2)
7183 * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
Andy Hunga97630b2015-07-22 23:27:24 -07007184 } else if (mIsLegacyUpmix || mIsLegacyDownmix) { // legacy modes always float
Andy Hungd330ee42015-04-20 13:23:41 -07007185 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
7186 } else if (mSrcChannelMask != mDstChannelMask && mDstFormat != mSrcFormat) {
Andy Hung97a893e2015-03-29 01:03:07 -07007187 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(mSrcFormat);
7188 } else {
7189 mBufFrameSize = 0;
7190 }
7191 mBufFrames = 0; // force the buffer to be resized.
7192
Andy Hungd330ee42015-04-20 13:23:41 -07007193 // do we need an input converter buffer provider to give us float?
7194 delete mInputConverterProvider;
7195 mInputConverterProvider = NULL;
7196 if (mRequiresFloat && mSrcFormat != AUDIO_FORMAT_PCM_FLOAT) {
7197 mInputConverterProvider = new ReformatBufferProvider(
7198 audio_channel_count_from_in_mask(mSrcChannelMask),
7199 mSrcFormat,
7200 AUDIO_FORMAT_PCM_FLOAT,
7201 256 /* provider buffer frame count */);
7202 }
7203
7204 // do we need a remixer to do channel mask conversion
7205 if (!mIsLegacyDownmix && !mIsLegacyUpmix && mSrcChannelMask != mDstChannelMask) {
7206 (void) memcpy_by_index_array_initialization_from_channel_mask(
7207 mIdxAry, ARRAY_SIZE(mIdxAry), mDstChannelMask, mSrcChannelMask);
Andy Hung97a893e2015-03-29 01:03:07 -07007208 }
7209 return NO_ERROR;
7210}
7211
Andy Hungd330ee42015-04-20 13:23:41 -07007212void AudioFlinger::RecordThread::RecordBufferConverter::convertNoResampler(
7213 void *dst, const void *src, size_t frames)
Andy Hung97a893e2015-03-29 01:03:07 -07007214{
Andy Hungd330ee42015-04-20 13:23:41 -07007215 // src is native type unless there is legacy upmix or downmix, whereupon it is float.
Andy Hung97a893e2015-03-29 01:03:07 -07007216 if (mBufFrameSize != 0 && mBufFrames < frames) {
7217 free(mBuf);
7218 mBufFrames = frames;
7219 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
7220 }
Andy Hungd330ee42015-04-20 13:23:41 -07007221 // do we need to do legacy upmix and downmix?
7222 if (mIsLegacyUpmix || mIsLegacyDownmix) {
Andy Hung97a893e2015-03-29 01:03:07 -07007223 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07007224 if (mIsLegacyUpmix) {
7225 upmix_to_stereo_float_from_mono_float((float *)dstBuf,
7226 (const float *)src, frames);
7227 } else /*mIsLegacyDownmix */ {
7228 downmix_to_mono_float_from_stereo_float((float *)dstBuf,
7229 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07007230 }
Andy Hungd330ee42015-04-20 13:23:41 -07007231 if (mBuf != NULL) {
7232 memcpy_by_audio_format(dst, mDstFormat, mBuf, AUDIO_FORMAT_PCM_FLOAT,
7233 frames * mDstChannelCount);
7234 }
7235 return;
7236 }
7237 // do we need to do channel mask conversion?
7238 if (mSrcChannelMask != mDstChannelMask) {
Andy Hung97a893e2015-03-29 01:03:07 -07007239 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07007240 memcpy_by_index_array(dstBuf, mDstChannelCount,
7241 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mSrcFormat), frames);
7242 if (dstBuf == dst) {
7243 return; // format is the same
7244 }
7245 }
7246 // convert to destination buffer
7247 const void *convertBuf = mBuf != NULL ? mBuf : src;
7248 memcpy_by_audio_format(dst, mDstFormat, convertBuf, mSrcFormat,
7249 frames * mDstChannelCount);
7250}
7251
7252void AudioFlinger::RecordThread::RecordBufferConverter::convertResampler(
7253 void *dst, /*not-a-const*/ void *src, size_t frames)
7254{
7255 // src buffer format is ALWAYS float when entering this routine
7256 if (mIsLegacyUpmix) {
7257 ; // mono to stereo already handled by resampler
7258 } else if (mIsLegacyDownmix
7259 || (mSrcChannelMask == mDstChannelMask && mSrcChannelCount == 1)) {
7260 // the resampler outputs stereo for mono input channel (a feature?)
7261 // must convert to mono
7262 downmix_to_mono_float_from_stereo_float((float *)src,
7263 (const float *)src, frames);
7264 } else if (mSrcChannelMask != mDstChannelMask) {
7265 // convert to mono channel again for channel mask conversion (could be skipped
7266 // with further optimization).
Andy Hung97a893e2015-03-29 01:03:07 -07007267 if (mSrcChannelCount == 1) {
Andy Hungd330ee42015-04-20 13:23:41 -07007268 downmix_to_mono_float_from_stereo_float((float *)src,
7269 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07007270 }
Andy Hungd330ee42015-04-20 13:23:41 -07007271 // convert to destination format (in place, OK as float is larger than other types)
7272 if (mDstFormat != AUDIO_FORMAT_PCM_FLOAT) {
7273 memcpy_by_audio_format(src, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
7274 frames * mSrcChannelCount);
7275 }
7276 // channel convert and save to dst
7277 memcpy_by_index_array(dst, mDstChannelCount,
7278 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mDstFormat), frames);
7279 return;
Andy Hung97a893e2015-03-29 01:03:07 -07007280 }
Andy Hungd330ee42015-04-20 13:23:41 -07007281 // convert to destination format and save to dst
7282 memcpy_by_audio_format(dst, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
7283 frames * mDstChannelCount);
Andy Hung97a893e2015-03-29 01:03:07 -07007284}
7285
Eric Laurent10351942014-05-08 18:49:52 -07007286bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
7287 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007288{
7289 bool reconfig = false;
7290
Eric Laurent10351942014-05-08 18:49:52 -07007291 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007292
Eric Laurent10351942014-05-08 18:49:52 -07007293 audio_format_t reqFormat = mFormat;
7294 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07007295 // 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 -07007296 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
7297
7298 AudioParameter param = AudioParameter(keyValuePair);
7299 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07007300
7301 // scope for AutoPark extends to end of method
7302 AutoPark<FastCapture> park(mFastCapture);
7303
Eric Laurent10351942014-05-08 18:49:52 -07007304 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
7305 // channel count change can be requested. Do we mandate the first client defines the
7306 // HAL sampling rate and channel count or do we allow changes on the fly?
7307 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
7308 samplingRate = value;
7309 reconfig = true;
7310 }
7311 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07007312 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07007313 status = BAD_VALUE;
7314 } else {
7315 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08007316 reconfig = true;
7317 }
Eric Laurent10351942014-05-08 18:49:52 -07007318 }
7319 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
7320 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07007321 if (!audio_is_input_channel(mask) ||
7322 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007323 status = BAD_VALUE;
7324 } else {
7325 channelMask = mask;
7326 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007327 }
Eric Laurent10351942014-05-08 18:49:52 -07007328 }
7329 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7330 // do not accept frame count changes if tracks are open as the track buffer
7331 // size depends on frame count and correct behavior would not be guaranteed
7332 // if frame count is changed after track creation
7333 if (mActiveTracks.size() > 0) {
7334 status = INVALID_OPERATION;
7335 } else {
7336 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007337 }
Eric Laurent10351942014-05-08 18:49:52 -07007338 }
7339 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7340 // forward device change to effects that have requested to be
7341 // aware of attached audio device.
7342 for (size_t i = 0; i < mEffectChains.size(); i++) {
7343 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08007344 }
Eric Laurent81784c32012-11-19 14:55:58 -08007345
Eric Laurent10351942014-05-08 18:49:52 -07007346 // store input device and output device but do not forward output device to audio HAL.
7347 // Note that status is ignored by the caller for output device
7348 // (see AudioFlinger::setParameters()
7349 if (audio_is_output_devices(value)) {
7350 mOutDevice = value;
7351 status = BAD_VALUE;
7352 } else {
7353 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07007354 if (value != AUDIO_DEVICE_NONE) {
7355 mPrevInDevice = value;
7356 }
Eric Laurent10351942014-05-08 18:49:52 -07007357 // disable AEC and NS if the device is a BT SCO headset supporting those
7358 // pre processings
7359 if (mTracks.size() > 0) {
7360 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7361 mAudioFlinger->btNrecIsOff();
7362 for (size_t i = 0; i < mTracks.size(); i++) {
7363 sp<RecordTrack> track = mTracks[i];
7364 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7365 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08007366 }
7367 }
7368 }
Eric Laurent10351942014-05-08 18:49:52 -07007369 }
7370 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
7371 mAudioSource != (audio_source_t)value) {
7372 // forward device change to effects that have requested to be
7373 // aware of attached audio device.
7374 for (size_t i = 0; i < mEffectChains.size(); i++) {
7375 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08007376 }
Eric Laurent10351942014-05-08 18:49:52 -07007377 mAudioSource = (audio_source_t)value;
7378 }
Glenn Kastene198c362013-08-13 09:13:36 -07007379
Eric Laurent10351942014-05-08 18:49:52 -07007380 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007381 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007382 if (status == INVALID_OPERATION) {
7383 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007384 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007385 }
7386 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007387 if (status == BAD_VALUE) {
7388 uint32_t sRate;
7389 audio_channel_mask_t channelMask;
7390 audio_format_t format;
7391 if (mInput->stream->getAudioProperties(&sRate, &channelMask, &format) == OK &&
7392 audio_is_linear_pcm(format) && audio_is_linear_pcm(reqFormat) &&
7393 sRate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
7394 audio_channel_count_from_in_mask(channelMask) <= FCC_8) {
7395 status = NO_ERROR;
7396 }
Eric Laurent81784c32012-11-19 14:55:58 -08007397 }
Eric Laurent10351942014-05-08 18:49:52 -07007398 if (status == NO_ERROR) {
7399 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007400 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08007401 }
7402 }
Eric Laurent81784c32012-11-19 14:55:58 -08007403 }
Eric Laurent10351942014-05-08 18:49:52 -07007404
Eric Laurent81784c32012-11-19 14:55:58 -08007405 return reconfig;
7406}
7407
7408String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
7409{
Eric Laurent81784c32012-11-19 14:55:58 -08007410 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007411 if (initCheck() == NO_ERROR) {
7412 String8 out_s8;
7413 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
7414 return out_s8;
7415 }
Eric Laurent81784c32012-11-19 14:55:58 -08007416 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007417 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08007418}
7419
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007420void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007421 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7422
7423 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08007424
7425 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007426 case AUDIO_INPUT_OPENED:
7427 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07007428 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07007429 desc->mChannelMask = mChannelMask;
7430 desc->mSamplingRate = mSampleRate;
7431 desc->mFormat = mFormat;
7432 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07007433 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07007434 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007435 break;
7436
Eric Laurent73e26b62015-04-27 16:55:58 -07007437 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08007438 default:
7439 break;
7440 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007441 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08007442}
7443
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007444void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007445{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007446 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
7447 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hunge5412692014-05-16 11:25:07 -07007448 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007449 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_8, "HAL channel count %d > %d", mChannelCount, FCC_8);
Andy Hung463be252014-07-10 16:56:07 -07007450 mFormat = mHALFormat;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007451 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
7452 result = mInput->stream->getFrameSize(&mFrameSize);
7453 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
7454 result = mInput->stream->getBufferSize(&mBufferSize);
7455 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08007456 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007457 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08007458 // 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 -07007459 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08007460 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007461 // A larger value should allow more old data to be read after a track calls start(),
7462 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07007463 //
7464 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08007465 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07007466 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07007467 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07007468 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007469
7470 // TODO optimize audio capture buffer sizes ...
7471 // Here we calculate the size of the sliding buffer used as a source
7472 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
7473 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
7474 // be better to have it derived from the pipe depth in the long term.
7475 // The current value is higher than necessary. However it should not add to latency.
7476
Glenn Kasten85948432013-08-19 12:09:05 -07007477 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Glenn Kasten1b291842016-07-18 14:55:21 -07007478 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
7479 (void)posix_memalign(&mRsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
7480 memset(mRsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize); // if posix_memalign fails, will segv here.
Eric Laurent81784c32012-11-19 14:55:58 -08007481
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007482 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
7483 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08007484}
7485
Glenn Kasten5f972c02014-01-13 09:59:31 -08007486uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08007487{
7488 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007489 uint32_t result;
7490 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
7491 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08007492 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007493 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007494}
7495
Eric Laurent4c415062016-06-17 16:14:16 -07007496// hasAudioSession_l() must be called with ThreadBase::mLock held
7497uint32_t AudioFlinger::RecordThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08007498{
Eric Laurent81784c32012-11-19 14:55:58 -08007499 uint32_t result = 0;
7500 if (getEffectChain_l(sessionId) != 0) {
7501 result = EFFECT_SESSION;
7502 }
7503
7504 for (size_t i = 0; i < mTracks.size(); ++i) {
7505 if (sessionId == mTracks[i]->sessionId()) {
7506 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07007507 if (mTracks[i]->isFastTrack()) {
7508 result |= FAST_SESSION;
7509 }
Eric Laurent81784c32012-11-19 14:55:58 -08007510 break;
7511 }
7512 }
7513
7514 return result;
7515}
7516
Glenn Kastend848eb42016-03-08 13:42:11 -08007517KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08007518{
Glenn Kastend848eb42016-03-08 13:42:11 -08007519 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08007520 Mutex::Autolock _l(mLock);
7521 for (size_t j = 0; j < mTracks.size(); ++j) {
7522 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08007523 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08007524 if (ids.indexOfKey(sessionId) < 0) {
7525 ids.add(sessionId, true);
7526 }
7527 }
7528 return ids;
7529}
7530
7531AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7532{
7533 Mutex::Autolock _l(mLock);
7534 AudioStreamIn *input = mInput;
7535 mInput = NULL;
7536 return input;
7537}
7538
7539// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007540sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08007541{
7542 if (mInput == NULL) {
7543 return NULL;
7544 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007545 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08007546}
7547
7548status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7549{
7550 // only one chain per input thread
7551 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07007552 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08007553 return INVALID_OPERATION;
7554 }
7555 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07007556 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08007557 chain->setInBuffer(NULL);
7558 chain->setOutBuffer(NULL);
7559
7560 checkSuspendOnAddEffectChain_l(chain);
7561
Eric Laurent1b928682014-10-02 19:41:47 -07007562 // make sure enabled pre processing effects state is communicated to the HAL as we
7563 // just moved them to a new input stream.
7564 chain->syncHalEffectsState();
7565
Eric Laurent81784c32012-11-19 14:55:58 -08007566 mEffectChains.add(chain);
7567
7568 return NO_ERROR;
7569}
7570
7571size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7572{
7573 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7574 ALOGW_IF(mEffectChains.size() != 1,
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007575 "removeEffectChain_l() %p invalid chain size %zu on thread %p",
Eric Laurent81784c32012-11-19 14:55:58 -08007576 chain.get(), mEffectChains.size(), this);
7577 if (mEffectChains.size() == 1) {
7578 mEffectChains.removeAt(0);
7579 }
7580 return 0;
7581}
7582
Eric Laurent1c333e22014-05-20 10:48:17 -07007583status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7584 audio_patch_handle_t *handle)
7585{
7586 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007587
7588 // store new device and send to effects
7589 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07007590 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07007591 for (size_t i = 0; i < mEffectChains.size(); i++) {
7592 mEffectChains[i]->setDevice_l(mInDevice);
7593 }
7594
7595 // disable AEC and NS if the device is a BT SCO headset supporting those
7596 // pre processings
7597 if (mTracks.size() > 0) {
7598 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7599 mAudioFlinger->btNrecIsOff();
7600 for (size_t i = 0; i < mTracks.size(); i++) {
7601 sp<RecordTrack> track = mTracks[i];
7602 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7603 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
7604 }
7605 }
7606
7607 // store new source and send to effects
7608 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7609 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07007610 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07007611 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07007612 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007613 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007614
Eric Laurent054d9d32015-04-24 08:48:48 -07007615 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007616 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7617 status = hwDevice->createAudioPatch(patch->num_sources,
7618 patch->sources,
7619 patch->num_sinks,
7620 patch->sinks,
7621 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007622 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007623 char *address;
7624 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7625 address = audio_device_address_to_parameter(
7626 patch->sources[0].ext.device.type,
7627 patch->sources[0].ext.device.address);
7628 } else {
7629 address = (char *)calloc(1, 1);
7630 }
7631 AudioParameter param = AudioParameter(String8(address));
7632 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007633 param.addInt(String8(AudioParameter::keyRouting),
Eric Laurent054d9d32015-04-24 08:48:48 -07007634 (int)patch->sources[0].ext.device.type);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007635 param.addInt(String8(AudioParameter::keyInputSource),
Eric Laurent054d9d32015-04-24 08:48:48 -07007636 (int)patch->sinks[0].ext.mix.usecase.source);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007637 status = mInput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07007638 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07007639 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007640
Eric Laurente8726fe2015-06-26 09:39:24 -07007641 if (mInDevice != mPrevInDevice) {
7642 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7643 mPrevInDevice = mInDevice;
7644 }
Eric Laurent296fb132015-05-01 11:38:42 -07007645
Eric Laurent1c333e22014-05-20 10:48:17 -07007646 return status;
7647}
7648
7649status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7650{
7651 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007652
7653 mInDevice = AUDIO_DEVICE_NONE;
7654
Eric Laurent1c333e22014-05-20 10:48:17 -07007655 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007656 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7657 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007658 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007659 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07007660 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007661 status = mInput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07007662 }
7663 return status;
7664}
7665
Eric Laurent83b88082014-06-20 18:31:16 -07007666void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
7667{
7668 Mutex::Autolock _l(mLock);
7669 mTracks.add(record);
7670}
7671
7672void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
7673{
7674 Mutex::Autolock _l(mLock);
7675 destroyTrack_l(record);
7676}
7677
7678void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
7679{
7680 ThreadBase::getAudioPortConfig(config);
7681 config->role = AUDIO_PORT_ROLE_SINK;
7682 config->ext.mix.hw_module = mInput->audioHwDev->handle();
7683 config->ext.mix.usecase.source = mAudioSource;
7684}
Eric Laurent1c333e22014-05-20 10:48:17 -07007685
Glenn Kasten63238ef2015-03-02 15:50:29 -08007686} // namespace android