blob: b9d66e9d0e874524cf11d1bb633a199bbcbf7d8a [file] [log] [blame]
Eric Laurent81784c32012-11-19 14:55:58 -08001/*
2**
3** Copyright 2012, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
Alex Ray371eb972012-11-30 11:11:54 -080021#define ATRACE_TAG ATRACE_TAG_AUDIO
Eric Laurent81784c32012-11-19 14:55:58 -080022
Glenn Kasten153b9fe2013-07-15 11:23:36 -070023#include "Configuration.h"
Eric Laurent81784c32012-11-19 14:55:58 -080024#include <math.h>
25#include <fcntl.h>
Glenn Kastenad8510a2015-02-17 16:24:07 -080026#include <linux/futex.h>
Eric Laurent81784c32012-11-19 14:55:58 -080027#include <sys/stat.h>
Glenn Kastenad8510a2015-02-17 16:24:07 -080028#include <sys/syscall.h>
Eric Laurent81784c32012-11-19 14:55:58 -080029#include <cutils/properties.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070030#include <media/AudioParameter.h>
Andy Hungcd044842014-08-07 11:04:34 -070031#include <media/AudioResamplerPublic.h>
Eric Laurent81784c32012-11-19 14:55:58 -080032#include <utils/Log.h>
Alex Ray371eb972012-11-30 11:11:54 -080033#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080034
35#include <private/media/AudioTrackShared.h>
36#include <hardware/audio.h>
37#include <audio_effects/effect_ns.h>
38#include <audio_effects/effect_aec.h>
Andy Hung2ddee192015-12-18 17:34:44 -080039#include <audio_utils/conversion.h>
Eric Laurent81784c32012-11-19 14:55:58 -080040#include <audio_utils/primitives.h>
Andy Hung98ef9782014-03-04 14:46:50 -080041#include <audio_utils/format.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070042#include <audio_utils/minifloat.h>
Eric Laurent81784c32012-11-19 14:55:58 -080043
44// NBAIO implementations
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070045#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080046#include <media/nbaio/AudioStreamOutSink.h>
47#include <media/nbaio/MonoPipe.h>
48#include <media/nbaio/MonoPipeReader.h>
49#include <media/nbaio/Pipe.h>
50#include <media/nbaio/PipeReader.h>
51#include <media/nbaio/SourceAudioBufferProvider.h>
Wei Jia3f273d12015-11-24 09:06:49 -080052#include <mediautils/BatteryNotifier.h>
Eric Laurent81784c32012-11-19 14:55:58 -080053
54#include <powermanager/PowerManager.h>
55
Eric Laurent81784c32012-11-19 14:55:58 -080056#include "AudioFlinger.h"
57#include "AudioMixer.h"
Andy Hungd330ee42015-04-20 13:23:41 -070058#include "BufferProviders.h"
Eric Laurent81784c32012-11-19 14:55:58 -080059#include "FastMixer.h"
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070060#include "FastCapture.h"
Eric Laurent81784c32012-11-19 14:55:58 -080061#include "ServiceUtilities.h"
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -070062#include "mediautils/SchedulingPolicyService.h"
Eric Laurent81784c32012-11-19 14:55:58 -080063
Eric Laurent81784c32012-11-19 14:55:58 -080064#ifdef ADD_BATTERY_DATA
65#include <media/IMediaPlayerService.h>
66#include <media/IMediaDeathNotifier.h>
67#endif
68
Eric Laurent81784c32012-11-19 14:55:58 -080069#ifdef DEBUG_CPU_USAGE
70#include <cpustats/CentralTendencyStatistics.h>
71#include <cpustats/ThreadCpuUsage.h>
72#endif
73
74// ----------------------------------------------------------------------------
75
76// Note: the following macro is used for extremely verbose logging message. In
77// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
78// 0; but one side effect of this is to turn all LOGV's as well. Some messages
79// are so verbose that we want to suppress them even when we have ALOG_ASSERT
80// turned on. Do not uncomment the #def below unless you really know what you
81// are doing and want to see all of the extremely verbose messages.
82//#define VERY_VERY_VERBOSE_LOGGING
83#ifdef VERY_VERY_VERBOSE_LOGGING
84#define ALOGVV ALOGV
85#else
86#define ALOGVV(a...) do { } while(0)
87#endif
88
Andy Hung6770c6f2015-04-07 13:43:36 -070089// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -070090#define max(a, b) ((a) > (b) ? (a) : (b))
Andy Hung6770c6f2015-04-07 13:43:36 -070091template <typename T>
92static inline T min(const T& a, const T& b)
93{
94 return a < b ? a : b;
95}
Glenn Kasten49d00ad2014-07-21 11:22:03 -070096
Andy Hungd330ee42015-04-20 13:23:41 -070097#ifndef ARRAY_SIZE
98#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
99#endif
100
Eric Laurent81784c32012-11-19 14:55:58 -0800101namespace android {
102
103// retry counts for buffer fill timeout
104// 50 * ~20msecs = 1 second
105static const int8_t kMaxTrackRetries = 50;
106static const int8_t kMaxTrackStartupRetries = 50;
107// allow less retry attempts on direct output thread.
108// direct outputs can be a scarce resource in audio hardware and should
109// be released as quickly as possible.
110static const int8_t kMaxTrackRetriesDirect = 2;
Eric Laurent51716182016-02-29 18:00:56 -0800111// retry count before removing active track in case of underrun on offloaded thread:
112// we need to make sure that AudioTrack client has enough time to send large buffers
113//FIXME may be more appropriate if expressed in time units. Need to revise how underrun is handled
114// for offloaded tracks
115static const int8_t kMaxTrackRetriesOffload = 10;
116static const int8_t kMaxTrackStartupRetriesOffload = 100;
117
Eric Laurent81784c32012-11-19 14:55:58 -0800118
119// don't warn about blocked writes or record buffer overflows more often than this
120static const nsecs_t kWarningThrottleNs = seconds(5);
121
122// RecordThread loop sleep time upon application overrun or audio HAL read error
123static const int kRecordThreadSleepUs = 5000;
124
Eric Laurent10351942014-05-08 18:49:52 -0700125// maximum time to wait in sendConfigEvent_l() for a status to be received
126static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800127
128// minimum sleep time for the mixer thread loop when tracks are active but in underrun
129static const uint32_t kMinThreadSleepTimeUs = 5000;
130// maximum divider applied to the active sleep time in the mixer thread loop
131static const uint32_t kMaxThreadSleepTimeShift = 2;
132
Andy Hung09a50072014-02-27 14:30:47 -0800133// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700134// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800135static const uint32_t kMinNormalSinkBufferSizeMs = 20;
136// maximum normal sink buffer size
137static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800138
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700139// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
140// FIXME This should be based on experimentally observed scheduling jitter
141static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
142
Eric Laurent972a1732013-09-04 09:42:59 -0700143// Offloaded output thread standby delay: allows track transition without going to standby
144static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
145
Eric Laurent51716182016-02-29 18:00:56 -0800146// Direct output thread minimum sleep time in idle or active(underrun) state
147static const nsecs_t kDirectMinSleepTimeUs = 10000;
148
149// Offloaded output bit rate in bits per second when unknown.
150// Used for sleep time calculation, so use a high default bitrate to be conservative on sleep time.
151static const uint32_t kOffloadDefaultBitRateBps = 1500000;
152
153
Eric Laurent81784c32012-11-19 14:55:58 -0800154// Whether to use fast mixer
155static const enum {
156 FastMixer_Never, // never initialize or use: for debugging only
157 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
158 // normal mixer multiplier is 1
159 FastMixer_Static, // initialize if needed, then use all the time if initialized,
160 // multiplier is calculated based on min & max normal mixer buffer size
161 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
162 // multiplier is calculated based on min & max normal mixer buffer size
163 // FIXME for FastMixer_Dynamic:
164 // Supporting this option will require fixing HALs that can't handle large writes.
165 // For example, one HAL implementation returns an error from a large write,
166 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
167 // We could either fix the HAL implementations, or provide a wrapper that breaks
168 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
169} kUseFastMixer = FastMixer_Static;
170
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700171// Whether to use fast capture
172static const enum {
173 FastCapture_Never, // never initialize or use: for debugging only
174 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
175 FastCapture_Static, // initialize if needed, then use all the time if initialized
176} kUseFastCapture = FastCapture_Static;
177
Eric Laurent81784c32012-11-19 14:55:58 -0800178// Priorities for requestPriority
179static const int kPriorityAudioApp = 2;
180static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700181static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800182
183// IAudioFlinger::createTrack() reports back to client the total size of shared memory area
184// for the track. The client then sub-divides this into smaller buffers for its use.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800185// Currently the client uses N-buffering by default, but doesn't tell us about the value of N.
186// So for now we just assume that client is double-buffered for fast tracks.
187// FIXME It would be better for client to tell AudioFlinger the value of N,
188// so AudioFlinger could allocate the right amount of memory.
Eric Laurent81784c32012-11-19 14:55:58 -0800189// See the client's minBufCount and mNotificationFramesAct calculations for details.
Glenn Kasten03490092014-05-27 12:30:54 -0700190
191// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800192static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800193
Glenn Kasten03490092014-05-27 12:30:54 -0700194// The minimum and maximum allowed values
195static const int kFastTrackMultiplierMin = 1;
196static const int kFastTrackMultiplierMax = 2;
197
198// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
199static int sFastTrackMultiplier = kFastTrackMultiplier;
200
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700201// See Thread::readOnlyHeap().
202// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
203// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
204// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Glenn Kasten9f81de32014-07-27 15:02:23 -0700205static const size_t kRecordThreadReadOnlyHeapSize = 0x2000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700206
Eric Laurent81784c32012-11-19 14:55:58 -0800207// ----------------------------------------------------------------------------
208
Glenn Kasten03490092014-05-27 12:30:54 -0700209static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
210
211static void sFastTrackMultiplierInit()
212{
213 char value[PROPERTY_VALUE_MAX];
214 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
215 char *endptr;
216 unsigned long ul = strtoul(value, &endptr, 0);
217 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
218 sFastTrackMultiplier = (int) ul;
219 }
220 }
221}
222
223// ----------------------------------------------------------------------------
224
Eric Laurent81784c32012-11-19 14:55:58 -0800225#ifdef ADD_BATTERY_DATA
226// To collect the amplifier usage
227static void addBatteryData(uint32_t params) {
228 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
229 if (service == NULL) {
230 // it already logged
231 return;
232 }
233
234 service->addBatteryData(params);
235}
236#endif
237
Andy Hung3f0c9022016-01-15 17:49:46 -0800238// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
239struct {
240 // call when you acquire a partial wakelock
241 void acquire(const sp<IBinder> &wakeLockToken) {
242 pthread_mutex_lock(&mLock);
243 if (wakeLockToken.get() == nullptr) {
244 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
245 } else {
246 if (mCount == 0) {
247 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
248 }
249 ++mCount;
250 }
251 pthread_mutex_unlock(&mLock);
252 }
253
254 // call when you release a partial wakelock.
255 void release(const sp<IBinder> &wakeLockToken) {
256 if (wakeLockToken.get() == nullptr) {
257 return;
258 }
259 pthread_mutex_lock(&mLock);
260 if (--mCount < 0) {
261 ALOGE("negative wakelock count");
262 mCount = 0;
263 }
264 pthread_mutex_unlock(&mLock);
265 }
266
267 // retrieves the boottime timebase offset from monotonic.
268 int64_t getBoottimeOffset() {
269 pthread_mutex_lock(&mLock);
270 int64_t boottimeOffset = mBoottimeOffset;
271 pthread_mutex_unlock(&mLock);
272 return boottimeOffset;
273 }
274
275 // Adjusts the timebase offset between TIMEBASE_MONOTONIC
276 // and the selected timebase.
277 // Currently only TIMEBASE_BOOTTIME is allowed.
278 //
279 // This only needs to be called upon acquiring the first partial wakelock
280 // after all other partial wakelocks are released.
281 //
282 // We do an empirical measurement of the offset rather than parsing
283 // /proc/timer_list since the latter is not a formal kernel ABI.
284 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
285 int clockbase;
286 switch (timebase) {
287 case ExtendedTimestamp::TIMEBASE_BOOTTIME:
288 clockbase = SYSTEM_TIME_BOOTTIME;
289 break;
290 default:
291 LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
292 break;
293 }
294 // try three times to get the clock offset, choose the one
295 // with the minimum gap in measurements.
296 const int tries = 3;
297 nsecs_t bestGap, measured;
298 for (int i = 0; i < tries; ++i) {
299 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
300 const nsecs_t tbase = systemTime(clockbase);
301 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
302 const nsecs_t gap = tmono2 - tmono;
303 if (i == 0 || gap < bestGap) {
304 bestGap = gap;
305 measured = tbase - ((tmono + tmono2) >> 1);
306 }
307 }
308
309 // to avoid micro-adjusting, we don't change the timebase
310 // unless it is significantly different.
311 //
312 // Assumption: It probably takes more than toleranceNs to
313 // suspend and resume the device.
314 static int64_t toleranceNs = 10000; // 10 us
315 if (llabs(*offset - measured) > toleranceNs) {
316 ALOGV("Adjusting timebase offset old: %lld new: %lld",
317 (long long)*offset, (long long)measured);
318 *offset = measured;
319 }
320 }
321
322 pthread_mutex_t mLock;
323 int32_t mCount;
324 int64_t mBoottimeOffset;
325} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
Eric Laurent81784c32012-11-19 14:55:58 -0800326
327// ----------------------------------------------------------------------------
328// CPU Stats
329// ----------------------------------------------------------------------------
330
331class CpuStats {
332public:
333 CpuStats();
334 void sample(const String8 &title);
335#ifdef DEBUG_CPU_USAGE
336private:
337 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
338 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
339
340 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
341
342 int mCpuNum; // thread's current CPU number
343 int mCpukHz; // frequency of thread's current CPU in kHz
344#endif
345};
346
347CpuStats::CpuStats()
348#ifdef DEBUG_CPU_USAGE
349 : mCpuNum(-1), mCpukHz(-1)
350#endif
351{
352}
353
Glenn Kasten0f11b512014-01-31 16:18:54 -0800354void CpuStats::sample(const String8 &title
355#ifndef DEBUG_CPU_USAGE
356 __unused
357#endif
358 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800359#ifdef DEBUG_CPU_USAGE
360 // get current thread's delta CPU time in wall clock ns
361 double wcNs;
362 bool valid = mCpuUsage.sampleAndEnable(wcNs);
363
364 // record sample for wall clock statistics
365 if (valid) {
366 mWcStats.sample(wcNs);
367 }
368
369 // get the current CPU number
370 int cpuNum = sched_getcpu();
371
372 // get the current CPU frequency in kHz
373 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
374
375 // check if either CPU number or frequency changed
376 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
377 mCpuNum = cpuNum;
378 mCpukHz = cpukHz;
379 // ignore sample for purposes of cycles
380 valid = false;
381 }
382
383 // if no change in CPU number or frequency, then record sample for cycle statistics
384 if (valid && mCpukHz > 0) {
385 double cycles = wcNs * cpukHz * 0.000001;
386 mHzStats.sample(cycles);
387 }
388
389 unsigned n = mWcStats.n();
390 // mCpuUsage.elapsed() is expensive, so don't call it every loop
391 if ((n & 127) == 1) {
392 long long elapsed = mCpuUsage.elapsed();
393 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
394 double perLoop = elapsed / (double) n;
395 double perLoop100 = perLoop * 0.01;
396 double perLoop1k = perLoop * 0.001;
397 double mean = mWcStats.mean();
398 double stddev = mWcStats.stddev();
399 double minimum = mWcStats.minimum();
400 double maximum = mWcStats.maximum();
401 double meanCycles = mHzStats.mean();
402 double stddevCycles = mHzStats.stddev();
403 double minCycles = mHzStats.minimum();
404 double maxCycles = mHzStats.maximum();
405 mCpuUsage.resetElapsed();
406 mWcStats.reset();
407 mHzStats.reset();
408 ALOGD("CPU usage for %s over past %.1f secs\n"
409 " (%u mixer loops at %.1f mean ms per loop):\n"
410 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
411 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
412 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
413 title.string(),
414 elapsed * .000000001, n, perLoop * .000001,
415 mean * .001,
416 stddev * .001,
417 minimum * .001,
418 maximum * .001,
419 mean / perLoop100,
420 stddev / perLoop100,
421 minimum / perLoop100,
422 maximum / perLoop100,
423 meanCycles / perLoop1k,
424 stddevCycles / perLoop1k,
425 minCycles / perLoop1k,
426 maxCycles / perLoop1k);
427
428 }
429 }
430#endif
431};
432
433// ----------------------------------------------------------------------------
434// ThreadBase
435// ----------------------------------------------------------------------------
436
Glenn Kasten97b7b752014-09-28 13:04:24 -0700437// static
438const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
439{
440 switch (type) {
441 case MIXER:
442 return "MIXER";
443 case DIRECT:
444 return "DIRECT";
445 case DUPLICATING:
446 return "DUPLICATING";
447 case RECORD:
448 return "RECORD";
449 case OFFLOAD:
450 return "OFFLOAD";
451 default:
452 return "unknown";
453 }
454}
455
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800456String8 devicesToString(audio_devices_t devices)
457{
458 static const struct mapping {
459 audio_devices_t mDevices;
460 const char * mString;
461 } mappingsOut[] = {
Glenn Kasten818da522015-12-02 13:53:26 -0800462 {AUDIO_DEVICE_OUT_EARPIECE, "EARPIECE"},
463 {AUDIO_DEVICE_OUT_SPEAKER, "SPEAKER"},
464 {AUDIO_DEVICE_OUT_WIRED_HEADSET, "WIRED_HEADSET"},
465 {AUDIO_DEVICE_OUT_WIRED_HEADPHONE, "WIRED_HEADPHONE"},
466 {AUDIO_DEVICE_OUT_BLUETOOTH_SCO, "BLUETOOTH_SCO"},
467 {AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET, "BLUETOOTH_SCO_HEADSET"},
468 {AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT, "BLUETOOTH_SCO_CARKIT"},
469 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, "BLUETOOTH_A2DP"},
470 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,"BLUETOOTH_A2DP_HEADPHONES"},
471 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER, "BLUETOOTH_A2DP_SPEAKER"},
472 {AUDIO_DEVICE_OUT_AUX_DIGITAL, "AUX_DIGITAL"},
473 {AUDIO_DEVICE_OUT_HDMI, "HDMI"},
474 {AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET,"ANLG_DOCK_HEADSET"},
475 {AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET,"DGTL_DOCK_HEADSET"},
476 {AUDIO_DEVICE_OUT_USB_ACCESSORY, "USB_ACCESSORY"},
477 {AUDIO_DEVICE_OUT_USB_DEVICE, "USB_DEVICE"},
478 {AUDIO_DEVICE_OUT_TELEPHONY_TX, "TELEPHONY_TX"},
479 {AUDIO_DEVICE_OUT_LINE, "LINE"},
480 {AUDIO_DEVICE_OUT_HDMI_ARC, "HDMI_ARC"},
481 {AUDIO_DEVICE_OUT_SPDIF, "SPDIF"},
482 {AUDIO_DEVICE_OUT_FM, "FM"},
483 {AUDIO_DEVICE_OUT_AUX_LINE, "AUX_LINE"},
484 {AUDIO_DEVICE_OUT_SPEAKER_SAFE, "SPEAKER_SAFE"},
485 {AUDIO_DEVICE_OUT_IP, "IP"},
Eric Laurent58545be2016-02-22 18:54:20 -0800486 {AUDIO_DEVICE_OUT_BUS, "BUS"},
Glenn Kasten818da522015-12-02 13:53:26 -0800487 {AUDIO_DEVICE_NONE, "NONE"}, // must be last
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800488 }, mappingsIn[] = {
Glenn Kasten818da522015-12-02 13:53:26 -0800489 {AUDIO_DEVICE_IN_COMMUNICATION, "COMMUNICATION"},
490 {AUDIO_DEVICE_IN_AMBIENT, "AMBIENT"},
491 {AUDIO_DEVICE_IN_BUILTIN_MIC, "BUILTIN_MIC"},
492 {AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET, "BLUETOOTH_SCO_HEADSET"},
493 {AUDIO_DEVICE_IN_WIRED_HEADSET, "WIRED_HEADSET"},
494 {AUDIO_DEVICE_IN_AUX_DIGITAL, "AUX_DIGITAL"},
495 {AUDIO_DEVICE_IN_VOICE_CALL, "VOICE_CALL"},
496 {AUDIO_DEVICE_IN_TELEPHONY_RX, "TELEPHONY_RX"},
497 {AUDIO_DEVICE_IN_BACK_MIC, "BACK_MIC"},
498 {AUDIO_DEVICE_IN_REMOTE_SUBMIX, "REMOTE_SUBMIX"},
499 {AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET, "ANLG_DOCK_HEADSET"},
500 {AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET, "DGTL_DOCK_HEADSET"},
501 {AUDIO_DEVICE_IN_USB_ACCESSORY, "USB_ACCESSORY"},
502 {AUDIO_DEVICE_IN_USB_DEVICE, "USB_DEVICE"},
503 {AUDIO_DEVICE_IN_FM_TUNER, "FM_TUNER"},
504 {AUDIO_DEVICE_IN_TV_TUNER, "TV_TUNER"},
505 {AUDIO_DEVICE_IN_LINE, "LINE"},
506 {AUDIO_DEVICE_IN_SPDIF, "SPDIF"},
507 {AUDIO_DEVICE_IN_BLUETOOTH_A2DP, "BLUETOOTH_A2DP"},
508 {AUDIO_DEVICE_IN_LOOPBACK, "LOOPBACK"},
509 {AUDIO_DEVICE_IN_IP, "IP"},
Eric Laurent58545be2016-02-22 18:54:20 -0800510 {AUDIO_DEVICE_IN_BUS, "BUS"},
Glenn Kasten818da522015-12-02 13:53:26 -0800511 {AUDIO_DEVICE_NONE, "NONE"}, // must be last
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800512 };
513 String8 result;
514 audio_devices_t allDevices = AUDIO_DEVICE_NONE;
515 const mapping *entry;
516 if (devices & AUDIO_DEVICE_BIT_IN) {
517 devices &= ~AUDIO_DEVICE_BIT_IN;
518 entry = mappingsIn;
519 } else {
520 entry = mappingsOut;
521 }
522 for ( ; entry->mDevices != AUDIO_DEVICE_NONE; entry++) {
523 allDevices = (audio_devices_t) (allDevices | entry->mDevices);
524 if (devices & entry->mDevices) {
525 if (!result.isEmpty()) {
526 result.append("|");
527 }
528 result.append(entry->mString);
529 }
530 }
531 if (devices & ~allDevices) {
532 if (!result.isEmpty()) {
533 result.append("|");
534 }
535 result.appendFormat("0x%X", devices & ~allDevices);
536 }
537 if (result.isEmpty()) {
538 result.append(entry->mString);
539 }
540 return result;
541}
542
543String8 inputFlagsToString(audio_input_flags_t flags)
544{
545 static const struct mapping {
546 audio_input_flags_t mFlag;
547 const char * mString;
548 } mappings[] = {
Glenn Kasten818da522015-12-02 13:53:26 -0800549 {AUDIO_INPUT_FLAG_FAST, "FAST"},
550 {AUDIO_INPUT_FLAG_HW_HOTWORD, "HW_HOTWORD"},
551 {AUDIO_INPUT_FLAG_RAW, "RAW"},
552 {AUDIO_INPUT_FLAG_SYNC, "SYNC"},
553 {AUDIO_INPUT_FLAG_NONE, "NONE"}, // must be last
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800554 };
555 String8 result;
556 audio_input_flags_t allFlags = AUDIO_INPUT_FLAG_NONE;
557 const mapping *entry;
558 for (entry = mappings; entry->mFlag != AUDIO_INPUT_FLAG_NONE; entry++) {
559 allFlags = (audio_input_flags_t) (allFlags | entry->mFlag);
560 if (flags & entry->mFlag) {
561 if (!result.isEmpty()) {
562 result.append("|");
563 }
564 result.append(entry->mString);
565 }
566 }
567 if (flags & ~allFlags) {
568 if (!result.isEmpty()) {
569 result.append("|");
570 }
571 result.appendFormat("0x%X", flags & ~allFlags);
572 }
573 if (result.isEmpty()) {
574 result.append(entry->mString);
575 }
576 return result;
577}
578
579String8 outputFlagsToString(audio_output_flags_t flags)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700580{
581 static const struct mapping {
582 audio_output_flags_t mFlag;
583 const char * mString;
584 } mappings[] = {
Glenn Kasten818da522015-12-02 13:53:26 -0800585 {AUDIO_OUTPUT_FLAG_DIRECT, "DIRECT"},
586 {AUDIO_OUTPUT_FLAG_PRIMARY, "PRIMARY"},
587 {AUDIO_OUTPUT_FLAG_FAST, "FAST"},
588 {AUDIO_OUTPUT_FLAG_DEEP_BUFFER, "DEEP_BUFFER"},
589 {AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,"COMPRESS_OFFLOAD"},
590 {AUDIO_OUTPUT_FLAG_NON_BLOCKING, "NON_BLOCKING"},
591 {AUDIO_OUTPUT_FLAG_HW_AV_SYNC, "HW_AV_SYNC"},
592 {AUDIO_OUTPUT_FLAG_RAW, "RAW"},
593 {AUDIO_OUTPUT_FLAG_SYNC, "SYNC"},
594 {AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO, "IEC958_NONAUDIO"},
595 {AUDIO_OUTPUT_FLAG_NONE, "NONE"}, // must be last
Glenn Kasten97b7b752014-09-28 13:04:24 -0700596 };
597 String8 result;
598 audio_output_flags_t allFlags = AUDIO_OUTPUT_FLAG_NONE;
599 const mapping *entry;
600 for (entry = mappings; entry->mFlag != AUDIO_OUTPUT_FLAG_NONE; entry++) {
601 allFlags = (audio_output_flags_t) (allFlags | entry->mFlag);
602 if (flags & entry->mFlag) {
603 if (!result.isEmpty()) {
604 result.append("|");
605 }
606 result.append(entry->mString);
607 }
608 }
609 if (flags & ~allFlags) {
610 if (!result.isEmpty()) {
611 result.append("|");
612 }
613 result.appendFormat("0x%X", flags & ~allFlags);
614 }
615 if (result.isEmpty()) {
616 result.append(entry->mString);
617 }
618 return result;
619}
620
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800621const char *sourceToString(audio_source_t source)
622{
623 switch (source) {
624 case AUDIO_SOURCE_DEFAULT: return "default";
625 case AUDIO_SOURCE_MIC: return "mic";
626 case AUDIO_SOURCE_VOICE_UPLINK: return "voice uplink";
627 case AUDIO_SOURCE_VOICE_DOWNLINK: return "voice downlink";
628 case AUDIO_SOURCE_VOICE_CALL: return "voice call";
629 case AUDIO_SOURCE_CAMCORDER: return "camcorder";
630 case AUDIO_SOURCE_VOICE_RECOGNITION: return "voice recognition";
631 case AUDIO_SOURCE_VOICE_COMMUNICATION: return "voice communication";
632 case AUDIO_SOURCE_REMOTE_SUBMIX: return "remote submix";
rago8a397d52015-12-02 11:27:57 -0800633 case AUDIO_SOURCE_UNPROCESSED: return "unprocessed";
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800634 case AUDIO_SOURCE_FM_TUNER: return "FM tuner";
635 case AUDIO_SOURCE_HOTWORD: return "hotword";
636 default: return "unknown";
637 }
638}
639
Eric Laurent81784c32012-11-19 14:55:58 -0800640AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -0700641 audio_devices_t outDevice, audio_devices_t inDevice, type_t type, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -0800642 : Thread(false /*canCallJava*/),
643 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700644 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700645 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800646 // are set by PlaybackThread::readOutputParameters_l() or
647 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700648 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800649 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700650 mPrevOutDevice(AUDIO_DEVICE_NONE), mPrevInDevice(AUDIO_DEVICE_NONE),
651 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800652 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700653 mDeathRecipient(new PMDeathRecipient(this)),
Wei Jia3f273d12015-11-24 09:06:49 -0800654 mSystemReady(systemReady),
655 mNotifiedBatteryStart(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800656{
Eric Laurent296fb132015-05-01 11:38:42 -0700657 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800658}
659
660AudioFlinger::ThreadBase::~ThreadBase()
661{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700662 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700663 mConfigEvents.clear();
664
Eric Laurent81784c32012-11-19 14:55:58 -0800665 // do not lock the mutex in destructor
666 releaseWakeLock_l();
667 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800668 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800669 binder->unlinkToDeath(mDeathRecipient);
670 }
671}
672
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700673status_t AudioFlinger::ThreadBase::readyToRun()
674{
675 status_t status = initCheck();
676 if (status == NO_ERROR) {
677 ALOGI("AudioFlinger's thread %p ready to run", this);
678 } else {
679 ALOGE("No working audio driver found.");
680 }
681 return status;
682}
683
Eric Laurent81784c32012-11-19 14:55:58 -0800684void AudioFlinger::ThreadBase::exit()
685{
686 ALOGV("ThreadBase::exit");
687 // do any cleanup required for exit to succeed
688 preExit();
689 {
690 // This lock prevents the following race in thread (uniprocessor for illustration):
691 // if (!exitPending()) {
692 // // context switch from here to exit()
693 // // exit() calls requestExit(), what exitPending() observes
694 // // exit() calls signal(), which is dropped since no waiters
695 // // context switch back from exit() to here
696 // mWaitWorkCV.wait(...);
697 // // now thread is hung
698 // }
699 AutoMutex lock(mLock);
700 requestExit();
701 mWaitWorkCV.broadcast();
702 }
703 // When Thread::requestExitAndWait is made virtual and this method is renamed to
704 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
705 requestExitAndWait();
706}
707
708status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
709{
Eric Laurent81784c32012-11-19 14:55:58 -0800710 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
711 Mutex::Autolock _l(mLock);
712
Eric Laurent10351942014-05-08 18:49:52 -0700713 return sendSetParameterConfigEvent_l(keyValuePairs);
714}
715
716// sendConfigEvent_l() must be called with ThreadBase::mLock held
717// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
718status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
719{
720 status_t status = NO_ERROR;
721
Eric Laurent72e3f392015-05-20 14:43:50 -0700722 if (event->mRequiresSystemReady && !mSystemReady) {
723 event->mWaitStatus = false;
724 mPendingConfigEvents.add(event);
725 return status;
726 }
Eric Laurent10351942014-05-08 18:49:52 -0700727 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700728 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800729 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700730 mLock.unlock();
731 {
732 Mutex::Autolock _l(event->mLock);
733 while (event->mWaitStatus) {
734 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
735 event->mStatus = TIMED_OUT;
736 event->mWaitStatus = false;
737 }
738 }
739 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800740 }
Eric Laurent10351942014-05-08 18:49:52 -0700741 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800742 return status;
743}
744
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700745void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800746{
747 Mutex::Autolock _l(mLock);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700748 sendIoConfigEvent_l(event, pid);
Eric Laurent81784c32012-11-19 14:55:58 -0800749}
750
751// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700752void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800753{
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700754 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid);
Eric Laurent10351942014-05-08 18:49:52 -0700755 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800756}
757
Eric Laurent72e3f392015-05-20 14:43:50 -0700758void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio)
759{
760 Mutex::Autolock _l(mLock);
761 sendPrioConfigEvent_l(pid, tid, prio);
762}
763
Eric Laurent81784c32012-11-19 14:55:58 -0800764// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
765void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
766{
Eric Laurent10351942014-05-08 18:49:52 -0700767 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio);
768 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800769}
770
Eric Laurent10351942014-05-08 18:49:52 -0700771// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
772status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800773{
Andy Hung2ddee192015-12-18 17:34:44 -0800774 sp<ConfigEvent> configEvent;
775 AudioParameter param(keyValuePair);
776 int value;
777 if (param.getInt(String8(AUDIO_PARAMETER_MONO_OUTPUT), value) == NO_ERROR) {
778 setMasterMono_l(value != 0);
779 if (param.size() == 1) {
780 return NO_ERROR; // should be a solo parameter - we don't pass down
781 }
782 param.remove(String8(AUDIO_PARAMETER_MONO_OUTPUT));
783 configEvent = new SetParameterConfigEvent(param.toString());
784 } else {
785 configEvent = new SetParameterConfigEvent(keyValuePair);
786 }
Eric Laurent10351942014-05-08 18:49:52 -0700787 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700788}
789
Eric Laurent1c333e22014-05-20 10:48:17 -0700790status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
791 const struct audio_patch *patch,
792 audio_patch_handle_t *handle)
793{
794 Mutex::Autolock _l(mLock);
795 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
796 status_t status = sendConfigEvent_l(configEvent);
797 if (status == NO_ERROR) {
798 CreateAudioPatchConfigEventData *data =
799 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
800 *handle = data->mHandle;
801 }
802 return status;
803}
804
805status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
806 const audio_patch_handle_t handle)
807{
808 Mutex::Autolock _l(mLock);
809 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
810 return sendConfigEvent_l(configEvent);
811}
812
813
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700814// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700815void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700816{
Eric Laurent10351942014-05-08 18:49:52 -0700817 bool configChanged = false;
818
Eric Laurent81784c32012-11-19 14:55:58 -0800819 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700820 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700821 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800822 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700823 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700824 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700825 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
826 // FIXME Need to understand why this has to be done asynchronously
827 int err = requestPriority(data->mPid, data->mTid, data->mPrio,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700828 true /*asynchronous*/);
829 if (err != 0) {
830 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700831 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700832 }
833 } break;
834 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700835 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700836 ioConfigChanged(data->mEvent, data->mPid);
Eric Laurent10351942014-05-08 18:49:52 -0700837 } break;
838 case CFG_EVENT_SET_PARAMETER: {
839 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
840 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
841 configChanged = true;
Glenn Kastend5418eb2013-08-14 13:11:06 -0700842 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700843 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700844 case CFG_EVENT_CREATE_AUDIO_PATCH: {
845 CreateAudioPatchConfigEventData *data =
846 (CreateAudioPatchConfigEventData *)event->mData.get();
847 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
848 } break;
849 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
850 ReleaseAudioPatchConfigEventData *data =
851 (ReleaseAudioPatchConfigEventData *)event->mData.get();
852 event->mStatus = releaseAudioPatch_l(data->mHandle);
853 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700854 default:
Eric Laurent10351942014-05-08 18:49:52 -0700855 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700856 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800857 }
Eric Laurent10351942014-05-08 18:49:52 -0700858 {
859 Mutex::Autolock _l(event->mLock);
860 if (event->mWaitStatus) {
861 event->mWaitStatus = false;
862 event->mCond.signal();
863 }
864 }
865 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
866 }
867
868 if (configChanged) {
869 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800870 }
Eric Laurent81784c32012-11-19 14:55:58 -0800871}
872
Marco Nelissenb2208842014-02-07 14:00:50 -0800873String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
874 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700875 const audio_channel_representation_t representation =
876 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700877
878 switch (representation) {
879 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
880 if (output) {
881 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
882 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
883 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
884 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
885 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
886 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
887 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
888 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
889 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
890 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
891 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
892 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
893 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
894 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
895 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
896 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
897 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
898 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
899 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
900 } else {
901 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
902 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
903 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
904 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
905 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
906 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
907 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
908 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
909 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
910 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
911 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
912 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
913 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
914 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
915 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
916 }
917 const int len = s.length();
918 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -0700919 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -0700920 s.unlockBuffer(len - 2); // remove trailing ", "
921 }
922 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800923 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700924 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
925 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
926 return s;
927 default:
928 s.appendFormat("unknown mask, representation:%d bits:%#x",
929 representation, audio_channel_mask_get_bits(mask));
930 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800931 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800932}
933
Glenn Kasten0f11b512014-01-31 16:18:54 -0800934void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800935{
936 const size_t SIZE = 256;
937 char buffer[SIZE];
938 String8 result;
939
940 bool locked = AudioFlinger::dumpTryLock(mLock);
941 if (!locked) {
Glenn Kasten97b7b752014-09-28 13:04:24 -0700942 dprintf(fd, "thread %p may be deadlocked\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -0800943 }
944
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800945 dprintf(fd, " Thread name: %s\n", mThreadName);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700946 dprintf(fd, " I/O handle: %d\n", mId);
947 dprintf(fd, " TID: %d\n", getTid());
948 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700949 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700950 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700951 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat));
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700952 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700953 dprintf(fd, " Channel count: %u\n", mChannelCount);
954 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800955 channelMaskToString(mChannelMask, mType != RECORD).string());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700956 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat));
957 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700958 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800959 size_t numConfig = mConfigEvents.size();
960 if (numConfig) {
961 for (size_t i = 0; i < numConfig; i++) {
962 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700963 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800964 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700965 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800966 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700967 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800968 }
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800969 dprintf(fd, " Output device: %#x (%s)\n", mOutDevice, devicesToString(mOutDevice).string());
970 dprintf(fd, " Input device: %#x (%s)\n", mInDevice, devicesToString(mInDevice).string());
971 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, sourceToString(mAudioSource));
Eric Laurent81784c32012-11-19 14:55:58 -0800972
973 if (locked) {
974 mLock.unlock();
975 }
976}
977
978void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
979{
980 const size_t SIZE = 256;
981 char buffer[SIZE];
982 String8 result;
983
Marco Nelissenb2208842014-02-07 14:00:50 -0800984 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000985 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800986 write(fd, buffer, strlen(buffer));
987
Marco Nelissenb2208842014-02-07 14:00:50 -0800988 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800989 sp<EffectChain> chain = mEffectChains[i];
990 if (chain != 0) {
991 chain->dump(fd, args);
992 }
993 }
994}
995
Marco Nelissene14a5d62013-10-03 08:51:24 -0700996void AudioFlinger::ThreadBase::acquireWakeLock(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800997{
998 Mutex::Autolock _l(mLock);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700999 acquireWakeLock_l(uid);
Eric Laurent81784c32012-11-19 14:55:58 -08001000}
1001
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001002String16 AudioFlinger::ThreadBase::getWakeLockTag()
1003{
1004 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -08001005 case MIXER:
1006 return String16("AudioMix");
1007 case DIRECT:
1008 return String16("AudioDirectOut");
1009 case DUPLICATING:
1010 return String16("AudioDup");
1011 case RECORD:
1012 return String16("AudioIn");
1013 case OFFLOAD:
1014 return String16("AudioOffload");
1015 default:
1016 ALOG_ASSERT(false);
1017 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001018 }
1019}
1020
Marco Nelissene14a5d62013-10-03 08:51:24 -07001021void AudioFlinger::ThreadBase::acquireWakeLock_l(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -08001022{
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001023 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001024 if (mPowerManager != 0) {
1025 sp<IBinder> binder = new BBinder();
Marco Nelissene14a5d62013-10-03 08:51:24 -07001026 status_t status;
1027 if (uid >= 0) {
Eric Laurent547789d2013-10-04 11:46:55 -07001028 status = mPowerManager->acquireWakeLockWithUid(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -07001029 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001030 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -07001031 String16("audioserver"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -07001032 uid,
1033 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -07001034 } else {
Eric Laurent547789d2013-10-04 11:46:55 -07001035 status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -07001036 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001037 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -07001038 String16("audioserver"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -07001039 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -07001040 }
Eric Laurent81784c32012-11-19 14:55:58 -08001041 if (status == NO_ERROR) {
1042 mWakeLockToken = binder;
1043 }
Glenn Kastend7dca052015-03-05 16:05:54 -08001044 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -08001045 }
Wei Jia3f273d12015-11-24 09:06:49 -08001046
1047 if (!mNotifiedBatteryStart) {
1048 BatteryNotifier::getInstance().noteStartAudio();
1049 mNotifiedBatteryStart = true;
1050 }
Andy Hung3f0c9022016-01-15 17:49:46 -08001051 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -08001052 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
1053 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -08001054}
1055
1056void AudioFlinger::ThreadBase::releaseWakeLock()
1057{
1058 Mutex::Autolock _l(mLock);
1059 releaseWakeLock_l();
1060}
1061
1062void AudioFlinger::ThreadBase::releaseWakeLock_l()
1063{
Andy Hung3f0c9022016-01-15 17:49:46 -08001064 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -08001065 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001066 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001067 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -07001068 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
1069 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -08001070 }
1071 mWakeLockToken.clear();
1072 }
Wei Jia3f273d12015-11-24 09:06:49 -08001073
1074 if (mNotifiedBatteryStart) {
1075 BatteryNotifier::getInstance().noteStopAudio();
1076 mNotifiedBatteryStart = false;
1077 }
Eric Laurent81784c32012-11-19 14:55:58 -08001078}
1079
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001080void AudioFlinger::ThreadBase::updateWakeLockUids(const SortedVector<int> &uids) {
1081 Mutex::Autolock _l(mLock);
1082 updateWakeLockUids_l(uids);
1083}
1084
1085void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -07001086 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001087 // use checkService() to avoid blocking if power service is not up yet
1088 sp<IBinder> binder =
1089 defaultServiceManager()->checkService(String16("power"));
1090 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001091 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001092 } else {
1093 mPowerManager = interface_cast<IPowerManager>(binder);
1094 binder->linkToDeath(mDeathRecipient);
1095 }
1096 }
1097}
1098
1099void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<int> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001100 getPowerManager_l();
Andy Hung438e7572015-12-14 15:51:17 -08001101 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
1102 if (mSystemReady) {
1103 ALOGE("no wake lock to update, but system ready!");
1104 } else {
1105 ALOGW("no wake lock to update, system not ready yet");
1106 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001107 return;
1108 }
1109 if (mPowerManager != 0) {
1110 sp<IBinder> binder = new BBinder();
1111 status_t status;
Glenn Kasten3abc2de2014-09-05 16:45:52 -07001112 status = mPowerManager->updateWakeLockUids(mWakeLockToken, uids.size(), uids.array(),
1113 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent4d231dc2016-03-11 18:38:23 -08001114 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001115 }
1116}
1117
Eric Laurent81784c32012-11-19 14:55:58 -08001118void AudioFlinger::ThreadBase::clearPowerManager()
1119{
1120 Mutex::Autolock _l(mLock);
1121 releaseWakeLock_l();
1122 mPowerManager.clear();
1123}
1124
Glenn Kasten0f11b512014-01-31 16:18:54 -08001125void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001126{
1127 sp<ThreadBase> thread = mThread.promote();
1128 if (thread != 0) {
1129 thread->clearPowerManager();
1130 }
1131 ALOGW("power manager service died !!!");
1132}
1133
1134void AudioFlinger::ThreadBase::setEffectSuspended(
Glenn Kastend848eb42016-03-08 13:42:11 -08001135 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001136{
1137 Mutex::Autolock _l(mLock);
1138 setEffectSuspended_l(type, suspend, sessionId);
1139}
1140
1141void AudioFlinger::ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001142 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001143{
1144 sp<EffectChain> chain = getEffectChain_l(sessionId);
1145 if (chain != 0) {
1146 if (type != NULL) {
1147 chain->setEffectSuspended_l(type, suspend);
1148 } else {
1149 chain->setEffectSuspendedAll_l(suspend);
1150 }
1151 }
1152
1153 updateSuspendedSessions_l(type, suspend, sessionId);
1154}
1155
1156void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1157{
1158 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1159 if (index < 0) {
1160 return;
1161 }
1162
1163 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1164 mSuspendedSessions.valueAt(index);
1165
1166 for (size_t i = 0; i < sessionEffects.size(); i++) {
1167 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1168 for (int j = 0; j < desc->mRefCount; j++) {
1169 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1170 chain->setEffectSuspendedAll_l(true);
1171 } else {
1172 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1173 desc->mType.timeLow);
1174 chain->setEffectSuspended_l(&desc->mType, true);
1175 }
1176 }
1177 }
1178}
1179
1180void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1181 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001182 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001183{
1184 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1185
1186 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1187
1188 if (suspend) {
1189 if (index >= 0) {
1190 sessionEffects = mSuspendedSessions.valueAt(index);
1191 } else {
1192 mSuspendedSessions.add(sessionId, sessionEffects);
1193 }
1194 } else {
1195 if (index < 0) {
1196 return;
1197 }
1198 sessionEffects = mSuspendedSessions.valueAt(index);
1199 }
1200
1201
1202 int key = EffectChain::kKeyForSuspendAll;
1203 if (type != NULL) {
1204 key = type->timeLow;
1205 }
1206 index = sessionEffects.indexOfKey(key);
1207
1208 sp<SuspendedSessionDesc> desc;
1209 if (suspend) {
1210 if (index >= 0) {
1211 desc = sessionEffects.valueAt(index);
1212 } else {
1213 desc = new SuspendedSessionDesc();
1214 if (type != NULL) {
1215 desc->mType = *type;
1216 }
1217 sessionEffects.add(key, desc);
1218 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1219 }
1220 desc->mRefCount++;
1221 } else {
1222 if (index < 0) {
1223 return;
1224 }
1225 desc = sessionEffects.valueAt(index);
1226 if (--desc->mRefCount == 0) {
1227 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1228 sessionEffects.removeItemsAt(index);
1229 if (sessionEffects.isEmpty()) {
1230 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1231 sessionId);
1232 mSuspendedSessions.removeItem(sessionId);
1233 }
1234 }
1235 }
1236 if (!sessionEffects.isEmpty()) {
1237 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1238 }
1239}
1240
1241void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1242 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001243 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001244{
1245 Mutex::Autolock _l(mLock);
1246 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1247}
1248
1249void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1250 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001251 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001252{
1253 if (mType != RECORD) {
1254 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1255 // another session. This gives the priority to well behaved effect control panels
1256 // and applications not using global effects.
1257 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1258 // global effects
1259 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1260 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1261 }
1262 }
1263
1264 sp<EffectChain> chain = getEffectChain_l(sessionId);
1265 if (chain != 0) {
1266 chain->checkSuspendOnEffectEnabled(effect, enabled);
1267 }
1268}
1269
1270// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1271sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1272 const sp<AudioFlinger::Client>& client,
1273 const sp<IEffectClient>& effectClient,
1274 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001275 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001276 effect_descriptor_t *desc,
1277 int *enabled,
Glenn Kasten9156ef32013-08-06 15:39:08 -07001278 status_t *status)
Eric Laurent81784c32012-11-19 14:55:58 -08001279{
1280 sp<EffectModule> effect;
1281 sp<EffectHandle> handle;
1282 status_t lStatus;
1283 sp<EffectChain> chain;
1284 bool chainCreated = false;
1285 bool effectCreated = false;
1286 bool effectRegistered = false;
1287
1288 lStatus = initCheck();
1289 if (lStatus != NO_ERROR) {
1290 ALOGW("createEffect_l() Audio driver not initialized.");
1291 goto Exit;
1292 }
1293
Andy Hung98ef9782014-03-04 14:46:50 -08001294 // Reject any effect on Direct output threads for now, since the format of
1295 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1296 if (mType == DIRECT) {
1297 ALOGW("createEffect_l() Cannot add effect %s on Direct output type thread %s",
Glenn Kastend7dca052015-03-05 16:05:54 -08001298 desc->name, mThreadName);
Andy Hung98ef9782014-03-04 14:46:50 -08001299 lStatus = BAD_VALUE;
1300 goto Exit;
1301 }
1302
Andy Hung389cfdb2014-08-07 17:49:53 -07001303 // Reject any effect on mixer or duplicating multichannel sinks.
Andy Hung9a592762014-07-21 21:56:01 -07001304 // TODO: fix both format and multichannel issues with effects.
Andy Hung389cfdb2014-08-07 17:49:53 -07001305 if ((mType == MIXER || mType == DUPLICATING) && mChannelCount != FCC_2) {
1306 ALOGW("createEffect_l() Cannot add effect %s for multichannel(%d) %s threads",
1307 desc->name, mChannelCount, mType == MIXER ? "MIXER" : "DUPLICATING");
Andy Hung9a592762014-07-21 21:56:01 -07001308 lStatus = BAD_VALUE;
1309 goto Exit;
1310 }
1311
Eric Laurent5baf2af2013-09-12 17:37:00 -07001312 // Allow global effects only on offloaded and mixer threads
1313 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1314 switch (mType) {
1315 case MIXER:
1316 case OFFLOAD:
1317 break;
1318 case DIRECT:
1319 case DUPLICATING:
1320 case RECORD:
1321 default:
Glenn Kastend7dca052015-03-05 16:05:54 -08001322 ALOGW("createEffect_l() Cannot add global effect %s on thread %s",
1323 desc->name, mThreadName);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001324 lStatus = BAD_VALUE;
1325 goto Exit;
1326 }
Eric Laurent81784c32012-11-19 14:55:58 -08001327 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001328
Eric Laurent81784c32012-11-19 14:55:58 -08001329 // Only Pre processor effects are allowed on input threads and only on input threads
1330 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
1331 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
1332 desc->name, desc->flags, mType);
1333 lStatus = BAD_VALUE;
1334 goto Exit;
1335 }
1336
1337 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1338
1339 { // scope for mLock
1340 Mutex::Autolock _l(mLock);
1341
1342 // check for existing effect chain with the requested audio session
1343 chain = getEffectChain_l(sessionId);
1344 if (chain == 0) {
1345 // create a new chain for this session
1346 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1347 chain = new EffectChain(this, sessionId);
1348 addEffectChain_l(chain);
1349 chain->setStrategy(getStrategyForSession_l(sessionId));
1350 chainCreated = true;
1351 } else {
1352 effect = chain->getEffectFromDesc_l(desc);
1353 }
1354
1355 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1356
1357 if (effect == 0) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08001358 audio_unique_id_t id = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001359 // Check CPU and memory usage
1360 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
1361 if (lStatus != NO_ERROR) {
1362 goto Exit;
1363 }
1364 effectRegistered = true;
1365 // create a new effect module if none present in the chain
1366 effect = new EffectModule(this, chain, desc, id, sessionId);
1367 lStatus = effect->status();
1368 if (lStatus != NO_ERROR) {
1369 goto Exit;
1370 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001371 effect->setOffloaded(mType == OFFLOAD, mId);
1372
Eric Laurent81784c32012-11-19 14:55:58 -08001373 lStatus = chain->addEffect_l(effect);
1374 if (lStatus != NO_ERROR) {
1375 goto Exit;
1376 }
1377 effectCreated = true;
1378
1379 effect->setDevice(mOutDevice);
1380 effect->setDevice(mInDevice);
1381 effect->setMode(mAudioFlinger->getMode());
1382 effect->setAudioSource(mAudioSource);
1383 }
1384 // create effect handle and connect it to effect module
1385 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001386 lStatus = handle->initCheck();
1387 if (lStatus == OK) {
1388 lStatus = effect->addHandle(handle.get());
1389 }
Eric Laurent81784c32012-11-19 14:55:58 -08001390 if (enabled != NULL) {
1391 *enabled = (int)effect->isEnabled();
1392 }
1393 }
1394
1395Exit:
1396 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1397 Mutex::Autolock _l(mLock);
1398 if (effectCreated) {
1399 chain->removeEffect_l(effect);
1400 }
1401 if (effectRegistered) {
1402 AudioSystem::unregisterEffect(effect->id());
1403 }
1404 if (chainCreated) {
1405 removeEffectChain_l(chain);
1406 }
1407 handle.clear();
1408 }
1409
Glenn Kasten9156ef32013-08-06 15:39:08 -07001410 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001411 return handle;
1412}
1413
Glenn Kastend848eb42016-03-08 13:42:11 -08001414sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1415 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001416{
1417 Mutex::Autolock _l(mLock);
1418 return getEffect_l(sessionId, effectId);
1419}
1420
Glenn Kastend848eb42016-03-08 13:42:11 -08001421sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1422 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001423{
1424 sp<EffectChain> chain = getEffectChain_l(sessionId);
1425 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1426}
1427
1428// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1429// PlaybackThread::mLock held
1430status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1431{
1432 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001433 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001434 sp<EffectChain> chain = getEffectChain_l(sessionId);
1435 bool chainCreated = false;
1436
Eric Laurent5baf2af2013-09-12 17:37:00 -07001437 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1438 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1439 this, effect->desc().name, effect->desc().flags);
1440
Eric Laurent81784c32012-11-19 14:55:58 -08001441 if (chain == 0) {
1442 // create a new chain for this session
1443 ALOGV("addEffect_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 }
1449 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1450
1451 if (chain->getEffectFromId_l(effect->id()) != 0) {
1452 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1453 this, effect->desc().name, chain.get());
1454 return BAD_VALUE;
1455 }
1456
Eric Laurent5baf2af2013-09-12 17:37:00 -07001457 effect->setOffloaded(mType == OFFLOAD, mId);
1458
Eric Laurent81784c32012-11-19 14:55:58 -08001459 status_t status = chain->addEffect_l(effect);
1460 if (status != NO_ERROR) {
1461 if (chainCreated) {
1462 removeEffectChain_l(chain);
1463 }
1464 return status;
1465 }
1466
1467 effect->setDevice(mOutDevice);
1468 effect->setDevice(mInDevice);
1469 effect->setMode(mAudioFlinger->getMode());
1470 effect->setAudioSource(mAudioSource);
1471 return NO_ERROR;
1472}
1473
1474void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
1475
1476 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
1477 effect_descriptor_t desc = effect->desc();
1478 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1479 detachAuxEffect_l(effect->id());
1480 }
1481
1482 sp<EffectChain> chain = effect->chain().promote();
1483 if (chain != 0) {
1484 // remove effect chain if removing last effect
1485 if (chain->removeEffect_l(effect) == 0) {
1486 removeEffectChain_l(chain);
1487 }
1488 } else {
1489 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1490 }
1491}
1492
1493void AudioFlinger::ThreadBase::lockEffectChains_l(
1494 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1495{
1496 effectChains = mEffectChains;
1497 for (size_t i = 0; i < mEffectChains.size(); i++) {
1498 mEffectChains[i]->lock();
1499 }
1500}
1501
1502void AudioFlinger::ThreadBase::unlockEffectChains(
1503 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1504{
1505 for (size_t i = 0; i < effectChains.size(); i++) {
1506 effectChains[i]->unlock();
1507 }
1508}
1509
Glenn Kastend848eb42016-03-08 13:42:11 -08001510sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001511{
1512 Mutex::Autolock _l(mLock);
1513 return getEffectChain_l(sessionId);
1514}
1515
Glenn Kastend848eb42016-03-08 13:42:11 -08001516sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1517 const
Eric Laurent81784c32012-11-19 14:55:58 -08001518{
1519 size_t size = mEffectChains.size();
1520 for (size_t i = 0; i < size; i++) {
1521 if (mEffectChains[i]->sessionId() == sessionId) {
1522 return mEffectChains[i];
1523 }
1524 }
1525 return 0;
1526}
1527
1528void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1529{
1530 Mutex::Autolock _l(mLock);
1531 size_t size = mEffectChains.size();
1532 for (size_t i = 0; i < size; i++) {
1533 mEffectChains[i]->setMode_l(mode);
1534 }
1535}
1536
Eric Laurent83b88082014-06-20 18:31:16 -07001537void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1538{
1539 config->type = AUDIO_PORT_TYPE_MIX;
1540 config->ext.mix.handle = mId;
1541 config->sample_rate = mSampleRate;
1542 config->format = mFormat;
1543 config->channel_mask = mChannelMask;
1544 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1545 AUDIO_PORT_CONFIG_FORMAT;
1546}
1547
Eric Laurent72e3f392015-05-20 14:43:50 -07001548void AudioFlinger::ThreadBase::systemReady()
1549{
1550 Mutex::Autolock _l(mLock);
1551 if (mSystemReady) {
1552 return;
1553 }
1554 mSystemReady = true;
1555
1556 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1557 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1558 }
1559 mPendingConfigEvents.clear();
1560}
1561
Eric Laurent83b88082014-06-20 18:31:16 -07001562
Eric Laurent81784c32012-11-19 14:55:58 -08001563// ----------------------------------------------------------------------------
1564// Playback
1565// ----------------------------------------------------------------------------
1566
1567AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1568 AudioStreamOut* output,
1569 audio_io_handle_t id,
1570 audio_devices_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07001571 type_t type,
Eric Laurent51716182016-02-29 18:00:56 -08001572 bool systemReady,
1573 uint32_t bitRate)
Eric Laurent72e3f392015-05-20 14:43:50 -07001574 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001575 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001576 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001577 mMixerBuffer(NULL),
1578 mMixerBufferSize(0),
1579 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1580 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001581 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001582 mEffectBuffer(NULL),
1583 mEffectBufferSize(0),
1584 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1585 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001586 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001587 mFramesWritten(0),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001588 mActiveTracksGeneration(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001589 // mStreamTypes[] initialized in constructor body
1590 mOutput(output),
1591 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
1592 mMixerStatus(MIXER_IDLE),
1593 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001594 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001595 mBytesRemaining(0),
1596 mCurrentWriteLength(0),
1597 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001598 mWriteAckSequence(0),
1599 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001600 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001601 mScreenState(AudioFlinger::mScreenState),
1602 // index 0 is reserved for normal mixer's submix
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001603 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1),
Andy Hunge10393e2015-06-12 13:59:33 -07001604 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001605{
Glenn Kastend7dca052015-03-05 16:05:54 -08001606 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1607 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001608
1609 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1610 // it would be safer to explicitly pass initial masterVolume/masterMute as
1611 // parameter.
1612 //
1613 // If the HAL we are using has support for master volume or master mute,
1614 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1615 // and the mute set to false).
1616 mMasterVolume = audioFlinger->masterVolume_l();
1617 mMasterMute = audioFlinger->masterMute_l();
1618 if (mOutput && mOutput->audioHwDev) {
1619 if (mOutput->audioHwDev->canSetMasterVolume()) {
1620 mMasterVolume = 1.0;
1621 }
1622
1623 if (mOutput->audioHwDev->canSetMasterMute()) {
1624 mMasterMute = false;
1625 }
1626 }
1627
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001628 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001629
Eric Laurent223fd5c2014-11-11 13:43:36 -08001630 // ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001631 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001632 stream = (audio_stream_type_t) (stream + 1)) {
1633 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1634 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1635 }
Eric Laurent51716182016-02-29 18:00:56 -08001636
1637 if (audio_has_proportional_frames(mFormat)) {
1638 mBufferDurationUs = (uint32_t)((mNormalFrameCount * 1000000LL) / mSampleRate);
1639 } else {
1640 bitRate = bitRate != 0 ? bitRate : kOffloadDefaultBitRateBps;
1641 mBufferDurationUs = (uint32_t)((mBufferSize * 8 * 1000000LL) / bitRate);
1642 }
Eric Laurent81784c32012-11-19 14:55:58 -08001643}
1644
1645AudioFlinger::PlaybackThread::~PlaybackThread()
1646{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001647 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001648 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001649 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001650 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001651}
1652
1653void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1654{
1655 dumpInternals(fd, args);
1656 dumpTracks(fd, args);
1657 dumpEffectChains(fd, args);
1658}
1659
Glenn Kasten0f11b512014-01-31 16:18:54 -08001660void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001661{
1662 const size_t SIZE = 256;
1663 char buffer[SIZE];
1664 String8 result;
1665
Marco Nelissenb2208842014-02-07 14:00:50 -08001666 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001667 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1668 const stream_type_t *st = &mStreamTypes[i];
1669 if (i > 0) {
1670 result.appendFormat(", ");
1671 }
1672 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1673 if (st->mute) {
1674 result.append("M");
1675 }
1676 }
1677 result.append("\n");
1678 write(fd, result.string(), result.length());
1679 result.clear();
1680
Eric Laurent81784c32012-11-19 14:55:58 -08001681 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1682 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001683 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001684 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001685
1686 size_t numtracks = mTracks.size();
1687 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001688 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001689 size_t numactiveseen = 0;
1690 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001691 dprintf(fd, " of which %zu are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001692 Track::appendDumpHeader(result);
1693 for (size_t i = 0; i < numtracks; ++i) {
1694 sp<Track> track = mTracks[i];
1695 if (track != 0) {
1696 bool active = mActiveTracks.indexOf(track) >= 0;
1697 if (active) {
1698 numactiveseen++;
1699 }
1700 track->dump(buffer, SIZE, active);
1701 result.append(buffer);
1702 }
1703 }
1704 } else {
1705 result.append("\n");
1706 }
1707 if (numactiveseen != numactive) {
1708 // some tracks in the active list were not in the tracks list
1709 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1710 " not in the track list\n");
1711 result.append(buffer);
1712 Track::appendDumpHeader(result);
1713 for (size_t i = 0; i < numactive; ++i) {
1714 sp<Track> track = mActiveTracks[i].promote();
1715 if (track != 0 && mTracks.indexOf(track) < 0) {
1716 track->dump(buffer, SIZE, true);
1717 result.append(buffer);
1718 }
1719 }
1720 }
1721
1722 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001723}
1724
1725void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1726{
Glenn Kasten97b7b752014-09-28 13:04:24 -07001727 dprintf(fd, "\nOutput thread %p type %d (%s):\n", this, type(), threadTypeToString(type()));
Glenn Kasten44182c22015-03-05 17:12:23 -08001728
1729 dumpBase(fd, args);
1730
Elliott Hughes87cebad2014-05-22 10:14:43 -07001731 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001732 dprintf(fd, " Last write occurred (msecs): %llu\n",
1733 (unsigned long long) ns2ms(systemTime() - mLastWriteTime));
Elliott Hughes87cebad2014-05-22 10:14:43 -07001734 dprintf(fd, " Total writes: %d\n", mNumWrites);
1735 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1736 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1737 dprintf(fd, " Suspend count: %d\n", mSuspended);
1738 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1739 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1740 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1741 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08001742 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001743 AudioStreamOut *output = mOutput;
1744 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
1745 String8 flagsAsString = outputFlagsToString(flags);
1746 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n", output, flags, flagsAsString.string());
Eric Laurent81784c32012-11-19 14:55:58 -08001747}
1748
1749// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001750
1751void AudioFlinger::PlaybackThread::onFirstRef()
1752{
Glenn Kastend7dca052015-03-05 16:05:54 -08001753 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001754}
1755
1756// ThreadBase virtuals
1757void AudioFlinger::PlaybackThread::preExit()
1758{
1759 ALOGV(" preExit()");
1760 // FIXME this is using hard-coded strings but in the future, this functionality will be
1761 // converted to use audio HAL extensions required to support tunneling
1762 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1763}
1764
1765// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1766sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1767 const sp<AudioFlinger::Client>& client,
1768 audio_stream_type_t streamType,
1769 uint32_t sampleRate,
1770 audio_format_t format,
1771 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001772 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001773 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08001774 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001775 IAudioFlinger::track_flags_t *flags,
1776 pid_t tid,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001777 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -08001778 status_t *status)
1779{
Glenn Kasten74935e42013-12-19 08:56:45 -08001780 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001781 sp<Track> track;
1782 status_t lStatus;
1783
Eric Laurent81784c32012-11-19 14:55:58 -08001784 // client expresses a preference for FAST, but we get the final say
1785 if (*flags & IAudioFlinger::TRACK_FAST) {
1786 if (
Eric Laurent81784c32012-11-19 14:55:58 -08001787 // PCM data
1788 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001789 // TODO: extract as a data library function that checks that a computationally
1790 // expensive downmixer is not required: isFastOutputChannelConversion()
Andy Hung9a592762014-07-21 21:56:01 -07001791 (channelMask == mChannelMask ||
Andy Hung1f439e12015-05-19 12:57:41 -07001792 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1793 (channelMask == AUDIO_CHANNEL_OUT_MONO
1794 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001795 // hardware sample rate
1796 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001797 // normal mixer has an associated fast mixer
1798 hasFastMixer() &&
1799 // there are sufficient fast track slots available
1800 (mFastTrackAvailMask != 0)
1801 // FIXME test that MixerThread for this fast track has a capable output HAL
1802 // FIXME add a permission test also?
1803 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07001804 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
1805 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001806 // read the fast track multiplier property the first time it is needed
1807 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1808 if (ok != 0) {
1809 ALOGE("%s pthread_once failed: %d", __func__, ok);
1810 }
Andy Hunge0a269a2016-03-23 15:13:42 -07001811 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08001812 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001813 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08001814 frameCount, mFrameCount);
1815 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001816 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
1817 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07001818 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001819 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08001820 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001821 audio_is_linear_pcm(format),
1822 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1823 *flags &= ~IAudioFlinger::TRACK_FAST;
Andy Hung0e48d252015-01-26 11:43:15 -08001824 }
1825 }
1826 // For normal PCM streaming tracks, update minimum frame count.
1827 // For compatibility with AudioTrack calculation, buffer depth is forced
1828 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1829 // This is probably too conservative, but legacy application code may depend on it.
1830 // If you change this calculation, also review the start threshold which is related.
1831 if (!(*flags & IAudioFlinger::TRACK_FAST)
Phil Burkfdb3c072016-02-09 10:47:02 -08001832 && audio_has_proportional_frames(format) && sharedBuffer == 0) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001833 // this must match AudioTrack.cpp calculateMinFrameCount().
1834 // TODO: Move to a common library
Eric Laurent81784c32012-11-19 14:55:58 -08001835 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1836 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1837 if (minBufCount < 2) {
1838 minBufCount = 2;
1839 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07001840 // For normal mixing tracks, if speed is > 1.0f (normal), AudioTrack
1841 // or the client should compute and pass in a larger buffer request.
Andy Hung0e48d252015-01-26 11:43:15 -08001842 size_t minFrameCount =
Andy Hung8edb8dc2015-03-26 19:13:55 -07001843 minBufCount * sourceFramesNeededWithTimestretch(
1844 sampleRate, mNormalFrameCount,
1845 mSampleRate, AUDIO_TIMESTRETCH_SPEED_NORMAL /*speed*/);
Andy Hung0e48d252015-01-26 11:43:15 -08001846 if (frameCount < minFrameCount) { // including frameCount == 0
Eric Laurent81784c32012-11-19 14:55:58 -08001847 frameCount = minFrameCount;
1848 }
Eric Laurent81784c32012-11-19 14:55:58 -08001849 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001850 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001851
Glenn Kastenc3df8382014-03-13 15:05:25 -07001852 switch (mType) {
1853
1854 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08001855 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08001856 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001857 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1858 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001859 sampleRate, format, channelMask, mOutput, mFormat);
1860 lStatus = BAD_VALUE;
1861 goto Exit;
1862 }
1863 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001864 break;
1865
1866 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001867 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001868 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1869 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001870 sampleRate, format, channelMask, mOutput, mFormat);
1871 lStatus = BAD_VALUE;
1872 goto Exit;
1873 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001874 break;
1875
1876 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001877 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001878 ALOGE("createTrack_l() Bad parameter: format %#x \""
1879 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001880 format, mOutput, mFormat);
1881 lStatus = BAD_VALUE;
1882 goto Exit;
1883 }
Andy Hungcd044842014-08-07 11:04:34 -07001884 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08001885 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1886 lStatus = BAD_VALUE;
1887 goto Exit;
1888 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001889 break;
1890
Eric Laurent81784c32012-11-19 14:55:58 -08001891 }
1892
1893 lStatus = initCheck();
1894 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001895 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08001896 goto Exit;
1897 }
1898
1899 { // scope for mLock
1900 Mutex::Autolock _l(mLock);
1901
1902 // all tracks in same audio session must share the same routing strategy otherwise
1903 // conflicts will happen when tracks are moved from one output to another by audio policy
1904 // manager
1905 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1906 for (size_t i = 0; i < mTracks.size(); ++i) {
1907 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07001908 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001909 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1910 if (sessionId == t->sessionId() && strategy != actual) {
1911 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1912 strategy, actual);
1913 lStatus = BAD_VALUE;
1914 goto Exit;
1915 }
1916 }
1917 }
1918
Glenn Kastend79072e2016-01-06 08:41:20 -08001919 track = new Track(this, client, streamType, sampleRate, format,
1920 channelMask, frameCount, NULL, sharedBuffer,
1921 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT);
Glenn Kasten03003332013-08-06 15:40:54 -07001922
Glenn Kasten03003332013-08-06 15:40:54 -07001923 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1924 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08001925 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001926 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08001927 goto Exit;
1928 }
1929 mTracks.add(track);
1930
1931 sp<EffectChain> chain = getEffectChain_l(sessionId);
1932 if (chain != 0) {
1933 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1934 track->setMainBuffer(chain->inBuffer());
1935 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1936 chain->incTrackCnt();
1937 }
1938
1939 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1940 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1941 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1942 // so ask activity manager to do this on our behalf
1943 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1944 }
1945 }
1946
1947 lStatus = NO_ERROR;
1948
1949Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001950 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001951 return track;
1952}
1953
1954uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1955{
1956 return latency;
1957}
1958
1959uint32_t AudioFlinger::PlaybackThread::latency() const
1960{
1961 Mutex::Autolock _l(mLock);
1962 return latency_l();
1963}
1964uint32_t AudioFlinger::PlaybackThread::latency_l() const
1965{
1966 if (initCheck() == NO_ERROR) {
1967 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1968 } else {
1969 return 0;
1970 }
1971}
1972
1973void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1974{
1975 Mutex::Autolock _l(mLock);
1976 // Don't apply master volume in SW if our HAL can do it for us.
1977 if (mOutput && mOutput->audioHwDev &&
1978 mOutput->audioHwDev->canSetMasterVolume()) {
1979 mMasterVolume = 1.0;
1980 } else {
1981 mMasterVolume = value;
1982 }
1983}
1984
1985void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1986{
1987 Mutex::Autolock _l(mLock);
1988 // Don't apply master mute in SW if our HAL can do it for us.
1989 if (mOutput && mOutput->audioHwDev &&
1990 mOutput->audioHwDev->canSetMasterMute()) {
1991 mMasterMute = false;
1992 } else {
1993 mMasterMute = muted;
1994 }
1995}
1996
1997void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1998{
1999 Mutex::Autolock _l(mLock);
2000 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002001 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002002}
2003
2004void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2005{
2006 Mutex::Autolock _l(mLock);
2007 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002008 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002009}
2010
2011float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2012{
2013 Mutex::Autolock _l(mLock);
2014 return mStreamTypes[stream].volume;
2015}
2016
2017// addTrack_l() must be called with ThreadBase::mLock held
2018status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2019{
2020 status_t status = ALREADY_EXISTS;
2021
Eric Laurent81784c32012-11-19 14:55:58 -08002022 if (mActiveTracks.indexOf(track) < 0) {
2023 // the track is newly added, make sure it fills up all its
2024 // buffers before playing. This is to ensure the client will
2025 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002026 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002027 TrackBase::track_state state = track->mState;
2028 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002029 status = AudioSystem::startOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002030 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002031 mLock.lock();
2032 // abort track was stopped/paused while we released the lock
2033 if (state != track->mState) {
2034 if (status == NO_ERROR) {
2035 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002036 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002037 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002038 mLock.lock();
2039 }
2040 return INVALID_OPERATION;
2041 }
2042 // abort if start is rejected by audio policy manager
2043 if (status != NO_ERROR) {
2044 return PERMISSION_DENIED;
2045 }
2046#ifdef ADD_BATTERY_DATA
2047 // to track the speaker usage
2048 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2049#endif
2050 }
2051
Eric Laurent51716182016-02-29 18:00:56 -08002052 // set retry count for buffer fill
2053 if (track->isOffloaded()) {
2054 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2055 } else {
2056 track->mRetryCount = kMaxTrackStartupRetries;
2057 }
2058
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002059 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08002060 track->mResetDone = false;
2061 track->mPresentationCompleteFrames = 0;
2062 mActiveTracks.add(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002063 mWakeLockUids.add(track->uid());
2064 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07002065 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07002066 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2067 if (chain != 0) {
2068 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2069 track->sessionId());
2070 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002071 }
2072
2073 status = NO_ERROR;
2074 }
2075
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002076 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002077 return status;
2078}
2079
Eric Laurentbfb1b832013-01-07 09:53:42 -08002080bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002081{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002082 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002083 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002084 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2085 track->mState = TrackBase::STOPPED;
2086 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002087 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002088 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002089 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002090 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002091
2092 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002093}
2094
2095void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2096{
2097 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
2098 mTracks.remove(track);
2099 deleteTrackName_l(track->name());
2100 // redundant as track is about to be destroyed, for dumpsys only
2101 track->mName = -1;
2102 if (track->isFastTrack()) {
2103 int index = track->mFastIndex;
2104 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
2105 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2106 mFastTrackAvailMask |= 1 << index;
2107 // redundant as track is about to be destroyed, for dumpsys only
2108 track->mFastIndex = -1;
2109 }
2110 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2111 if (chain != 0) {
2112 chain->decTrackCnt();
2113 }
2114}
2115
Eric Laurentede6c3b2013-09-19 14:37:46 -07002116void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002117{
2118 // Thread could be blocked waiting for async
2119 // so signal it to handle state changes immediately
2120 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
2121 // be lost so we also flag to prevent it blocking on mWaitWorkCV
2122 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002123 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002124}
2125
Eric Laurent81784c32012-11-19 14:55:58 -08002126String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2127{
Eric Laurent81784c32012-11-19 14:55:58 -08002128 Mutex::Autolock _l(mLock);
2129 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07002130 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002131 }
2132
Glenn Kastend8ea6992013-07-16 14:17:15 -07002133 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
2134 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08002135 free(s);
2136 return out_s8;
2137}
2138
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002139void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002140 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2141 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002142
Eric Laurent73e26b62015-04-27 16:55:58 -07002143 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002144
2145 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002146 case AUDIO_OUTPUT_OPENED:
2147 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002148 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002149 desc->mChannelMask = mChannelMask;
2150 desc->mSamplingRate = mSampleRate;
2151 desc->mFormat = mFormat;
2152 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002153 // AudioFlinger::frameCount(audio_io_handle_t)
Eric Laurent73e26b62015-04-27 16:55:58 -07002154 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002155 break;
2156
Eric Laurent73e26b62015-04-27 16:55:58 -07002157 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002158 default:
2159 break;
2160 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002161 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002162}
2163
Eric Laurentbfb1b832013-01-07 09:53:42 -08002164void AudioFlinger::PlaybackThread::writeCallback()
2165{
2166 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002167 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002168}
2169
2170void AudioFlinger::PlaybackThread::drainCallback()
2171{
2172 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002173 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002174}
2175
Eric Laurent3b4529e2013-09-05 18:09:19 -07002176void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002177{
2178 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002179 // reject out of sequence requests
2180 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2181 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002182 mWaitWorkCV.signal();
2183 }
2184}
2185
Eric Laurent3b4529e2013-09-05 18:09:19 -07002186void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002187{
2188 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002189 // reject out of sequence requests
2190 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
2191 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002192 mWaitWorkCV.signal();
2193 }
2194}
2195
2196// static
2197int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
Glenn Kasten0f11b512014-01-31 16:18:54 -08002198 void *param __unused,
Eric Laurentbfb1b832013-01-07 09:53:42 -08002199 void *cookie)
2200{
2201 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
2202 ALOGV("asyncCallback() event %d", event);
2203 switch (event) {
2204 case STREAM_CBK_EVENT_WRITE_READY:
2205 me->writeCallback();
2206 break;
2207 case STREAM_CBK_EVENT_DRAIN_READY:
2208 me->drainCallback();
2209 break;
2210 default:
2211 ALOGW("asyncCallback() unknown event %d", event);
2212 break;
2213 }
2214 return 0;
2215}
2216
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002217void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002218{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002219 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002220 mSampleRate = mOutput->getSampleRate();
2221 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002222 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002223 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002224 }
Andy Hung9a592762014-07-21 21:56:01 -07002225 if ((mType == MIXER || mType == DUPLICATING)
2226 && !isValidPcmSinkChannelMask(mChannelMask)) {
2227 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2228 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002229 }
Andy Hunge5412692014-05-16 11:25:07 -07002230 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002231
2232 // Get actual HAL format.
Andy Hung463be252014-07-10 16:56:07 -07002233 mHALFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Phil Burkca5e6142015-07-14 09:42:29 -07002234 // Get format from the shim, which will be different than the HAL format
2235 // if playing compressed audio over HDMI passthrough.
2236 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002237 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002238 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002239 }
Andy Hung6146c082014-03-18 11:56:15 -07002240 if ((mType == MIXER || mType == DUPLICATING)
2241 && !isValidPcmSinkFormat(mFormat)) {
2242 LOG_FATAL("HAL format %#x not supported for mixed output",
2243 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002244 }
Phil Burk062e67a2015-02-11 13:40:50 -08002245 mFrameSize = mOutput->getFrameSize();
Glenn Kasten70949c42013-08-06 07:40:12 -07002246 mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
2247 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002248 if (mFrameCount & 15) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002249 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002250 mFrameCount);
2251 }
2252
Eric Laurentbfb1b832013-01-07 09:53:42 -08002253 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
2254 (mOutput->stream->set_callback != NULL)) {
2255 if (mOutput->stream->set_callback(mOutput->stream,
2256 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
2257 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002258 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002259 }
2260 }
2261
Eric Laurentd1f69b02014-12-15 14:33:13 -08002262 mHwSupportsPause = false;
2263 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
2264 if (mOutput->stream->pause != NULL) {
2265 if (mOutput->stream->resume != NULL) {
2266 mHwSupportsPause = true;
2267 } else {
2268 ALOGW("direct output implements pause but not resume");
2269 }
2270 } else if (mOutput->stream->resume != NULL) {
2271 ALOGW("direct output implements resume but not pause");
2272 }
2273 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002274 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2275 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2276 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002277
Andy Hungfbfc3952015-01-15 13:33:51 -08002278 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2279 // For best precision, we use float instead of the associated output
2280 // device format (typically PCM 16 bit).
2281
2282 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2283 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2284 mBufferSize = mFrameSize * mFrameCount;
2285
2286 // TODO: We currently use the associated output device channel mask and sample rate.
2287 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2288 // (if a valid mask) to avoid premature downmix.
2289 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2290 // instead of the output device sample rate to avoid loss of high frequency information.
2291 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2292 }
2293
Andy Hung09a50072014-02-27 14:30:47 -08002294 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002295 double multiplier = 1.0;
2296 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2297 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002298 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2299 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Eric Laurent81784c32012-11-19 14:55:58 -08002300 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2301 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2302 maxNormalFrameCount = maxNormalFrameCount & ~15;
2303 if (maxNormalFrameCount < minNormalFrameCount) {
2304 maxNormalFrameCount = minNormalFrameCount;
2305 }
2306 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2307 if (multiplier <= 1.0) {
2308 multiplier = 1.0;
2309 } else if (multiplier <= 2.0) {
2310 if (2 * mFrameCount <= maxNormalFrameCount) {
2311 multiplier = 2.0;
2312 } else {
2313 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2314 }
2315 } else {
2316 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
Andy Hung09a50072014-02-27 14:30:47 -08002317 // SRC (it would be unusual for the normal sink buffer size to not be a multiple of fast
Eric Laurent81784c32012-11-19 14:55:58 -08002318 // track, but we sometimes have to do this to satisfy the maximum frame count
2319 // constraint)
2320 // FIXME this rounding up should not be done if no HAL SRC
2321 uint32_t truncMult = (uint32_t) multiplier;
2322 if ((truncMult & 1)) {
2323 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2324 ++truncMult;
2325 }
2326 }
2327 multiplier = (double) truncMult;
2328 }
2329 }
2330 mNormalFrameCount = multiplier * mFrameCount;
2331 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002332 if (mType == MIXER || mType == DUPLICATING) {
2333 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2334 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002335 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002336 mNormalFrameCount);
2337
Andy Hung08fb1742015-05-31 23:22:10 -07002338 // Check if we want to throttle the processing to no more than 2x normal rate
2339 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002340 mThreadThrottleTimeMs = 0;
2341 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002342 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2343
Andy Hung010a1a12014-03-13 13:57:33 -07002344 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2345 // Originally this was int16_t[] array, need to remove legacy implications.
2346 free(mSinkBuffer);
2347 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002348 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2349 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2350 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002351 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002352
Andy Hung69aed5f2014-02-25 17:24:40 -08002353 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2354 // drives the output.
2355 free(mMixerBuffer);
2356 mMixerBuffer = NULL;
2357 if (mMixerBufferEnabled) {
2358 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2359 mMixerBufferSize = mNormalFrameCount * mChannelCount
2360 * audio_bytes_per_sample(mMixerBufferFormat);
2361 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2362 }
Andy Hung98ef9782014-03-04 14:46:50 -08002363 free(mEffectBuffer);
2364 mEffectBuffer = NULL;
2365 if (mEffectBufferEnabled) {
2366 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2367 mEffectBufferSize = mNormalFrameCount * mChannelCount
2368 * audio_bytes_per_sample(mEffectBufferFormat);
2369 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2370 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002371
Eric Laurent81784c32012-11-19 14:55:58 -08002372 // force reconfiguration of effect chains and engines to take new buffer size and audio
2373 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002374 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002375 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2376 // matter.
2377 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2378 Vector< sp<EffectChain> > effectChains = mEffectChains;
2379 for (size_t i = 0; i < effectChains.size(); i ++) {
2380 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2381 }
2382}
2383
2384
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002385status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002386{
2387 if (halFrames == NULL || dspFrames == NULL) {
2388 return BAD_VALUE;
2389 }
2390 Mutex::Autolock _l(mLock);
2391 if (initCheck() != NO_ERROR) {
2392 return INVALID_OPERATION;
2393 }
Andy Hung818e7a32016-02-16 18:08:07 -08002394 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002395 *halFrames = framesWritten;
2396
2397 if (isSuspended()) {
2398 // return an estimation of rendered frames when the output is suspended
2399 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002400 *dspFrames = (uint32_t)
2401 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002402 return NO_ERROR;
2403 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002404 status_t status;
2405 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002406 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002407 *dspFrames = (size_t)frames;
2408 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002409 }
2410}
2411
Glenn Kastend848eb42016-03-08 13:42:11 -08002412uint32_t AudioFlinger::PlaybackThread::hasAudioSession(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08002413{
2414 Mutex::Autolock _l(mLock);
2415 uint32_t result = 0;
2416 if (getEffectChain_l(sessionId) != 0) {
2417 result = EFFECT_SESSION;
2418 }
2419
2420 for (size_t i = 0; i < mTracks.size(); ++i) {
2421 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002422 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002423 result |= TRACK_SESSION;
2424 break;
2425 }
2426 }
2427
2428 return result;
2429}
2430
Glenn Kastend848eb42016-03-08 13:42:11 -08002431uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08002432{
2433 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2434 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2435 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2436 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2437 }
2438 for (size_t i = 0; i < mTracks.size(); i++) {
2439 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002440 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002441 return AudioSystem::getStrategyForStream(track->streamType());
2442 }
2443 }
2444 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2445}
2446
2447
Phil Burk062e67a2015-02-11 13:40:50 -08002448AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002449{
2450 Mutex::Autolock _l(mLock);
2451 return mOutput;
2452}
2453
Phil Burk062e67a2015-02-11 13:40:50 -08002454AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002455{
2456 Mutex::Autolock _l(mLock);
2457 AudioStreamOut *output = mOutput;
2458 mOutput = NULL;
2459 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2460 // must push a NULL and wait for ack
2461 mOutputSink.clear();
2462 mPipeSink.clear();
2463 mNormalSink.clear();
2464 return output;
2465}
2466
2467// this method must always be called either with ThreadBase mLock held or inside the thread loop
2468audio_stream_t* AudioFlinger::PlaybackThread::stream() const
2469{
2470 if (mOutput == NULL) {
2471 return NULL;
2472 }
2473 return &mOutput->stream->common;
2474}
2475
2476uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2477{
2478 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2479}
2480
2481status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2482{
2483 if (!isValidSyncEvent(event)) {
2484 return BAD_VALUE;
2485 }
2486
2487 Mutex::Autolock _l(mLock);
2488
2489 for (size_t i = 0; i < mTracks.size(); ++i) {
2490 sp<Track> track = mTracks[i];
2491 if (event->triggerSession() == track->sessionId()) {
2492 (void) track->setSyncEvent(event);
2493 return NO_ERROR;
2494 }
2495 }
2496
2497 return NAME_NOT_FOUND;
2498}
2499
2500bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2501{
2502 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2503}
2504
2505void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2506 const Vector< sp<Track> >& tracksToRemove)
2507{
2508 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002509 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002510 for (size_t i = 0 ; i < count ; i++) {
2511 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002512 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002513 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002514 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002515#ifdef ADD_BATTERY_DATA
2516 // to track the speaker usage
2517 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2518#endif
2519 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002520 AudioSystem::releaseOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002521 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002522 }
Eric Laurent81784c32012-11-19 14:55:58 -08002523 }
2524 }
2525 }
Eric Laurent81784c32012-11-19 14:55:58 -08002526}
2527
2528void AudioFlinger::PlaybackThread::checkSilentMode_l()
2529{
2530 if (!mMasterMute) {
2531 char value[PROPERTY_VALUE_MAX];
2532 if (property_get("ro.audio.silent", value, "0") > 0) {
2533 char *endptr;
2534 unsigned long ul = strtoul(value, &endptr, 0);
2535 if (*endptr == '\0' && ul != 0) {
2536 ALOGD("Silence is golden");
2537 // The setprop command will not allow a property to be changed after
2538 // the first time it is set, so we don't have to worry about un-muting.
2539 setMasterMute_l(true);
2540 }
2541 }
2542 }
2543}
2544
2545// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002546ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002547{
2548 // FIXME rewrite to reduce number of system calls
2549 mLastWriteTime = systemTime();
2550 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002551 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002552 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002553
2554 // If an NBAIO sink is present, use it to write the normal mixer's submix
2555 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002556
Andy Hung010a1a12014-03-13 13:57:33 -07002557 const size_t count = mBytesRemaining / mFrameSize;
2558
Simon Wilson2d590962012-11-29 15:18:50 -08002559 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002560 // update the setpoint when AudioFlinger::mScreenState changes
2561 uint32_t screenState = AudioFlinger::mScreenState;
2562 if (screenState != mScreenState) {
2563 mScreenState = screenState;
2564 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2565 if (pipe != NULL) {
2566 pipe->setAvgFrames((mScreenState & 1) ?
2567 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2568 }
2569 }
Andy Hung010a1a12014-03-13 13:57:33 -07002570 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002571 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002572 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002573 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002574 } else {
2575 bytesWritten = framesWritten;
2576 }
2577 // otherwise use the HAL / AudioStreamOut directly
2578 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002579 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002580
Eric Laurentbfb1b832013-01-07 09:53:42 -08002581 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002582 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2583 mWriteAckSequence += 2;
2584 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002585 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002586 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002587 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002588 // FIXME We should have an implementation of timestamps for direct output threads.
2589 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002590 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurent51716182016-02-29 18:00:56 -08002591
Eric Laurentbfb1b832013-01-07 09:53:42 -08002592 if (mUseAsyncWrite &&
2593 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2594 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002595 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002596 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002597 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002598 }
Eric Laurent81784c32012-11-19 14:55:58 -08002599 }
2600
Eric Laurent81784c32012-11-19 14:55:58 -08002601 mNumWrites++;
2602 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002603 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002604 return bytesWritten;
2605}
2606
2607void AudioFlinger::PlaybackThread::threadLoop_drain()
2608{
2609 if (mOutput->stream->drain) {
2610 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2611 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002612 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2613 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002614 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002615 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002616 }
2617 mOutput->stream->drain(mOutput->stream,
2618 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2619 : AUDIO_DRAIN_ALL);
2620 }
2621}
2622
2623void AudioFlinger::PlaybackThread::threadLoop_exit()
2624{
Eric Laurent275e8e92014-11-30 15:14:47 -08002625 {
2626 Mutex::Autolock _l(mLock);
2627 for (size_t i = 0; i < mTracks.size(); i++) {
2628 sp<Track> track = mTracks[i];
2629 track->invalidate();
2630 }
2631 }
Eric Laurent81784c32012-11-19 14:55:58 -08002632}
2633
2634/*
2635The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002636 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002637 - mActiveSleepTimeUs from activeSleepTimeUs()
2638 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08002639 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
2640 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08002641 - maxPeriod from frame count and sample rate (MIXER only)
2642
2643The parameters that affect these derived values are:
2644 - frame count
2645 - frame size
2646 - sample rate
2647 - device type: A2DP or not
2648 - device latency
2649 - format: PCM or not
2650 - active sleep time
2651 - idle sleep time
2652*/
2653
2654void AudioFlinger::PlaybackThread::cacheParameters_l()
2655{
Andy Hung25c2dac2014-02-27 14:56:00 -08002656 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002657 mActiveSleepTimeUs = activeSleepTimeUs();
2658 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08002659
2660 // make sure standby delay is not too short when connected to an A2DP sink to avoid
2661 // truncating audio when going to standby.
2662 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
2663 if ((mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != 0) {
2664 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
2665 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
2666 }
2667 }
Eric Laurent81784c32012-11-19 14:55:58 -08002668}
2669
2670void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2671{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002672 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08002673 this, streamType, mTracks.size());
2674 Mutex::Autolock _l(mLock);
2675
2676 size_t size = mTracks.size();
2677 for (size_t i = 0; i < size; i++) {
2678 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07002679 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002680 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08002681 }
2682 }
2683}
2684
2685status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2686{
Glenn Kastend848eb42016-03-08 13:42:11 -08002687 audio_session_t session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002688 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2689 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002690 bool ownsBuffer = false;
2691
2692 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Glenn Kastend848eb42016-03-08 13:42:11 -08002693 if (session > AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002694 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002695 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002696 if (mType != DIRECT) {
2697 size_t numSamples = mNormalFrameCount * mChannelCount;
2698 buffer = new int16_t[numSamples];
2699 memset(buffer, 0, numSamples * sizeof(int16_t));
2700 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2701 ownsBuffer = true;
2702 }
2703
2704 // Attach all tracks with same session ID to this chain.
2705 for (size_t i = 0; i < mTracks.size(); ++i) {
2706 sp<Track> track = mTracks[i];
2707 if (session == track->sessionId()) {
2708 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2709 buffer);
2710 track->setMainBuffer(buffer);
2711 chain->incTrackCnt();
2712 }
2713 }
2714
2715 // indicate all active tracks in the chain
2716 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2717 sp<Track> track = mActiveTracks[i].promote();
2718 if (track == 0) {
2719 continue;
2720 }
2721 if (session == track->sessionId()) {
2722 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2723 chain->incActiveTrackCnt();
2724 }
2725 }
2726 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002727 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08002728 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002729 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2730 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002731 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Glenn Kastend848eb42016-03-08 13:42:11 -08002732 // chains list in order to be processed last as it contains output stage effects.
Eric Laurent81784c32012-11-19 14:55:58 -08002733 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2734 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08002735 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08002736 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08002737 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08002738 // Effect chain for other sessions are inserted at beginning of effect
2739 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08002740 // sessions is not important.
2741 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
2742 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX,
2743 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08002744 size_t size = mEffectChains.size();
2745 size_t i = 0;
2746 for (i = 0; i < size; i++) {
2747 if (mEffectChains[i]->sessionId() < session) {
2748 break;
2749 }
2750 }
2751 mEffectChains.insertAt(chain, i);
2752 checkSuspendOnAddEffectChain_l(chain);
2753
2754 return NO_ERROR;
2755}
2756
2757size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2758{
Glenn Kastend848eb42016-03-08 13:42:11 -08002759 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08002760
2761 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2762
2763 for (size_t i = 0; i < mEffectChains.size(); i++) {
2764 if (chain == mEffectChains[i]) {
2765 mEffectChains.removeAt(i);
2766 // detach all active tracks from the chain
2767 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2768 sp<Track> track = mActiveTracks[i].promote();
2769 if (track == 0) {
2770 continue;
2771 }
2772 if (session == track->sessionId()) {
2773 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2774 chain.get(), session);
2775 chain->decActiveTrackCnt();
2776 }
2777 }
2778
2779 // detach all tracks with same session ID from this chain
2780 for (size_t i = 0; i < mTracks.size(); ++i) {
2781 sp<Track> track = mTracks[i];
2782 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002783 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002784 chain->decTrackCnt();
2785 }
2786 }
2787 break;
2788 }
2789 }
2790 return mEffectChains.size();
2791}
2792
2793status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2794 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2795{
2796 Mutex::Autolock _l(mLock);
2797 return attachAuxEffect_l(track, EffectId);
2798}
2799
2800status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2801 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2802{
2803 status_t status = NO_ERROR;
2804
2805 if (EffectId == 0) {
2806 track->setAuxBuffer(0, NULL);
2807 } else {
2808 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2809 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2810 if (effect != 0) {
2811 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2812 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2813 } else {
2814 status = INVALID_OPERATION;
2815 }
2816 } else {
2817 status = BAD_VALUE;
2818 }
2819 }
2820 return status;
2821}
2822
2823void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2824{
2825 for (size_t i = 0; i < mTracks.size(); ++i) {
2826 sp<Track> track = mTracks[i];
2827 if (track->auxEffectId() == effectId) {
2828 attachAuxEffect_l(track, 0);
2829 }
2830 }
2831}
2832
2833bool AudioFlinger::PlaybackThread::threadLoop()
2834{
2835 Vector< sp<Track> > tracksToRemove;
2836
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002837 mStandbyTimeNs = systemTime();
Eric Laurent81784c32012-11-19 14:55:58 -08002838
2839 // MIXER
2840 nsecs_t lastWarning = 0;
2841
2842 // DUPLICATING
2843 // FIXME could this be made local to while loop?
2844 writeFrames = 0;
2845
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002846 int lastGeneration = 0;
2847
Eric Laurent81784c32012-11-19 14:55:58 -08002848 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002849 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002850
2851 if (mType == MIXER) {
2852 sleepTimeShift = 0;
2853 }
2854
2855 CpuStats cpuStats;
2856 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2857
2858 acquireWakeLock();
2859
Glenn Kasten9e58b552013-01-18 15:09:48 -08002860 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2861 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2862 // and then that string will be logged at the next convenient opportunity.
2863 const char *logString = NULL;
2864
Eric Laurent664539d2013-09-23 18:24:31 -07002865 checkSilentMode_l();
2866
Eric Laurent81784c32012-11-19 14:55:58 -08002867 while (!exitPending())
2868 {
2869 cpuStats.sample(myName);
2870
2871 Vector< sp<EffectChain> > effectChains;
2872
Eric Laurent81784c32012-11-19 14:55:58 -08002873 { // scope for mLock
2874
2875 Mutex::Autolock _l(mLock);
2876
Eric Laurent021cf962014-05-13 10:18:14 -07002877 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002878
Glenn Kasten9e58b552013-01-18 15:09:48 -08002879 if (logString != NULL) {
2880 mNBLogWriter->logTimestamp();
2881 mNBLogWriter->log(logString);
2882 logString = NULL;
2883 }
2884
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002885 // Gather the framesReleased counters for all active tracks,
Andy Hunge10393e2015-06-12 13:59:33 -07002886 // and associate with the sink frames written out. We need
2887 // this to convert the sink timestamp to the track timestamp.
2888 if (mNormalSink != 0) {
Andy Hungc54b1ff2016-02-23 14:07:07 -08002889 // Note: The DuplicatingThread may not have a mNormalSink.
Andy Hung818e7a32016-02-16 18:08:07 -08002890 // We always fetch the timestamp here because often the downstream
2891 // sink will block whie writing.
2892 ExtendedTimestamp timestamp; // use private copy to fetch
2893 (void) mNormalSink->getTimestamp(timestamp);
2894 // copy over kernel info
2895 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
2896 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
2897 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
2898 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hungc54b1ff2016-02-23 14:07:07 -08002899 }
2900 // mFramesWritten for non-offloaded tracks are contiguous
2901 // even after standby() is called. This is useful for the track frame
2902 // to sink frame mapping.
2903 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
2904 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
2905 const size_t size = mActiveTracks.size();
2906 for (size_t i = 0; i < size; ++i) {
2907 sp<Track> t = mActiveTracks[i].promote();
2908 if (t != 0 && !t->isFastTrack()) {
2909 t->updateTrackFrameInfo(
2910 t->mAudioTrackServerProxy->framesReleased(),
2911 mFramesWritten,
2912 mTimestamp);
Andy Hunge10393e2015-06-12 13:59:33 -07002913 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002914 }
2915
Eric Laurent81784c32012-11-19 14:55:58 -08002916 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002917 if (mSignalPending) {
2918 // A signal was raised while we were unlocked
2919 mSignalPending = false;
2920 } else if (waitingAsyncCallback_l()) {
2921 if (exitPending()) {
2922 break;
2923 }
Marco Nelissen078538c2015-05-12 09:17:57 -07002924 bool released = false;
2925 // The following works around a bug in the offload driver. Ideally we would release
2926 // the wake lock every time, but that causes the last offload buffer(s) to be
2927 // dropped while the device is on battery, so we need to hold a wake lock during
2928 // the drain phase.
2929 if (mBytesRemaining && !(mDrainSequence & 1)) {
2930 releaseWakeLock_l();
2931 released = true;
2932 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002933 mWakeLockUids.clear();
2934 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002935 ALOGV("wait async completion");
2936 mWaitWorkCV.wait(mLock);
2937 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07002938 if (released) {
2939 acquireWakeLock_l();
2940 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002941 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
2942 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002943
2944 continue;
2945 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002946 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002947 isSuspended()) {
2948 // put audio hardware into standby after short delay
2949 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002950
2951 threadLoop_standby();
2952
2953 mStandby = true;
2954 }
2955
2956 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2957 // we're about to wait, flush the binder command buffer
2958 IPCThreadState::self()->flushCommands();
2959
2960 clearOutputTracks();
2961
2962 if (exitPending()) {
2963 break;
2964 }
2965
2966 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002967 mWakeLockUids.clear();
2968 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002969 // wait until we have something to do...
2970 ALOGV("%s going to sleep", myName.string());
2971 mWaitWorkCV.wait(mLock);
2972 ALOGV("%s waking up", myName.string());
2973 acquireWakeLock_l();
2974
2975 mMixerStatus = MIXER_IDLE;
2976 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2977 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002978 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002979 checkSilentMode_l();
2980
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002981 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
2982 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002983 if (mType == MIXER) {
2984 sleepTimeShift = 0;
2985 }
2986
2987 continue;
2988 }
2989 }
Eric Laurent81784c32012-11-19 14:55:58 -08002990 // mMixerStatusIgnoringFastTracks is also updated internally
2991 mMixerStatus = prepareTracks_l(&tracksToRemove);
2992
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002993 // compare with previously applied list
2994 if (lastGeneration != mActiveTracksGeneration) {
2995 // update wakelock
2996 updateWakeLockUids_l(mWakeLockUids);
2997 lastGeneration = mActiveTracksGeneration;
2998 }
2999
Eric Laurent81784c32012-11-19 14:55:58 -08003000 // prevent any changes in effect chain list and in each effect chain
3001 // during mixing and effect process as the audio buffers could be deleted
3002 // or modified if an effect is created or deleted
3003 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003004 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003005
Eric Laurentbfb1b832013-01-07 09:53:42 -08003006 if (mBytesRemaining == 0) {
3007 mCurrentWriteLength = 0;
3008 if (mMixerStatus == MIXER_TRACKS_READY) {
3009 // threadLoop_mix() sets mCurrentWriteLength
3010 threadLoop_mix();
3011 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3012 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003013 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003014 // must be written to HAL
3015 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003016 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003017 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003018 }
3019 }
Andy Hung98ef9782014-03-04 14:46:50 -08003020 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003021 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003022 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3023 // or mSinkBuffer (if there are no effects).
3024 //
3025 // This is done pre-effects computation; if effects change to
3026 // support higher precision, this needs to move.
3027 //
3028 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003029 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003030 if (mMixerBufferValid) {
3031 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3032 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3033
Andy Hung2ddee192015-12-18 17:34:44 -08003034 // mono blend occurs for mixer threads only (not direct or offloaded)
3035 // and is handled here if we're going directly to the sink.
3036 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003037 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3038 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003039 }
3040
Andy Hung98ef9782014-03-04 14:46:50 -08003041 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
3042 mNormalFrameCount * mChannelCount);
3043 }
3044
Eric Laurentbfb1b832013-01-07 09:53:42 -08003045 mBytesRemaining = mCurrentWriteLength;
3046 if (isSuspended()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003047 mSleepTimeUs = suspendSleepTimeUs();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003048 // simulate write to HAL when suspended
Andy Hung25c2dac2014-02-27 14:56:00 -08003049 mBytesWritten += mSinkBufferSize;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003050 mFramesWritten += mSinkBufferSize / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003051 mBytesRemaining = 0;
3052 }
Eric Laurent81784c32012-11-19 14:55:58 -08003053
Eric Laurentbfb1b832013-01-07 09:53:42 -08003054 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003055 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003056 for (size_t i = 0; i < effectChains.size(); i ++) {
3057 effectChains[i]->process_l();
3058 }
Eric Laurent81784c32012-11-19 14:55:58 -08003059 }
3060 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003061 // Process effect chains for offloaded thread even if no audio
3062 // was read from audio track: process only updates effect state
3063 // and thus does have to be synchronized with audio writes but may have
3064 // to be called while waiting for async write callback
3065 if (mType == OFFLOAD) {
3066 for (size_t i = 0; i < effectChains.size(); i ++) {
3067 effectChains[i]->process_l();
3068 }
3069 }
Eric Laurent81784c32012-11-19 14:55:58 -08003070
Andy Hung98ef9782014-03-04 14:46:50 -08003071 // Only if the Effects buffer is enabled and there is data in the
3072 // Effects buffer (buffer valid), we need to
3073 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003074 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003075 if (mEffectBufferValid) {
3076 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003077
3078 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003079 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3080 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003081 }
3082
Andy Hung98ef9782014-03-04 14:46:50 -08003083 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
3084 mNormalFrameCount * mChannelCount);
3085 }
3086
Eric Laurent81784c32012-11-19 14:55:58 -08003087 // enable changes in effect chain
3088 unlockEffectChains(effectChains);
3089
Eric Laurentbfb1b832013-01-07 09:53:42 -08003090 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003091 // mSleepTimeUs == 0 means we must write to audio hardware
3092 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003093 ssize_t ret = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003094 if (mBytesRemaining) {
Andy Hung08fb1742015-05-31 23:22:10 -07003095 ret = threadLoop_write();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003096 if (ret < 0) {
3097 mBytesRemaining = 0;
3098 } else {
3099 mBytesWritten += ret;
3100 mBytesRemaining -= ret;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003101 mFramesWritten += ret / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003102 }
3103 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3104 (mMixerStatus == MIXER_DRAIN_ALL)) {
3105 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003106 }
Andy Hung08fb1742015-05-31 23:22:10 -07003107 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003108 // write blocked detection
3109 nsecs_t now = systemTime();
3110 nsecs_t delta = now - mLastWriteTime;
Andy Hung08fb1742015-05-31 23:22:10 -07003111 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003112 mNumDelayedWrites++;
3113 if ((now - lastWarning) > kWarningThrottleNs) {
3114 ATRACE_NAME("underrun");
3115 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003116 (unsigned long long) ns2ms(delta), mNumDelayedWrites, this);
Glenn Kasten4944acb2013-08-19 08:39:20 -07003117 lastWarning = now;
3118 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003119 }
Andy Hung08fb1742015-05-31 23:22:10 -07003120
3121 if (mThreadThrottle
3122 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
3123 && ret > 0) { // we wrote something
3124 // Limit MixerThread data processing to no more than twice the
3125 // expected processing rate.
3126 //
3127 // This helps prevent underruns with NuPlayer and other applications
3128 // which may set up buffers that are close to the minimum size, or use
3129 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3130 //
3131 // The throttle smooths out sudden large data drains from the device,
3132 // e.g. when it comes out of standby, which often causes problems with
3133 // (1) mixer threads without a fast mixer (which has its own warm-up)
3134 // (2) minimum buffer sized tracks (even if the track is full,
3135 // the app won't fill fast enough to handle the sudden draw).
3136
3137 const int32_t deltaMs = delta / 1000000;
3138 const int32_t throttleMs = mHalfBufferMs - deltaMs;
3139 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3140 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003141 // notify of throttle start on verbose log
3142 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3143 "mixer(%p) throttle begin:"
3144 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003145 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003146 mThreadThrottleTimeMs += throttleMs;
3147 } else {
3148 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3149 if (diff > 0) {
3150 // notify of throttle end on debug log
3151 ALOGD("mixer(%p) throttle end: throttle time(%u)", this, diff);
3152 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3153 }
Andy Hung08fb1742015-05-31 23:22:10 -07003154 }
3155 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003156 }
Eric Laurent81784c32012-11-19 14:55:58 -08003157
Eric Laurentbfb1b832013-01-07 09:53:42 -08003158 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003159 ATRACE_BEGIN("sleep");
Eric Laurent51716182016-02-29 18:00:56 -08003160 if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
3161 Mutex::Autolock _l(mLock);
3162 if (!mSignalPending && !exitPending()) {
3163 // Do not sleep more than one buffer duration since last write and not
3164 // less than kDirectMinSleepTimeUs
3165 // Wake up if a command is received
3166 nsecs_t now = systemTime();
3167 uint32_t deltaUs = (uint32_t)((now - mLastWriteTime) / 1000);
3168 uint32_t timeoutUs = mSleepTimeUs;
3169 if (timeoutUs + deltaUs > mBufferDurationUs) {
3170 if (mBufferDurationUs > deltaUs) {
3171 timeoutUs = mBufferDurationUs - deltaUs;
3172 if (timeoutUs < kDirectMinSleepTimeUs) {
3173 timeoutUs = kDirectMinSleepTimeUs;
3174 }
3175 } else {
3176 timeoutUs = kDirectMinSleepTimeUs;
3177 }
3178 }
3179 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)timeoutUs));
3180 }
3181 } else {
3182 usleep(mSleepTimeUs);
3183 }
Glenn Kastene7754022014-10-31 12:11:26 -07003184 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003185 }
Eric Laurent81784c32012-11-19 14:55:58 -08003186 }
3187
3188 // Finally let go of removed track(s), without the lock held
3189 // since we can't guarantee the destructors won't acquire that
3190 // same lock. This will also mutate and push a new fast mixer state.
3191 threadLoop_removeTracks(tracksToRemove);
3192 tracksToRemove.clear();
3193
3194 // FIXME I don't understand the need for this here;
3195 // it was in the original code but maybe the
3196 // assignment in saveOutputTracks() makes this unnecessary?
3197 clearOutputTracks();
3198
3199 // Effect chains will be actually deleted here if they were removed from
3200 // mEffectChains list during mixing or effects processing
3201 effectChains.clear();
3202
3203 // FIXME Note that the above .clear() is no longer necessary since effectChains
3204 // is now local to this block, but will keep it for now (at least until merge done).
3205 }
3206
Eric Laurentbfb1b832013-01-07 09:53:42 -08003207 threadLoop_exit();
3208
Eric Laurentcf817a22014-08-04 20:36:31 -07003209 if (!mStandby) {
3210 threadLoop_standby();
3211 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003212 }
3213
3214 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003215 mWakeLockUids.clear();
3216 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08003217
3218 ALOGV("Thread %p type %d exiting", this, mType);
3219 return false;
3220}
3221
Eric Laurentbfb1b832013-01-07 09:53:42 -08003222// removeTracks_l() must be called with ThreadBase::mLock held
3223void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3224{
3225 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003226 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003227 for (size_t i=0 ; i<count ; i++) {
3228 const sp<Track>& track = tracksToRemove.itemAt(i);
3229 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003230 mWakeLockUids.remove(track->uid());
3231 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003232 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3233 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3234 if (chain != 0) {
3235 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3236 track->sessionId());
3237 chain->decActiveTrackCnt();
3238 }
3239 if (track->isTerminated()) {
3240 removeTrack_l(track);
3241 }
3242 }
3243 }
3244
3245}
Eric Laurent81784c32012-11-19 14:55:58 -08003246
Eric Laurentaccc1472013-09-20 09:36:34 -07003247status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3248{
3249 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08003250 ExtendedTimestamp ets;
3251 status_t status = mNormalSink->getTimestamp(ets);
3252 if (status == NO_ERROR) {
3253 status = ets.getBestTimestamp(&timestamp);
3254 }
3255 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07003256 }
Andy Hung9a1c8892014-12-03 11:37:42 -08003257 if ((mType == OFFLOAD || mType == DIRECT)
3258 && mOutput != NULL && mOutput->stream->get_presentation_position) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003259 uint64_t position64;
Phil Burk062e67a2015-02-11 13:40:50 -08003260 int ret = mOutput->getPresentationPosition(&position64, &timestamp.mTime);
Eric Laurentaccc1472013-09-20 09:36:34 -07003261 if (ret == 0) {
3262 timestamp.mPosition = (uint32_t)position64;
3263 return NO_ERROR;
3264 }
3265 }
3266 return INVALID_OPERATION;
3267}
Eric Laurent1c333e22014-05-20 10:48:17 -07003268
Eric Laurent054d9d32015-04-24 08:48:48 -07003269status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3270 audio_patch_handle_t *handle)
3271{
3272 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3273 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3274 if (mFastMixer != 0) {
3275 FastMixerStateQueue *sq = mFastMixer->sq();
3276 FastMixerState *state = sq->begin();
3277 if (!(state->mCommand & FastMixerState::IDLE)) {
3278 previousCommand = state->mCommand;
3279 state->mCommand = FastMixerState::HOT_IDLE;
3280 sq->end();
3281 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3282 } else {
3283 sq->end(false /*didModify*/);
3284 }
3285 }
3286 status_t status = PlaybackThread::createAudioPatch_l(patch, handle);
3287
3288 if (!(previousCommand & FastMixerState::IDLE)) {
3289 ALOG_ASSERT(mFastMixer != 0);
3290 FastMixerStateQueue *sq = mFastMixer->sq();
3291 FastMixerState *state = sq->begin();
3292 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3293 state->mCommand = previousCommand;
3294 sq->end();
3295 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3296 }
3297
3298 return status;
3299}
3300
Eric Laurent1c333e22014-05-20 10:48:17 -07003301status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3302 audio_patch_handle_t *handle)
3303{
3304 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003305
3306 // store new device and send to effects
3307 audio_devices_t type = AUDIO_DEVICE_NONE;
3308 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3309 type |= patch->sinks[i].ext.device.type;
3310 }
3311
3312#ifdef ADD_BATTERY_DATA
3313 // when changing the audio output device, call addBatteryData to notify
3314 // the change
3315 if (mOutDevice != type) {
3316 uint32_t params = 0;
3317 // check whether speaker is on
3318 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3319 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003320 }
3321
Eric Laurent054d9d32015-04-24 08:48:48 -07003322 audio_devices_t deviceWithoutSpeaker
3323 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3324 // check if any other device (except speaker) is on
3325 if (type & deviceWithoutSpeaker) {
3326 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3327 }
3328
3329 if (params != 0) {
3330 addBatteryData(params);
3331 }
3332 }
3333#endif
3334
3335 for (size_t i = 0; i < mEffectChains.size(); i++) {
3336 mEffectChains[i]->setDevice_l(type);
3337 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003338
3339 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3340 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3341 bool configChanged = mPrevOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003342 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003343 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003344
3345 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003346 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3347 status = hwDevice->create_audio_patch(hwDevice,
3348 patch->num_sources,
3349 patch->sources,
3350 patch->num_sinks,
3351 patch->sinks,
3352 handle);
3353 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003354 char *address;
3355 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3356 //FIXME: we only support address on first sink with HAL version < 3.0
3357 address = audio_device_address_to_parameter(
3358 patch->sinks[0].ext.device.type,
3359 patch->sinks[0].ext.device.address);
3360 } else {
3361 address = (char *)calloc(1, 1);
3362 }
3363 AudioParameter param = AudioParameter(String8(address));
3364 free(address);
3365 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), (int)type);
3366 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3367 param.toString().string());
3368 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003369 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003370 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003371 mPrevOutDevice = type;
Eric Laurente8726fe2015-06-26 09:39:24 -07003372 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3373 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003374 return status;
3375}
3376
Eric Laurent054d9d32015-04-24 08:48:48 -07003377status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3378{
3379 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3380 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3381 if (mFastMixer != 0) {
3382 FastMixerStateQueue *sq = mFastMixer->sq();
3383 FastMixerState *state = sq->begin();
3384 if (!(state->mCommand & FastMixerState::IDLE)) {
3385 previousCommand = state->mCommand;
3386 state->mCommand = FastMixerState::HOT_IDLE;
3387 sq->end();
3388 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3389 } else {
3390 sq->end(false /*didModify*/);
3391 }
3392 }
3393
3394 status_t status = PlaybackThread::releaseAudioPatch_l(handle);
3395
3396 if (!(previousCommand & FastMixerState::IDLE)) {
3397 ALOG_ASSERT(mFastMixer != 0);
3398 FastMixerStateQueue *sq = mFastMixer->sq();
3399 FastMixerState *state = sq->begin();
3400 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3401 state->mCommand = previousCommand;
3402 sq->end();
3403 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3404 }
3405
3406 return status;
3407}
3408
Eric Laurent1c333e22014-05-20 10:48:17 -07003409status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3410{
3411 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003412
3413 mOutDevice = AUDIO_DEVICE_NONE;
3414
Eric Laurent1c333e22014-05-20 10:48:17 -07003415 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
3416 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3417 status = hwDevice->release_audio_patch(hwDevice, handle);
3418 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003419 AudioParameter param;
3420 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
3421 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3422 param.toString().string());
Eric Laurent1c333e22014-05-20 10:48:17 -07003423 }
3424 return status;
3425}
3426
Eric Laurent83b88082014-06-20 18:31:16 -07003427void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3428{
3429 Mutex::Autolock _l(mLock);
3430 mTracks.add(track);
3431}
3432
3433void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3434{
3435 Mutex::Autolock _l(mLock);
3436 destroyTrack_l(track);
3437}
3438
3439void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3440{
3441 ThreadBase::getAudioPortConfig(config);
3442 config->role = AUDIO_PORT_ROLE_SOURCE;
3443 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3444 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3445}
3446
Eric Laurent81784c32012-11-19 14:55:58 -08003447// ----------------------------------------------------------------------------
3448
3449AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003450 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3451 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003452 // mAudioMixer below
3453 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08003454 mFastMixerFutex(0),
3455 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08003456 // mOutputSink below
3457 // mPipeSink below
3458 // mNormalSink below
3459{
3460 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003461 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%zu, "
3462 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003463 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3464 mNormalFrameCount);
3465 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3466
Andy Hungfbfc3952015-01-15 13:33:51 -08003467 if (type == DUPLICATING) {
3468 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3469 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3470 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3471 return;
3472 }
Eric Laurent81784c32012-11-19 14:55:58 -08003473 // create an NBAIO sink for the HAL output stream, and negotiate
3474 mOutputSink = new AudioStreamOutSink(output->stream);
3475 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003476 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003477#if !LOG_NDEBUG
3478 ssize_t index =
3479#else
3480 (void)
3481#endif
3482 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003483 ALOG_ASSERT(index == 0);
3484
3485 // initialize fast mixer depending on configuration
3486 bool initFastMixer;
3487 switch (kUseFastMixer) {
3488 case FastMixer_Never:
3489 initFastMixer = false;
3490 break;
3491 case FastMixer_Always:
3492 initFastMixer = true;
3493 break;
3494 case FastMixer_Static:
3495 case FastMixer_Dynamic:
3496 initFastMixer = mFrameCount < mNormalFrameCount;
3497 break;
3498 }
3499 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003500 audio_format_t fastMixerFormat;
3501 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3502 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3503 } else {
3504 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3505 }
3506 if (mFormat != fastMixerFormat) {
3507 // change our Sink format to accept our intermediate precision
3508 mFormat = fastMixerFormat;
3509 free(mSinkBuffer);
3510 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3511 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3512 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3513 }
Eric Laurent81784c32012-11-19 14:55:58 -08003514
3515 // create a MonoPipe to connect our submix to FastMixer
3516 NBAIO_Format format = mOutputSink->format();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003517#ifdef TEE_SINK
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003518 NBAIO_Format origformat = format;
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003519#endif
Andy Hung1258c1a2014-05-23 21:22:17 -07003520 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07003521 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003522 format.mFormat = fastMixerFormat;
3523 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3524
Eric Laurent81784c32012-11-19 14:55:58 -08003525 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3526 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3527 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3528 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3529 const NBAIO_Format offers[1] = {format};
3530 size_t numCounterOffers = 0;
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003531#if !LOG_NDEBUG
3532 ssize_t index =
3533#else
3534 (void)
3535#endif
3536 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003537 ALOG_ASSERT(index == 0);
3538 monoPipe->setAvgFrames((mScreenState & 1) ?
3539 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3540 mPipeSink = monoPipe;
3541
Glenn Kasten46909e72013-02-26 09:20:22 -08003542#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003543 if (mTeeSinkOutputEnabled) {
3544 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003545 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3546 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003547 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003548 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003549 ALOG_ASSERT(index == 0);
3550 mTeeSink = teeSink;
3551 PipeReader *teeSource = new PipeReader(*teeSink);
3552 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003553 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003554 ALOG_ASSERT(index == 0);
3555 mTeeSource = teeSource;
3556 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003557#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003558
3559 // create fast mixer and configure it initially with just one fast track for our submix
3560 mFastMixer = new FastMixer();
3561 FastMixerStateQueue *sq = mFastMixer->sq();
3562#ifdef STATE_QUEUE_DUMP
3563 sq->setObserverDump(&mStateQueueObserverDump);
3564 sq->setMutatorDump(&mStateQueueMutatorDump);
3565#endif
3566 FastMixerState *state = sq->begin();
3567 FastTrack *fastTrack = &state->mFastTracks[0];
3568 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3569 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3570 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003571 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3572 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003573 fastTrack->mGeneration++;
3574 state->mFastTracksGen++;
3575 state->mTrackMask = 1;
3576 // fast mixer will use the HAL output sink
3577 state->mOutputSink = mOutputSink.get();
3578 state->mOutputSinkGen++;
3579 state->mFrameCount = mFrameCount;
3580 state->mCommand = FastMixerState::COLD_IDLE;
3581 // already done in constructor initialization list
3582 //mFastMixerFutex = 0;
3583 state->mColdFutexAddr = &mFastMixerFutex;
3584 state->mColdGen++;
3585 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003586#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003587 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003588#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003589 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3590 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003591 sq->end();
3592 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3593
3594 // start the fast mixer
3595 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3596 pid_t tid = mFastMixer->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003597 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003598
3599#ifdef AUDIO_WATCHDOG
3600 // create and start the watchdog
3601 mAudioWatchdog = new AudioWatchdog();
3602 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3603 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3604 tid = mAudioWatchdog->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003605 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003606#endif
3607
Eric Laurent81784c32012-11-19 14:55:58 -08003608 }
3609
3610 switch (kUseFastMixer) {
3611 case FastMixer_Never:
3612 case FastMixer_Dynamic:
3613 mNormalSink = mOutputSink;
3614 break;
3615 case FastMixer_Always:
3616 mNormalSink = mPipeSink;
3617 break;
3618 case FastMixer_Static:
3619 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3620 break;
3621 }
3622}
3623
3624AudioFlinger::MixerThread::~MixerThread()
3625{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003626 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003627 FastMixerStateQueue *sq = mFastMixer->sq();
3628 FastMixerState *state = sq->begin();
3629 if (state->mCommand == FastMixerState::COLD_IDLE) {
3630 int32_t old = android_atomic_inc(&mFastMixerFutex);
3631 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003632 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003633 }
3634 }
3635 state->mCommand = FastMixerState::EXIT;
3636 sq->end();
3637 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3638 mFastMixer->join();
3639 // Though the fast mixer thread has exited, it's state queue is still valid.
3640 // We'll use that extract the final state which contains one remaining fast track
3641 // corresponding to our sub-mix.
3642 state = sq->begin();
3643 ALOG_ASSERT(state->mTrackMask == 1);
3644 FastTrack *fastTrack = &state->mFastTracks[0];
3645 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3646 delete fastTrack->mBufferProvider;
3647 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003648 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003649#ifdef AUDIO_WATCHDOG
3650 if (mAudioWatchdog != 0) {
3651 mAudioWatchdog->requestExit();
3652 mAudioWatchdog->requestExitAndWait();
3653 mAudioWatchdog.clear();
3654 }
3655#endif
3656 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003657 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003658 delete mAudioMixer;
3659}
3660
3661
3662uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3663{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003664 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003665 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3666 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3667 }
3668 return latency;
3669}
3670
3671
3672void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3673{
3674 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3675}
3676
Eric Laurentbfb1b832013-01-07 09:53:42 -08003677ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003678{
3679 // FIXME we should only do one push per cycle; confirm this is true
3680 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003681 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003682 FastMixerStateQueue *sq = mFastMixer->sq();
3683 FastMixerState *state = sq->begin();
3684 if (state->mCommand != FastMixerState::MIX_WRITE &&
3685 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3686 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07003687
3688 // FIXME workaround for first HAL write being CPU bound on some devices
3689 ATRACE_BEGIN("write");
3690 mOutput->write((char *)mSinkBuffer, 0);
3691 ATRACE_END();
3692
Eric Laurent81784c32012-11-19 14:55:58 -08003693 int32_t old = android_atomic_inc(&mFastMixerFutex);
3694 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003695 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003696 }
3697#ifdef AUDIO_WATCHDOG
3698 if (mAudioWatchdog != 0) {
3699 mAudioWatchdog->resume();
3700 }
3701#endif
3702 }
3703 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003704#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003705 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003706 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003707#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003708 sq->end();
3709 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3710 if (kUseFastMixer == FastMixer_Dynamic) {
3711 mNormalSink = mPipeSink;
3712 }
3713 } else {
3714 sq->end(false /*didModify*/);
3715 }
3716 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003717 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003718}
3719
3720void AudioFlinger::MixerThread::threadLoop_standby()
3721{
3722 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003723 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003724 FastMixerStateQueue *sq = mFastMixer->sq();
3725 FastMixerState *state = sq->begin();
3726 if (!(state->mCommand & FastMixerState::IDLE)) {
3727 state->mCommand = FastMixerState::COLD_IDLE;
3728 state->mColdFutexAddr = &mFastMixerFutex;
3729 state->mColdGen++;
3730 mFastMixerFutex = 0;
3731 sq->end();
3732 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3733 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3734 if (kUseFastMixer == FastMixer_Dynamic) {
3735 mNormalSink = mOutputSink;
3736 }
3737#ifdef AUDIO_WATCHDOG
3738 if (mAudioWatchdog != 0) {
3739 mAudioWatchdog->pause();
3740 }
3741#endif
3742 } else {
3743 sq->end(false /*didModify*/);
3744 }
3745 }
3746 PlaybackThread::threadLoop_standby();
3747}
3748
Eric Laurentbfb1b832013-01-07 09:53:42 -08003749bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3750{
3751 return false;
3752}
3753
3754bool AudioFlinger::PlaybackThread::shouldStandby_l()
3755{
3756 return !mStandby;
3757}
3758
3759bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3760{
3761 Mutex::Autolock _l(mLock);
3762 return waitingAsyncCallback_l();
3763}
3764
Eric Laurent81784c32012-11-19 14:55:58 -08003765// shared by MIXER and DIRECT, overridden by DUPLICATING
3766void AudioFlinger::PlaybackThread::threadLoop_standby()
3767{
3768 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08003769 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003770 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003771 // discard any pending drain or write ack by incrementing sequence
3772 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3773 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003774 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003775 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3776 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003777 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003778 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003779}
3780
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003781void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3782{
3783 ALOGV("signal playback thread");
3784 broadcast_l();
3785}
3786
Eric Laurent81784c32012-11-19 14:55:58 -08003787void AudioFlinger::MixerThread::threadLoop_mix()
3788{
Eric Laurent81784c32012-11-19 14:55:58 -08003789 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08003790 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08003791 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003792 // increase sleep time progressively when application underrun condition clears.
3793 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3794 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3795 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003796 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003797 sleepTimeShift--;
3798 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003799 mSleepTimeUs = 0;
3800 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08003801 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003802
Eric Laurent81784c32012-11-19 14:55:58 -08003803}
3804
3805void AudioFlinger::MixerThread::threadLoop_sleepTime()
3806{
3807 // If no tracks are ready, sleep once for the duration of an output
3808 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003809 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003810 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003811 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
3812 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
3813 mSleepTimeUs = kMinThreadSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003814 }
3815 // reduce sleep time in case of consecutive application underruns to avoid
3816 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3817 // duration we would end up writing less data than needed by the audio HAL if
3818 // the condition persists.
3819 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3820 sleepTimeShift++;
3821 }
3822 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003823 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003824 }
3825 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003826 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3827 // before effects processing or output.
3828 if (mMixerBufferValid) {
3829 memset(mMixerBuffer, 0, mMixerBufferSize);
3830 } else {
3831 memset(mSinkBuffer, 0, mSinkBufferSize);
3832 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003833 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003834 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3835 "anticipated start");
3836 }
3837 // TODO add standby time extension fct of effect tail
3838}
3839
3840// prepareTracks_l() must be called with ThreadBase::mLock held
3841AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3842 Vector< sp<Track> > *tracksToRemove)
3843{
3844
3845 mixer_state mixerStatus = MIXER_IDLE;
3846 // find out which tracks need to be processed
3847 size_t count = mActiveTracks.size();
3848 size_t mixedTracks = 0;
3849 size_t tracksWithEffect = 0;
3850 // counts only _active_ fast tracks
3851 size_t fastTracks = 0;
3852 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3853
3854 float masterVolume = mMasterVolume;
3855 bool masterMute = mMasterMute;
3856
3857 if (masterMute) {
3858 masterVolume = 0;
3859 }
3860 // Delegate master volume control to effect in output mix effect chain if needed
3861 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3862 if (chain != 0) {
3863 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3864 chain->setVolume_l(&v, &v);
3865 masterVolume = (float)((v + (1 << 23)) >> 24);
3866 chain.clear();
3867 }
3868
3869 // prepare a new state to push
3870 FastMixerStateQueue *sq = NULL;
3871 FastMixerState *state = NULL;
3872 bool didModify = false;
3873 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003874 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003875 sq = mFastMixer->sq();
3876 state = sq->begin();
3877 }
3878
Andy Hung69aed5f2014-02-25 17:24:40 -08003879 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003880 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003881
Eric Laurent81784c32012-11-19 14:55:58 -08003882 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003883 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003884 if (t == 0) {
3885 continue;
3886 }
3887
3888 // this const just means the local variable doesn't change
3889 Track* const track = t.get();
3890
3891 // process fast tracks
3892 if (track->isFastTrack()) {
3893
3894 // It's theoretically possible (though unlikely) for a fast track to be created
3895 // and then removed within the same normal mix cycle. This is not a problem, as
3896 // the track never becomes active so it's fast mixer slot is never touched.
3897 // The converse, of removing an (active) track and then creating a new track
3898 // at the identical fast mixer slot within the same normal mix cycle,
3899 // is impossible because the slot isn't marked available until the end of each cycle.
3900 int j = track->mFastIndex;
3901 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
3902 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3903 FastTrack *fastTrack = &state->mFastTracks[j];
3904
3905 // Determine whether the track is currently in underrun condition,
3906 // and whether it had a recent underrun.
3907 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3908 FastTrackUnderruns underruns = ftDump->mUnderruns;
3909 uint32_t recentFull = (underruns.mBitFields.mFull -
3910 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3911 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3912 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3913 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3914 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3915 uint32_t recentUnderruns = recentPartial + recentEmpty;
3916 track->mObservedUnderruns = underruns;
3917 // don't count underruns that occur while stopping or pausing
3918 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07003919 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3920 recentUnderruns > 0) {
3921 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3922 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Phil Burk2812d9e2016-01-04 10:34:30 -08003923 } else {
3924 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Eric Laurent81784c32012-11-19 14:55:58 -08003925 }
3926
3927 // This is similar to the state machine for normal tracks,
3928 // with a few modifications for fast tracks.
3929 bool isActive = true;
3930 switch (track->mState) {
3931 case TrackBase::STOPPING_1:
3932 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08003933 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003934 track->mState = TrackBase::STOPPING_2;
3935 }
3936 break;
3937 case TrackBase::PAUSING:
3938 // ramp down is not yet implemented
3939 track->setPaused();
3940 break;
3941 case TrackBase::RESUMING:
3942 // ramp up is not yet implemented
3943 track->mState = TrackBase::ACTIVE;
3944 break;
3945 case TrackBase::ACTIVE:
3946 if (recentFull > 0 || recentPartial > 0) {
3947 // track has provided at least some frames recently: reset retry count
3948 track->mRetryCount = kMaxTrackRetries;
3949 }
3950 if (recentUnderruns == 0) {
3951 // no recent underruns: stay active
3952 break;
3953 }
3954 // there has recently been an underrun of some kind
3955 if (track->sharedBuffer() == 0) {
3956 // were any of the recent underruns "empty" (no frames available)?
3957 if (recentEmpty == 0) {
3958 // no, then ignore the partial underruns as they are allowed indefinitely
3959 break;
3960 }
3961 // there has recently been an "empty" underrun: decrement the retry counter
3962 if (--(track->mRetryCount) > 0) {
3963 break;
3964 }
3965 // indicate to client process that the track was disabled because of underrun;
3966 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08003967 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08003968 // remove from active list, but state remains ACTIVE [confusing but true]
3969 isActive = false;
3970 break;
3971 }
3972 // fall through
3973 case TrackBase::STOPPING_2:
3974 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003975 case TrackBase::STOPPED:
3976 case TrackBase::FLUSHED: // flush() while active
3977 // Check for presentation complete if track is inactive
3978 // We have consumed all the buffers of this track.
3979 // This would be incomplete if we auto-paused on underrun
3980 {
3981 size_t audioHALFrames =
3982 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08003983 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003984 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
3985 // track stays in active list until presentation is complete
3986 break;
3987 }
3988 }
3989 if (track->isStopping_2()) {
3990 track->mState = TrackBase::STOPPED;
3991 }
3992 if (track->isStopped()) {
3993 // Can't reset directly, as fast mixer is still polling this track
3994 // track->reset();
3995 // So instead mark this track as needing to be reset after push with ack
3996 resetMask |= 1 << i;
3997 }
3998 isActive = false;
3999 break;
4000 case TrackBase::IDLE:
4001 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08004002 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08004003 }
4004
4005 if (isActive) {
4006 // was it previously inactive?
4007 if (!(state->mTrackMask & (1 << j))) {
4008 ExtendedAudioBufferProvider *eabp = track;
4009 VolumeProvider *vp = track;
4010 fastTrack->mBufferProvider = eabp;
4011 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08004012 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07004013 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08004014 fastTrack->mGeneration++;
4015 state->mTrackMask |= 1 << j;
4016 didModify = true;
4017 // no acknowledgement required for newly active tracks
4018 }
4019 // cache the combined master volume and stream type volume for fast mixer; this
4020 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08004021 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08004022 ++fastTracks;
4023 } else {
4024 // was it previously active?
4025 if (state->mTrackMask & (1 << j)) {
4026 fastTrack->mBufferProvider = NULL;
4027 fastTrack->mGeneration++;
4028 state->mTrackMask &= ~(1 << j);
4029 didModify = true;
4030 // If any fast tracks were removed, we must wait for acknowledgement
4031 // because we're about to decrement the last sp<> on those tracks.
4032 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4033 } else {
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08004034 LOG_ALWAYS_FATAL("fast track %d should have been active; "
4035 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
4036 j, track->mState, state->mTrackMask, recentUnderruns,
4037 track->sharedBuffer() != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004038 }
4039 tracksToRemove->add(track);
4040 // Avoids a misleading display in dumpsys
4041 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
4042 }
4043 continue;
4044 }
4045
4046 { // local variable scope to avoid goto warning
4047
4048 audio_track_cblk_t* cblk = track->cblk();
4049
4050 // The first time a track is added we wait
4051 // for all its buffers to be filled before processing it
4052 int name = track->name();
4053 // make sure that we have enough frames to mix one full buffer.
4054 // enforce this condition only once to enable draining the buffer in case the client
4055 // app does not call stop() and relies on underrun to stop:
4056 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
4057 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004058 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07004059 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004060 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004061
4062 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004063 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004064 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
4065 // add frames already consumed but not yet released by the resampler
4066 // because mAudioTrackServerProxy->framesReady() will include these frames
4067 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
4068
Eric Laurent81784c32012-11-19 14:55:58 -08004069 uint32_t minFrames = 1;
4070 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
4071 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004072 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08004073 }
Eric Laurent13e4c962013-12-20 17:36:01 -08004074
4075 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07004076 if (ATRACE_ENABLED()) {
4077 // I wish we had formatted trace names
4078 char traceName[16];
4079 strcpy(traceName, "nRdy");
4080 int name = track->name();
4081 if (AudioMixer::TRACK0 <= name &&
4082 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
4083 name -= AudioMixer::TRACK0;
4084 traceName[4] = (name / 10) + '0';
4085 traceName[5] = (name % 10) + '0';
4086 } else {
4087 traceName[4] = '?';
4088 traceName[5] = '?';
4089 }
4090 traceName[6] = '\0';
4091 ATRACE_INT(traceName, framesReady);
4092 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004093 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08004094 !track->isPaused() && !track->isTerminated())
4095 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004096 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004097
4098 mixedTracks++;
4099
Andy Hung69aed5f2014-02-25 17:24:40 -08004100 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
4101 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08004102 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08004103 if (track->mainBuffer() != mSinkBuffer &&
4104 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004105 if (mEffectBufferEnabled) {
4106 mEffectBufferValid = true; // Later can set directly.
4107 }
Eric Laurent81784c32012-11-19 14:55:58 -08004108 chain = getEffectChain_l(track->sessionId());
4109 // Delegate volume control to effect in track effect chain if needed
4110 if (chain != 0) {
4111 tracksWithEffect++;
4112 } else {
4113 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
4114 "session %d",
4115 name, track->sessionId());
4116 }
4117 }
4118
4119
4120 int param = AudioMixer::VOLUME;
4121 if (track->mFillingUpStatus == Track::FS_FILLED) {
4122 // no ramp for the first volume setting
4123 track->mFillingUpStatus = Track::FS_ACTIVE;
4124 if (track->mState == TrackBase::RESUMING) {
4125 track->mState = TrackBase::ACTIVE;
4126 param = AudioMixer::RAMP_VOLUME;
4127 }
4128 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004129 // FIXME should not make a decision based on mServer
4130 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004131 // If the track is stopped before the first frame was mixed,
4132 // do not apply ramp
4133 param = AudioMixer::RAMP_VOLUME;
4134 }
4135
4136 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07004137 uint32_t vl, vr; // in U8.24 integer format
4138 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08004139 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07004140 vl = vr = 0;
4141 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08004142 if (track->isPausing()) {
4143 track->setPaused();
4144 }
4145 } else {
4146
4147 // read original volumes with volume control
4148 float typeVolume = mStreamTypes[track->streamType()].volume;
4149 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004150 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004151 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07004152 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
4153 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08004154 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07004155 if (vlf > GAIN_FLOAT_UNITY) {
4156 ALOGV("Track left volume out of range: %.3g", vlf);
4157 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004158 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07004159 if (vrf > GAIN_FLOAT_UNITY) {
4160 ALOGV("Track right volume out of range: %.3g", vrf);
4161 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004162 }
4163 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07004164 vlf *= v;
4165 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08004166 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07004167 // then derive vl and vr as U8.24 versions for the effect chain
4168 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
4169 vl = (uint32_t) (scaleto8_24 * vlf);
4170 vr = (uint32_t) (scaleto8_24 * vrf);
4171 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08004172 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08004173 // send level comes from shared memory and so may be corrupt
4174 if (sendLevel > MAX_GAIN_INT) {
4175 ALOGV("Track send level out of range: %04X", sendLevel);
4176 sendLevel = MAX_GAIN_INT;
4177 }
Andy Hung6be49402014-05-30 10:42:03 -07004178 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4179 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08004180 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004181
Eric Laurent81784c32012-11-19 14:55:58 -08004182 // Delegate volume control to effect in track effect chain if needed
4183 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4184 // Do not ramp volume if volume is controlled by effect
4185 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08004186 // Update remaining floating point volume levels
4187 vlf = (float)vl / (1 << 24);
4188 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004189 track->mHasVolumeController = true;
4190 } else {
4191 // force no volume ramp when volume controller was just disabled or removed
4192 // from effect chain to avoid volume spike
4193 if (track->mHasVolumeController) {
4194 param = AudioMixer::VOLUME;
4195 }
4196 track->mHasVolumeController = false;
4197 }
4198
Eric Laurent81784c32012-11-19 14:55:58 -08004199 // XXX: these things DON'T need to be done each time
4200 mAudioMixer->setBufferProvider(name, track);
4201 mAudioMixer->enable(name);
4202
Andy Hung6be49402014-05-30 10:42:03 -07004203 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
4204 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
4205 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004206 mAudioMixer->setParameter(
4207 name,
4208 AudioMixer::TRACK,
4209 AudioMixer::FORMAT, (void *)track->format());
4210 mAudioMixer->setParameter(
4211 name,
4212 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004213 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004214 mAudioMixer->setParameter(
4215 name,
4216 AudioMixer::TRACK,
4217 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004218 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004219 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004220 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004221 if (reqSampleRate == 0) {
4222 reqSampleRate = mSampleRate;
4223 } else if (reqSampleRate > maxSampleRate) {
4224 reqSampleRate = maxSampleRate;
4225 }
Eric Laurent81784c32012-11-19 14:55:58 -08004226 mAudioMixer->setParameter(
4227 name,
4228 AudioMixer::RESAMPLE,
4229 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004230 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004231
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004232 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004233 mAudioMixer->setParameter(
4234 name,
4235 AudioMixer::TIMESTRETCH,
4236 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004237 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004238
Andy Hung69aed5f2014-02-25 17:24:40 -08004239 /*
4240 * Select the appropriate output buffer for the track.
4241 *
Andy Hung98ef9782014-03-04 14:46:50 -08004242 * Tracks with effects go into their own effects chain buffer
4243 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004244 *
4245 * Other tracks can use mMixerBuffer for higher precision
4246 * channel accumulation. If this buffer is enabled
4247 * (mMixerBufferEnabled true), then selected tracks will accumulate
4248 * into it.
4249 *
4250 */
4251 if (mMixerBufferEnabled
4252 && (track->mainBuffer() == mSinkBuffer
4253 || track->mainBuffer() == mMixerBuffer)) {
4254 mAudioMixer->setParameter(
4255 name,
4256 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004257 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004258 mAudioMixer->setParameter(
4259 name,
4260 AudioMixer::TRACK,
4261 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4262 // TODO: override track->mainBuffer()?
4263 mMixerBufferValid = true;
4264 } else {
4265 mAudioMixer->setParameter(
4266 name,
4267 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004268 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004269 mAudioMixer->setParameter(
4270 name,
4271 AudioMixer::TRACK,
4272 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4273 }
Eric Laurent81784c32012-11-19 14:55:58 -08004274 mAudioMixer->setParameter(
4275 name,
4276 AudioMixer::TRACK,
4277 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4278
4279 // reset retry count
4280 track->mRetryCount = kMaxTrackRetries;
4281
4282 // If one track is ready, set the mixer ready if:
4283 // - the mixer was not ready during previous round OR
4284 // - no other track is not ready
4285 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4286 mixerStatus != MIXER_TRACKS_ENABLED) {
4287 mixerStatus = MIXER_TRACKS_READY;
4288 }
4289 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004290 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hung08fb1742015-05-31 23:22:10 -07004291 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)",
4292 track, framesReady, desiredFrames);
Glenn Kasten82aaf942013-07-17 16:05:07 -07004293 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08004294 } else {
4295 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004296 }
Phil Burk2812d9e2016-01-04 10:34:30 -08004297
Eric Laurent81784c32012-11-19 14:55:58 -08004298 // clear effect chain input buffer if an active track underruns to avoid sending
4299 // previous audio buffer again to effects
4300 chain = getEffectChain_l(track->sessionId());
4301 if (chain != 0) {
4302 chain->clearInputBuffer();
4303 }
4304
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004305 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004306 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4307 track->isStopped() || track->isPaused()) {
4308 // We have consumed all the buffers of this track.
4309 // Remove it from the list of active tracks.
4310 // TODO: use actual buffer filling status instead of latency when available from
4311 // audio HAL
4312 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004313 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004314 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4315 if (track->isStopped()) {
4316 track->reset();
4317 }
4318 tracksToRemove->add(track);
4319 }
4320 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004321 // No buffers for this track. Give it a few chances to
4322 // fill a buffer, then remove it from active list.
4323 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004324 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004325 tracksToRemove->add(track);
4326 // indicate to client process that the track was disabled because of underrun;
4327 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004328 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004329 // If one track is not ready, mark the mixer also not ready if:
4330 // - the mixer was ready during previous round OR
4331 // - no other track is ready
4332 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4333 mixerStatus != MIXER_TRACKS_READY) {
4334 mixerStatus = MIXER_TRACKS_ENABLED;
4335 }
4336 }
4337 mAudioMixer->disable(name);
4338 }
4339
4340 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08004341
4342 }
4343
4344 // Push the new FastMixer state if necessary
4345 bool pauseAudioWatchdog = false;
4346 if (didModify) {
4347 state->mFastTracksGen++;
4348 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4349 if (kUseFastMixer == FastMixer_Dynamic &&
4350 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4351 state->mCommand = FastMixerState::COLD_IDLE;
4352 state->mColdFutexAddr = &mFastMixerFutex;
4353 state->mColdGen++;
4354 mFastMixerFutex = 0;
4355 if (kUseFastMixer == FastMixer_Dynamic) {
4356 mNormalSink = mOutputSink;
4357 }
4358 // If we go into cold idle, need to wait for acknowledgement
4359 // so that fast mixer stops doing I/O.
4360 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4361 pauseAudioWatchdog = true;
4362 }
Eric Laurent81784c32012-11-19 14:55:58 -08004363 }
4364 if (sq != NULL) {
4365 sq->end(didModify);
4366 sq->push(block);
4367 }
4368#ifdef AUDIO_WATCHDOG
4369 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4370 mAudioWatchdog->pause();
4371 }
4372#endif
4373
4374 // Now perform the deferred reset on fast tracks that have stopped
4375 while (resetMask != 0) {
4376 size_t i = __builtin_ctz(resetMask);
4377 ALOG_ASSERT(i < count);
4378 resetMask &= ~(1 << i);
4379 sp<Track> t = mActiveTracks[i].promote();
4380 if (t == 0) {
4381 continue;
4382 }
4383 Track* track = t.get();
4384 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4385 track->reset();
4386 }
4387
4388 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004389 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004390
Eric Laurent97d547d2014-09-02 14:45:53 -07004391 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4392 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004393 }
4394
4395 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004396 // as long as there are effects we should clear the effects buffer, to avoid
4397 // passing a non-clean buffer to the effect chain
4398 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004399 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004400 // sink or mix buffer must be cleared if all tracks are connected to an
4401 // effect chain as in this case the mixer will not write to the sink or mix buffer
4402 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004403 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4404 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004405 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004406 if (mMixerBufferValid) {
4407 memset(mMixerBuffer, 0, mMixerBufferSize);
4408 // TODO: In testing, mSinkBuffer below need not be cleared because
4409 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4410 // after mixing.
4411 //
4412 // To enforce this guarantee:
4413 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4414 // (mixedTracks == 0 && fastTracks > 0))
4415 // must imply MIXER_TRACKS_READY.
4416 // Later, we may clear buffers regardless, and skip much of this logic.
4417 }
Andy Hung98ef9782014-03-04 14:46:50 -08004418 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004419 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004420 }
4421
4422 // if any fast tracks, then status is ready
4423 mMixerStatusIgnoringFastTracks = mixerStatus;
4424 if (fastTracks > 0) {
4425 mixerStatus = MIXER_TRACKS_READY;
4426 }
4427 return mixerStatus;
4428}
4429
4430// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07004431int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
Glenn Kastend848eb42016-03-08 13:42:11 -08004432 audio_format_t format, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08004433{
Andy Hunge8a1ced2014-05-09 15:02:21 -07004434 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08004435}
4436
4437// deleteTrackName_l() must be called with ThreadBase::mLock held
4438void AudioFlinger::MixerThread::deleteTrackName_l(int name)
4439{
4440 ALOGV("remove track (%d) and delete from mixer", name);
4441 mAudioMixer->deleteTrackName(name);
4442}
4443
Eric Laurent10351942014-05-08 18:49:52 -07004444// checkForNewParameter_l() must be called with ThreadBase::mLock held
4445bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4446 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004447{
Eric Laurent81784c32012-11-19 14:55:58 -08004448 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08004449 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004450
Eric Laurent10351942014-05-08 18:49:52 -07004451 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004452
Eric Laurent10351942014-05-08 18:49:52 -07004453 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
4454 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004455 if (mFastMixer != 0) {
Eric Laurent10351942014-05-08 18:49:52 -07004456 FastMixerStateQueue *sq = mFastMixer->sq();
4457 FastMixerState *state = sq->begin();
4458 if (!(state->mCommand & FastMixerState::IDLE)) {
4459 previousCommand = state->mCommand;
4460 state->mCommand = FastMixerState::HOT_IDLE;
4461 sq->end();
4462 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
4463 } else {
4464 sq->end(false /*didModify*/);
Eric Laurent81784c32012-11-19 14:55:58 -08004465 }
Eric Laurent10351942014-05-08 18:49:52 -07004466 }
Eric Laurent81784c32012-11-19 14:55:58 -08004467
Eric Laurent10351942014-05-08 18:49:52 -07004468 AudioParameter param = AudioParameter(keyValuePair);
4469 int value;
4470 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4471 reconfig = true;
4472 }
4473 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004474 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004475 status = BAD_VALUE;
4476 } else {
4477 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004478 reconfig = true;
4479 }
Eric Laurent10351942014-05-08 18:49:52 -07004480 }
4481 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004482 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004483 status = BAD_VALUE;
4484 } else {
4485 // no need to save value, since it's constant
4486 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004487 }
Eric Laurent10351942014-05-08 18:49:52 -07004488 }
4489 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4490 // do not accept frame count changes if tracks are open as the track buffer
4491 // size depends on frame count and correct behavior would not be guaranteed
4492 // if frame count is changed after track creation
4493 if (!mTracks.isEmpty()) {
4494 status = INVALID_OPERATION;
4495 } else {
4496 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004497 }
Eric Laurent10351942014-05-08 18:49:52 -07004498 }
4499 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004500#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004501 // when changing the audio output device, call addBatteryData to notify
4502 // the change
4503 if (mOutDevice != value) {
4504 uint32_t params = 0;
4505 // check whether speaker is on
4506 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4507 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004508 }
Eric Laurent10351942014-05-08 18:49:52 -07004509
4510 audio_devices_t deviceWithoutSpeaker
4511 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4512 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07004513 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07004514 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4515 }
4516
4517 if (params != 0) {
4518 addBatteryData(params);
4519 }
4520 }
Eric Laurent81784c32012-11-19 14:55:58 -08004521#endif
4522
Eric Laurent10351942014-05-08 18:49:52 -07004523 // forward device change to effects that have requested to be
4524 // aware of attached audio device.
4525 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08004526 a2dpDeviceChanged =
4527 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07004528 mOutDevice = value;
4529 for (size_t i = 0; i < mEffectChains.size(); i++) {
4530 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004531 }
4532 }
Eric Laurent10351942014-05-08 18:49:52 -07004533 }
Eric Laurent81784c32012-11-19 14:55:58 -08004534
Eric Laurent10351942014-05-08 18:49:52 -07004535 if (status == NO_ERROR) {
4536 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4537 keyValuePair.string());
4538 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004539 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004540 mStandby = true;
4541 mBytesWritten = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004542 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Eric Laurent10351942014-05-08 18:49:52 -07004543 keyValuePair.string());
Eric Laurent81784c32012-11-19 14:55:58 -08004544 }
Eric Laurent10351942014-05-08 18:49:52 -07004545 if (status == NO_ERROR && reconfig) {
4546 readOutputParameters_l();
4547 delete mAudioMixer;
4548 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4549 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004550 int name = getTrackName_l(mTracks[i]->mChannelMask,
4551 mTracks[i]->mFormat, mTracks[i]->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07004552 if (name < 0) {
4553 break;
4554 }
4555 mTracks[i]->mName = name;
4556 }
Eric Laurent73e26b62015-04-27 16:55:58 -07004557 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004558 }
Eric Laurent81784c32012-11-19 14:55:58 -08004559 }
4560
4561 if (!(previousCommand & FastMixerState::IDLE)) {
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004562 ALOG_ASSERT(mFastMixer != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004563 FastMixerStateQueue *sq = mFastMixer->sq();
4564 FastMixerState *state = sq->begin();
4565 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
4566 state->mCommand = previousCommand;
4567 sq->end();
4568 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4569 }
4570
Eric Laurent42537be2016-01-08 17:16:42 -08004571 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08004572}
4573
4574
4575void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4576{
Eric Laurent81784c32012-11-19 14:55:58 -08004577 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07004578 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Elliott Hughes87cebad2014-05-22 10:14:43 -07004579 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Andy Hung2ddee192015-12-18 17:34:44 -08004580 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent81784c32012-11-19 14:55:58 -08004581
4582 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten2f90c512015-12-02 11:40:09 -08004583 // while we are dumping it. It may be inconsistent, but it won't mutate!
4584 // This is a large object so we place it on the heap.
4585 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
4586 const FastMixerDumpState *copy = new FastMixerDumpState(mFastMixerDumpState);
4587 copy->dump(fd);
4588 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08004589
4590#ifdef STATE_QUEUE_DUMP
4591 // Similar for state queue
4592 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4593 observerCopy.dump(fd);
4594 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4595 mutatorCopy.dump(fd);
4596#endif
4597
Glenn Kasten46909e72013-02-26 09:20:22 -08004598#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004599 // Write the tee output to a .wav file
4600 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08004601#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004602
4603#ifdef AUDIO_WATCHDOG
4604 if (mAudioWatchdog != 0) {
4605 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4606 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4607 wdCopy.dump(fd);
4608 }
4609#endif
4610}
4611
4612uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4613{
4614 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4615}
4616
4617uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4618{
4619 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4620}
4621
4622void AudioFlinger::MixerThread::cacheParameters_l()
4623{
4624 PlaybackThread::cacheParameters_l();
4625
4626 // FIXME: Relaxed timing because of a certain device that can't meet latency
4627 // Should be reduced to 2x after the vendor fixes the driver issue
4628 // increase threshold again due to low power audio mode. The way this warning
4629 // threshold is calculated and its usefulness should be reconsidered anyway.
4630 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4631}
4632
4633// ----------------------------------------------------------------------------
4634
4635AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent51716182016-02-29 18:00:56 -08004636 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady,
4637 uint32_t bitRate)
4638 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady, bitRate)
Eric Laurent81784c32012-11-19 14:55:58 -08004639 // mLeftVolFloat, mRightVolFloat
4640{
4641}
4642
Eric Laurentbfb1b832013-01-07 09:53:42 -08004643AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4644 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurent51716182016-02-29 18:00:56 -08004645 ThreadBase::type_t type, bool systemReady, uint32_t bitRate)
4646 : PlaybackThread(audioFlinger, output, id, device, type, systemReady, bitRate)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004647 // mLeftVolFloat, mRightVolFloat
4648{
4649}
4650
Eric Laurent81784c32012-11-19 14:55:58 -08004651AudioFlinger::DirectOutputThread::~DirectOutputThread()
4652{
4653}
4654
Eric Laurentbfb1b832013-01-07 09:53:42 -08004655void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
4656{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004657 float left, right;
4658
4659 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4660 left = right = 0;
4661 } else {
4662 float typeVolume = mStreamTypes[track->streamType()].volume;
4663 float v = mMasterVolume * typeVolume;
4664 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004665 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4666 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4667 if (left > GAIN_FLOAT_UNITY) {
4668 left = GAIN_FLOAT_UNITY;
4669 }
4670 left *= v;
4671 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4672 if (right > GAIN_FLOAT_UNITY) {
4673 right = GAIN_FLOAT_UNITY;
4674 }
4675 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004676 }
4677
4678 if (lastTrack) {
4679 if (left != mLeftVolFloat || right != mRightVolFloat) {
4680 mLeftVolFloat = left;
4681 mRightVolFloat = right;
4682
4683 // Convert volumes from float to 8.24
4684 uint32_t vl = (uint32_t)(left * (1 << 24));
4685 uint32_t vr = (uint32_t)(right * (1 << 24));
4686
4687 // Delegate volume control to effect in track effect chain if needed
4688 // only one effect chain can be present on DirectOutputThread, so if
4689 // there is one, the track is connected to it
4690 if (!mEffectChains.isEmpty()) {
4691 mEffectChains[0]->setVolume_l(&vl, &vr);
4692 left = (float)vl / (1 << 24);
4693 right = (float)vr / (1 << 24);
4694 }
4695 if (mOutput->stream->set_volume) {
4696 mOutput->stream->set_volume(mOutput->stream, left, right);
4697 }
4698 }
4699 }
4700}
4701
Phil Burk43b4dcc2015-06-09 16:53:44 -07004702void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
4703{
4704 sp<Track> previousTrack = mPreviousTrack.promote();
4705 sp<Track> latestTrack = mLatestActiveTrack.promote();
4706
Eric Laurent0f0631e2015-07-06 18:01:25 -07004707 if (previousTrack != 0 && latestTrack != 0) {
4708 if (mType == DIRECT) {
4709 if (previousTrack.get() != latestTrack.get()) {
4710 mFlushPending = true;
4711 }
4712 } else /* mType == OFFLOAD */ {
4713 if (previousTrack->sessionId() != latestTrack->sessionId()) {
4714 mFlushPending = true;
4715 }
4716 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004717 }
4718 PlaybackThread::onAddNewTrack_l();
4719}
Eric Laurentbfb1b832013-01-07 09:53:42 -08004720
Eric Laurent81784c32012-11-19 14:55:58 -08004721AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4722 Vector< sp<Track> > *tracksToRemove
4723)
4724{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004725 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004726 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004727 bool doHwPause = false;
4728 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004729
4730 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07004731 for (size_t i = 0; i < count; i++) {
4732 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08004733 // The track died recently
4734 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004735 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08004736 }
4737
Phil Burk43b4dcc2015-06-09 16:53:44 -07004738 if (t->isInvalid()) {
4739 ALOGW("An invalidated track shouldn't be in active list");
4740 tracksToRemove->add(t);
4741 continue;
4742 }
4743
Eric Laurent81784c32012-11-19 14:55:58 -08004744 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004745#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08004746 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004747#endif
Eric Laurentfd477972013-10-25 18:10:40 -07004748 // Only consider last track started for volume and mixer state control.
4749 // In theory an older track could underrun and restart after the new one starts
4750 // but as we only care about the transition phase between two tracks on a
4751 // direct output, it is not a problem to ignore the underrun case.
4752 sp<Track> l = mLatestActiveTrack.promote();
4753 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004754
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004755 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004756 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004757 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004758 doHwPause = true;
4759 mHwPaused = true;
4760 }
4761 tracksToRemove->add(track);
4762 } else if (track->isFlushPending()) {
4763 track->flushAck();
4764 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004765 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004766 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004767 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004768 track->resumeAck();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004769 if (last && mHwPaused) {
4770 doHwResume = true;
4771 mHwPaused = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004772 }
4773 }
4774
Eric Laurent81784c32012-11-19 14:55:58 -08004775 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004776 // for all its buffers to be filled before processing it.
4777 // Allow draining the buffer in case the client
4778 // app does not call stop() and relies on underrun to stop:
4779 // hence the test on (track->mRetryCount > 1).
4780 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07004781 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08004782 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004783 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08004784 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004785 minFrames = mNormalFrameCount;
4786 } else {
4787 minFrames = 1;
4788 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004789
Eric Laurentab5cdba2014-06-09 17:22:27 -07004790 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4791 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004792 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004793 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004794
4795 if (track->mFillingUpStatus == Track::FS_FILLED) {
4796 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004797 // make sure processVolume_l() will apply new volume even if 0
4798 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004799 if (!mHwSupportsPause) {
4800 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004801 }
4802 }
4803
4804 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004805 processVolume_l(track, last);
4806 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004807 sp<Track> previousTrack = mPreviousTrack.promote();
4808 if (previousTrack != 0) {
4809 if (track != previousTrack.get()) {
4810 // Flush any data still being written from last track
4811 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07004812 // Invalidate previous track to force a seek when resuming.
4813 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004814 }
4815 }
4816 mPreviousTrack = track;
4817
Eric Laurentd595b7c2013-04-03 17:27:56 -07004818 // reset retry count
4819 track->mRetryCount = kMaxTrackRetriesDirect;
4820 mActiveTrack = t;
4821 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07004822 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004823 doHwResume = true;
4824 mHwPaused = false;
4825 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004826 }
Eric Laurent81784c32012-11-19 14:55:58 -08004827 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004828 // clear effect chain input buffer if the last active track started underruns
4829 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004830 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004831 mEffectChains[0]->clearInputBuffer();
4832 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004833 if (track->isStopping_1()) {
4834 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07004835 if (last && mHwPaused) {
4836 doHwResume = true;
4837 mHwPaused = false;
4838 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004839 }
4840 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4841 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004842 // We have consumed all the buffers of this track.
4843 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004844 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08004845 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004846 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4847 } else {
4848 audioHALFrames = 0;
4849 }
4850
Andy Hung818e7a32016-02-16 18:08:07 -08004851 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004852 if (mStandby || !last ||
4853 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004854 if (track->isStopping_2()) {
4855 track->mState = TrackBase::STOPPED;
4856 }
Eric Laurent81784c32012-11-19 14:55:58 -08004857 if (track->isStopped()) {
4858 track->reset();
4859 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004860 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004861 }
4862 } else {
4863 // No buffers for this track. Give it a few chances to
4864 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004865 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004866 if (--(track->mRetryCount) <= 0) {
4867 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004868 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004869 // indicate to client process that the track was disabled because of underrun;
4870 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004871 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004872 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07004873 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
4874 "minFrames = %u, mFormat = %#x",
4875 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08004876 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07004877 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004878 doHwPause = true;
4879 mHwPaused = true;
4880 }
Eric Laurent81784c32012-11-19 14:55:58 -08004881 }
4882 }
4883 }
4884 }
4885
Eric Laurentd1f69b02014-12-15 14:33:13 -08004886 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07004887 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004888 for (size_t i = 0; i < mTracks.size(); i++) {
4889 if (mTracks[i]->isFlushPending()) {
4890 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004891 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004892 }
4893 }
4894 }
4895
4896 // make sure the pause/flush/resume sequence is executed in the right order.
4897 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4898 // before flush and then resume HW. This can happen in case of pause/flush/resume
4899 // if resume is received before pause is executed.
4900 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07004901 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004902 mOutput->stream->pause(mOutput->stream);
4903 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004904 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004905 flushHw_l();
4906 }
4907 if (mHwSupportsPause && !mStandby && doHwResume) {
4908 mOutput->stream->resume(mOutput->stream);
4909 }
Eric Laurent81784c32012-11-19 14:55:58 -08004910 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004911 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004912
4913 return mixerStatus;
4914}
4915
4916void AudioFlinger::DirectOutputThread::threadLoop_mix()
4917{
Eric Laurent81784c32012-11-19 14:55:58 -08004918 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08004919 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004920 // output audio to hardware
4921 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07004922 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004923 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08004924 status_t status = mActiveTrack->getNextBuffer(&buffer);
4925 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08004926 // no need to pad with 0 for compressed audio
4927 if (audio_has_proportional_frames(mFormat)) {
4928 memset(curBuf, 0, frameCount * mFrameSize);
4929 }
Eric Laurent81784c32012-11-19 14:55:58 -08004930 break;
4931 }
4932 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
4933 frameCount -= buffer.frameCount;
4934 curBuf += buffer.frameCount * mFrameSize;
4935 mActiveTrack->releaseBuffer(&buffer);
4936 }
Andy Hung2098f272014-02-27 14:00:06 -08004937 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004938 mSleepTimeUs = 0;
4939 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004940 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004941}
4942
4943void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
4944{
Eric Laurentd1f69b02014-12-15 14:33:13 -08004945 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004946 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004947 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004948 return;
4949 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004950 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004951 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurent51716182016-02-29 18:00:56 -08004952 // For compressed offload, use faster sleep time when underruning until more than an
4953 // entire buffer was written to the audio HAL
4954 if (!audio_has_proportional_frames(mFormat) &&
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004955 (mType == OFFLOAD) && (mBytesWritten < (int64_t) mBufferSize)) {
Eric Laurent51716182016-02-29 18:00:56 -08004956 mSleepTimeUs = kDirectMinSleepTimeUs;
4957 } else {
4958 mSleepTimeUs = mActiveSleepTimeUs;
4959 }
Eric Laurent81784c32012-11-19 14:55:58 -08004960 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004961 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004962 }
Phil Burkfdb3c072016-02-09 10:47:02 -08004963 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08004964 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004965 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004966 }
4967}
4968
Eric Laurentd1f69b02014-12-15 14:33:13 -08004969void AudioFlinger::DirectOutputThread::threadLoop_exit()
4970{
4971 {
4972 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08004973 for (size_t i = 0; i < mTracks.size(); i++) {
4974 if (mTracks[i]->isFlushPending()) {
4975 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004976 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004977 }
4978 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004979 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004980 flushHw_l();
4981 }
4982 }
4983 PlaybackThread::threadLoop_exit();
4984}
4985
4986// must be called with thread mutex locked
4987bool AudioFlinger::DirectOutputThread::shouldStandby_l()
4988{
4989 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07004990 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004991
vivek mehta9cd7ad12016-03-17 00:18:29 -07004992 if ((mType == DIRECT) && audio_is_linear_pcm(mFormat) && !usesHwAvSync()) {
4993 return !mStandby;
4994 }
4995
Eric Laurentd1f69b02014-12-15 14:33:13 -08004996 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4997 // after a timeout and we will enter standby then.
4998 if (mTracks.size() > 0) {
4999 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07005000 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
5001 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005002 }
5003
Eric Laurent5cff4032015-05-26 13:49:58 -07005004 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08005005}
5006
Eric Laurent81784c32012-11-19 14:55:58 -08005007// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005008int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Glenn Kastend848eb42016-03-08 13:42:11 -08005009 audio_format_t format __unused, audio_session_t sessionId __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005010{
5011 return 0;
5012}
5013
5014// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005015void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005016{
5017}
5018
Eric Laurent10351942014-05-08 18:49:52 -07005019// checkForNewParameter_l() must be called with ThreadBase::mLock held
5020bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
5021 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005022{
5023 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005024 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005025
Eric Laurent10351942014-05-08 18:49:52 -07005026 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005027
Eric Laurent10351942014-05-08 18:49:52 -07005028 AudioParameter param = AudioParameter(keyValuePair);
5029 int value;
5030 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5031 // forward device change to effects that have requested to be
5032 // aware of attached audio device.
5033 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005034 a2dpDeviceChanged =
5035 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005036 mOutDevice = value;
5037 for (size_t i = 0; i < mEffectChains.size(); i++) {
5038 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07005039 }
5040 }
Eric Laurent81784c32012-11-19 14:55:58 -08005041 }
Eric Laurent10351942014-05-08 18:49:52 -07005042 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5043 // do not accept frame count changes if tracks are open as the track buffer
5044 // size depends on frame count and correct behavior would not be garantied
5045 // if frame count is changed after track creation
5046 if (!mTracks.isEmpty()) {
5047 status = INVALID_OPERATION;
5048 } else {
5049 reconfig = true;
5050 }
5051 }
5052 if (status == NO_ERROR) {
5053 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
5054 keyValuePair.string());
5055 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005056 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005057 mStandby = true;
5058 mBytesWritten = 0;
5059 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
5060 keyValuePair.string());
5061 }
5062 if (status == NO_ERROR && reconfig) {
5063 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07005064 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005065 }
5066 }
5067
Eric Laurent42537be2016-01-08 17:16:42 -08005068 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005069}
5070
5071uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
5072{
5073 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005074 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005075 time = PlaybackThread::activeSleepTimeUs();
5076 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005077 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005078 }
5079 return time;
5080}
5081
5082uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
5083{
5084 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005085 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005086 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
5087 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005088 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005089 }
5090 return time;
5091}
5092
5093uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
5094{
5095 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005096 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005097 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
5098 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005099 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005100 }
5101 return time;
5102}
5103
5104void AudioFlinger::DirectOutputThread::cacheParameters_l()
5105{
5106 PlaybackThread::cacheParameters_l();
5107
5108 // use shorter standby delay as on normal output to release
5109 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07005110 // no delay on outputs with HW A/V sync
5111 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005112 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08005113 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005114 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07005115 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005116 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07005117 }
Eric Laurent81784c32012-11-19 14:55:58 -08005118}
5119
Eric Laurente659ef42014-09-29 13:06:46 -07005120void AudioFlinger::DirectOutputThread::flushHw_l()
5121{
Phil Burk062e67a2015-02-11 13:40:50 -08005122 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08005123 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005124 mFlushPending = false;
Eric Laurente659ef42014-09-29 13:06:46 -07005125}
5126
Eric Laurent81784c32012-11-19 14:55:58 -08005127// ----------------------------------------------------------------------------
5128
Eric Laurentbfb1b832013-01-07 09:53:42 -08005129AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07005130 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005131 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07005132 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07005133 mWriteAckSequence(0),
5134 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005135{
5136}
5137
5138AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
5139{
5140}
5141
5142void AudioFlinger::AsyncCallbackThread::onFirstRef()
5143{
5144 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
5145}
5146
5147bool AudioFlinger::AsyncCallbackThread::threadLoop()
5148{
5149 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005150 uint32_t writeAckSequence;
5151 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005152
5153 {
5154 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005155 while (!((mWriteAckSequence & 1) ||
5156 (mDrainSequence & 1) ||
5157 exitPending())) {
5158 mWaitWorkCV.wait(mLock);
5159 }
5160
Eric Laurentbfb1b832013-01-07 09:53:42 -08005161 if (exitPending()) {
5162 break;
5163 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005164 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
5165 mWriteAckSequence, mDrainSequence);
5166 writeAckSequence = mWriteAckSequence;
5167 mWriteAckSequence &= ~1;
5168 drainSequence = mDrainSequence;
5169 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005170 }
5171 {
Eric Laurent4de95592013-09-26 15:28:21 -07005172 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
5173 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005174 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005175 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005176 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005177 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005178 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005179 }
5180 }
5181 }
5182 }
5183 return false;
5184}
5185
5186void AudioFlinger::AsyncCallbackThread::exit()
5187{
5188 ALOGV("AsyncCallbackThread::exit");
5189 Mutex::Autolock _l(mLock);
5190 requestExit();
5191 mWaitWorkCV.broadcast();
5192}
5193
Eric Laurent3b4529e2013-09-05 18:09:19 -07005194void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005195{
5196 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005197 // bit 0 is cleared
5198 mWriteAckSequence = sequence << 1;
5199}
5200
5201void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5202{
5203 Mutex::Autolock _l(mLock);
5204 // ignore unexpected callbacks
5205 if (mWriteAckSequence & 2) {
5206 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005207 mWaitWorkCV.signal();
5208 }
5209}
5210
Eric Laurent3b4529e2013-09-05 18:09:19 -07005211void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005212{
5213 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005214 // bit 0 is cleared
5215 mDrainSequence = sequence << 1;
5216}
5217
5218void AudioFlinger::AsyncCallbackThread::resetDraining()
5219{
5220 Mutex::Autolock _l(mLock);
5221 // ignore unexpected callbacks
5222 if (mDrainSequence & 2) {
5223 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005224 mWaitWorkCV.signal();
5225 }
5226}
5227
5228
5229// ----------------------------------------------------------------------------
5230AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent51716182016-02-29 18:00:56 -08005231 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady,
5232 uint32_t bitRate)
5233 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady, bitRate),
Eric Laurentd7e59222013-11-15 12:02:28 -08005234 mPausedBytesRemaining(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005235{
Eric Laurentfd477972013-10-25 18:10:40 -07005236 //FIXME: mStandby should be set to true by ThreadBase constructor
5237 mStandby = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005238}
5239
Eric Laurentbfb1b832013-01-07 09:53:42 -08005240void AudioFlinger::OffloadThread::threadLoop_exit()
5241{
5242 if (mFlushPending || mHwPaused) {
5243 // If a flush is pending or track was paused, just discard buffered data
5244 flushHw_l();
5245 } else {
5246 mMixerStatus = MIXER_DRAIN_ALL;
5247 threadLoop_drain();
5248 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005249 if (mUseAsyncWrite) {
5250 ALOG_ASSERT(mCallbackThread != 0);
5251 mCallbackThread->exit();
5252 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005253 PlaybackThread::threadLoop_exit();
5254}
5255
5256AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5257 Vector< sp<Track> > *tracksToRemove
5258)
5259{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005260 size_t count = mActiveTracks.size();
5261
5262 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005263 bool doHwPause = false;
5264 bool doHwResume = false;
5265
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005266 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07005267
Eric Laurentbfb1b832013-01-07 09:53:42 -08005268 // find out which tracks need to be processed
5269 for (size_t i = 0; i < count; i++) {
5270 sp<Track> t = mActiveTracks[i].promote();
5271 // The track died recently
5272 if (t == 0) {
5273 continue;
5274 }
5275 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005276#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08005277 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005278#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005279 // Only consider last track started for volume and mixer state control.
5280 // In theory an older track could underrun and restart after the new one starts
5281 // but as we only care about the transition phase between two tracks on a
5282 // direct output, it is not a problem to ignore the underrun case.
5283 sp<Track> l = mLatestActiveTrack.promote();
5284 bool last = l.get() == track;
5285
Haynes Mathew George7844f672014-01-15 12:32:55 -08005286 if (track->isInvalid()) {
5287 ALOGW("An invalidated track shouldn't be in active list");
5288 tracksToRemove->add(track);
5289 continue;
5290 }
5291
5292 if (track->mState == TrackBase::IDLE) {
5293 ALOGW("An idle track shouldn't be in active list");
5294 continue;
5295 }
5296
Eric Laurentbfb1b832013-01-07 09:53:42 -08005297 if (track->isPausing()) {
5298 track->setPaused();
5299 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005300 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005301 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005302 mHwPaused = true;
5303 }
5304 // If we were part way through writing the mixbuffer to
5305 // the HAL we must save this until we resume
5306 // BUG - this will be wrong if a different track is made active,
5307 // in that case we want to discard the pending data in the
5308 // mixbuffer and tell the client to present it again when the
5309 // track is resumed
5310 mPausedWriteLength = mCurrentWriteLength;
5311 mPausedBytesRemaining = mBytesRemaining;
5312 mBytesRemaining = 0; // stop writing
5313 }
5314 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005315 } else if (track->isFlushPending()) {
Eric Laurent51716182016-02-29 18:00:56 -08005316 track->mRetryCount = kMaxTrackRetriesOffload;
Haynes Mathew George7844f672014-01-15 12:32:55 -08005317 track->flushAck();
5318 if (last) {
5319 mFlushPending = true;
5320 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005321 } else if (track->isResumePending()){
5322 track->resumeAck();
5323 if (last) {
5324 if (mPausedBytesRemaining) {
5325 // Need to continue write that was interrupted
5326 mCurrentWriteLength = mPausedWriteLength;
5327 mBytesRemaining = mPausedBytesRemaining;
5328 mPausedBytesRemaining = 0;
5329 }
5330 if (mHwPaused) {
5331 doHwResume = true;
5332 mHwPaused = false;
5333 // threadLoop_mix() will handle the case that we need to
5334 // resume an interrupted write
5335 }
5336 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005337 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005338
5339 // Do not handle new data in this iteration even if track->framesReady()
5340 mixerStatus = MIXER_TRACKS_ENABLED;
5341 }
5342 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005343 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005344 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005345 if (track->mFillingUpStatus == Track::FS_FILLED) {
5346 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07005347 // make sure processVolume_l() will apply new volume even if 0
5348 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005349 }
5350
5351 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005352 sp<Track> previousTrack = mPreviousTrack.promote();
5353 if (previousTrack != 0) {
5354 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005355 // Flush any data still being written from last track
5356 mBytesRemaining = 0;
5357 if (mPausedBytesRemaining) {
5358 // Last track was paused so we also need to flush saved
5359 // mixbuffer state and invalidate track so that it will
5360 // re-submit that unwritten data when it is next resumed
5361 mPausedBytesRemaining = 0;
5362 // Invalidate is a bit drastic - would be more efficient
5363 // to have a flag to tell client that some of the
5364 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005365 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005366 }
5367 // flush data already sent to the DSP if changing audio session as audio
5368 // comes from a different source. Also invalidate previous track to force a
5369 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005370 if (previousTrack->sessionId() != track->sessionId()) {
5371 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005372 }
5373 }
5374 }
5375 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005376 // reset retry count
5377 track->mRetryCount = kMaxTrackRetriesOffload;
5378 mActiveTrack = t;
5379 mixerStatus = MIXER_TRACKS_READY;
5380 }
5381 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005382 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005383 if (track->isStopping_1()) {
5384 // Hardware buffer can hold a large amount of audio so we must
5385 // wait for all current track's data to drain before we say
5386 // that the track is stopped.
5387 if (mBytesRemaining == 0) {
5388 // Only start draining when all data in mixbuffer
5389 // has been written
5390 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5391 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005392 // do not drain if no data was ever sent to HAL (mStandby == true)
5393 if (last && !mStandby) {
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005394 // do not modify drain sequence if we are already draining. This happens
5395 // when resuming from pause after drain.
5396 if ((mDrainSequence & 1) == 0) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005397 mSleepTimeUs = 0;
5398 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005399 mixerStatus = MIXER_DRAIN_TRACK;
5400 mDrainSequence += 2;
5401 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005402 if (mHwPaused) {
5403 // It is possible to move from PAUSED to STOPPING_1 without
5404 // a resume so we must ensure hardware is running
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005405 doHwResume = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005406 mHwPaused = false;
5407 }
5408 }
5409 }
5410 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005411 // Drain has completed or we are in standby, signal presentation complete
5412 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005413 track->mState = TrackBase::STOPPED;
5414 size_t audioHALFrames =
5415 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005416 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005417 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005418 track->presentationComplete(framesWritten, audioHALFrames);
5419 track->reset();
5420 tracksToRemove->add(track);
5421 }
5422 } else {
5423 // No buffers for this track. Give it a few chances to
5424 // fill a buffer, then remove it from active list.
5425 if (--(track->mRetryCount) <= 0) {
5426 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5427 track->name());
5428 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005429 // indicate to client process that the track was disabled because of underrun;
5430 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005431 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005432 } else if (last){
5433 mixerStatus = MIXER_TRACKS_ENABLED;
5434 }
5435 }
5436 }
5437 // compute volume for this track
5438 processVolume_l(track, last);
5439 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005440
Eric Laurentea0fade2013-10-04 16:23:48 -07005441 // make sure the pause/flush/resume sequence is executed in the right order.
5442 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5443 // before flush and then resume HW. This can happen in case of pause/flush/resume
5444 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07005445 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07005446 mOutput->stream->pause(mOutput->stream);
5447 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005448 if (mFlushPending) {
5449 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005450 }
Eric Laurentfd477972013-10-25 18:10:40 -07005451 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07005452 mOutput->stream->resume(mOutput->stream);
5453 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005454
Eric Laurentbfb1b832013-01-07 09:53:42 -08005455 // remove all the tracks that need to be...
5456 removeTracks_l(*tracksToRemove);
5457
5458 return mixerStatus;
5459}
5460
Eric Laurentbfb1b832013-01-07 09:53:42 -08005461// must be called with thread mutex locked
5462bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5463{
Eric Laurent3b4529e2013-09-05 18:09:19 -07005464 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5465 mWriteAckSequence, mDrainSequence);
5466 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005467 return true;
5468 }
5469 return false;
5470}
5471
Eric Laurentbfb1b832013-01-07 09:53:42 -08005472bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5473{
5474 Mutex::Autolock _l(mLock);
5475 return waitingAsyncCallback_l();
5476}
5477
5478void AudioFlinger::OffloadThread::flushHw_l()
5479{
Eric Laurente659ef42014-09-29 13:06:46 -07005480 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005481 // Flush anything still waiting in the mixbuffer
5482 mCurrentWriteLength = 0;
5483 mBytesRemaining = 0;
5484 mPausedWriteLength = 0;
5485 mPausedBytesRemaining = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08005486
Eric Laurentbfb1b832013-01-07 09:53:42 -08005487 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005488 // discard any pending drain or write ack by incrementing sequence
5489 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5490 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005491 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005492 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5493 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005494 }
5495}
5496
Eric Laurent51716182016-02-29 18:00:56 -08005497uint32_t AudioFlinger::OffloadThread::activeSleepTimeUs() const
5498{
5499 uint32_t time;
5500 if (audio_has_proportional_frames(mFormat)) {
5501 time = PlaybackThread::activeSleepTimeUs();
5502 } else {
5503 // sleep time is half the duration of an audio HAL buffer.
5504 // Note: This can be problematic in case of underrun with variable bit rate and
5505 // current rate is much less than initial rate.
5506 time = (uint32_t)max(kDirectMinSleepTimeUs, mBufferDurationUs / 2);
5507 }
5508 return time;
5509}
5510
Eric Laurentbfb1b832013-01-07 09:53:42 -08005511// ----------------------------------------------------------------------------
5512
Eric Laurent81784c32012-11-19 14:55:58 -08005513AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005514 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005515 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07005516 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08005517 mWaitTimeMs(UINT_MAX)
5518{
5519 addOutputTrack(mainThread);
5520}
5521
5522AudioFlinger::DuplicatingThread::~DuplicatingThread()
5523{
5524 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5525 mOutputTracks[i]->destroy();
5526 }
5527}
5528
5529void AudioFlinger::DuplicatingThread::threadLoop_mix()
5530{
5531 // mix buffers...
5532 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08005533 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08005534 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005535 if (mMixerBufferValid) {
5536 memset(mMixerBuffer, 0, mMixerBufferSize);
5537 } else {
5538 memset(mSinkBuffer, 0, mSinkBufferSize);
5539 }
Eric Laurent81784c32012-11-19 14:55:58 -08005540 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005541 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005542 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005543 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005544 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005545}
5546
5547void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5548{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005549 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005550 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005551 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005552 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005553 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005554 }
5555 } else if (mBytesWritten != 0) {
5556 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5557 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005558 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005559 } else {
5560 // flush remaining overflow buffers in output tracks
5561 writeFrames = 0;
5562 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005563 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005564 }
5565}
5566
Eric Laurentbfb1b832013-01-07 09:53:42 -08005567ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005568{
5569 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005570 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005571 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005572 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005573 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005574}
5575
5576void AudioFlinger::DuplicatingThread::threadLoop_standby()
5577{
5578 // DuplicatingThread implements standby by stopping all tracks
5579 for (size_t i = 0; i < outputTracks.size(); i++) {
5580 outputTracks[i]->stop();
5581 }
5582}
5583
5584void AudioFlinger::DuplicatingThread::saveOutputTracks()
5585{
5586 outputTracks = mOutputTracks;
5587}
5588
5589void AudioFlinger::DuplicatingThread::clearOutputTracks()
5590{
5591 outputTracks.clear();
5592}
5593
5594void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5595{
5596 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005597 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5598 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5599 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5600 const size_t frameCount =
5601 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5602 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5603 // from different OutputTracks and their associated MixerThreads (e.g. one may
5604 // nearly empty and the other may be dropping data).
5605
5606 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005607 this,
5608 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005609 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005610 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005611 frameCount,
5612 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08005613 if (outputTrack->cblk() != NULL) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005614 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
Eric Laurent81784c32012-11-19 14:55:58 -08005615 mOutputTracks.add(outputTrack);
Andy Hungc25b84a2015-01-14 19:04:10 -08005616 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005617 updateWaitTime_l();
5618 }
5619}
5620
5621void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5622{
5623 Mutex::Autolock _l(mLock);
5624 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5625 if (mOutputTracks[i]->thread() == thread) {
5626 mOutputTracks[i]->destroy();
5627 mOutputTracks.removeAt(i);
5628 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07005629 if (thread->getOutput() == mOutput) {
5630 mOutput = NULL;
5631 }
Eric Laurent81784c32012-11-19 14:55:58 -08005632 return;
5633 }
5634 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07005635 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005636}
5637
5638// caller must hold mLock
5639void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5640{
5641 mWaitTimeMs = UINT_MAX;
5642 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5643 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5644 if (strong != 0) {
5645 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5646 if (waitTimeMs < mWaitTimeMs) {
5647 mWaitTimeMs = waitTimeMs;
5648 }
5649 }
5650 }
5651}
5652
5653
5654bool AudioFlinger::DuplicatingThread::outputsReady(
5655 const SortedVector< sp<OutputTrack> > &outputTracks)
5656{
5657 for (size_t i = 0; i < outputTracks.size(); i++) {
5658 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5659 if (thread == 0) {
5660 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5661 outputTracks[i].get());
5662 return false;
5663 }
5664 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5665 // see note at standby() declaration
5666 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5667 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5668 thread.get());
5669 return false;
5670 }
5671 }
5672 return true;
5673}
5674
5675uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5676{
5677 return (mWaitTimeMs * 1000) / 2;
5678}
5679
5680void AudioFlinger::DuplicatingThread::cacheParameters_l()
5681{
5682 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5683 updateWaitTime_l();
5684
5685 MixerThread::cacheParameters_l();
5686}
5687
5688// ----------------------------------------------------------------------------
5689// Record
5690// ----------------------------------------------------------------------------
5691
5692AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5693 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005694 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005695 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07005696 audio_devices_t inDevice,
5697 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08005698#ifdef TEE_SINK
5699 , const sp<NBAIO_Sink>& teeSink
5700#endif
5701 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07005702 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005703 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005704 // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005705 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005706#ifdef TEE_SINK
5707 , mTeeSink(teeSink)
5708#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005709 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5710 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005711 // mFastCapture below
5712 , mFastCaptureFutex(0)
5713 // mInputSource
5714 // mPipeSink
5715 // mPipeSource
5716 , mPipeFramesP2(0)
5717 // mPipeMemory
5718 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005719 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005720{
Glenn Kastend7dca052015-03-05 16:05:54 -08005721 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5722 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08005723
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005724 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005725
5726 // create an NBAIO source for the HAL input stream, and negotiate
5727 mInputSource = new AudioStreamInSource(input->stream);
5728 size_t numCounterOffers = 0;
5729 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005730#if !LOG_NDEBUG
5731 ssize_t index =
5732#else
5733 (void)
5734#endif
5735 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005736 ALOG_ASSERT(index == 0);
5737
5738 // initialize fast capture depending on configuration
5739 bool initFastCapture;
5740 switch (kUseFastCapture) {
5741 case FastCapture_Never:
5742 initFastCapture = false;
5743 break;
5744 case FastCapture_Always:
5745 initFastCapture = true;
5746 break;
5747 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07005748 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005749 break;
5750 // case FastCapture_Dynamic:
5751 }
5752
5753 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07005754 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005755 NBAIO_Format format = mInputSource->format();
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005756 size_t pipeFramesP2 = roundup(mSampleRate / 25); // double-buffering of 20 ms each
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005757 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5758 void *pipeBuffer;
5759 const sp<MemoryDealer> roHeap(readOnlyHeap());
5760 sp<IMemory> pipeMemory;
5761 if ((roHeap == 0) ||
5762 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5763 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5764 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5765 goto failed;
5766 }
5767 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5768 memset(pipeBuffer, 0, pipeSize);
5769 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5770 const NBAIO_Format offers[1] = {format};
5771 size_t numCounterOffers = 0;
5772 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5773 ALOG_ASSERT(index == 0);
5774 mPipeSink = pipe;
5775 PipeReader *pipeReader = new PipeReader(*pipe);
5776 numCounterOffers = 0;
5777 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5778 ALOG_ASSERT(index == 0);
5779 mPipeSource = pipeReader;
5780 mPipeFramesP2 = pipeFramesP2;
5781 mPipeMemory = pipeMemory;
5782
5783 // create fast capture
5784 mFastCapture = new FastCapture();
5785 FastCaptureStateQueue *sq = mFastCapture->sq();
5786#ifdef STATE_QUEUE_DUMP
5787 // FIXME
5788#endif
5789 FastCaptureState *state = sq->begin();
5790 state->mCblk = NULL;
5791 state->mInputSource = mInputSource.get();
5792 state->mInputSourceGen++;
5793 state->mPipeSink = pipe;
5794 state->mPipeSinkGen++;
5795 state->mFrameCount = mFrameCount;
5796 state->mCommand = FastCaptureState::COLD_IDLE;
5797 // already done in constructor initialization list
5798 //mFastCaptureFutex = 0;
5799 state->mColdFutexAddr = &mFastCaptureFutex;
5800 state->mColdGen++;
5801 state->mDumpState = &mFastCaptureDumpState;
5802#ifdef TEE_SINK
5803 // FIXME
5804#endif
5805 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
5806 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
5807 sq->end();
5808 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5809
5810 // start the fast capture
5811 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
5812 pid_t tid = mFastCapture->getTid();
Glenn Kasten8379b722016-03-18 14:54:17 -07005813 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005814#ifdef AUDIO_WATCHDOG
5815 // FIXME
5816#endif
5817
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005818 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005819 }
5820failed: ;
5821
5822 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08005823}
5824
Eric Laurent81784c32012-11-19 14:55:58 -08005825AudioFlinger::RecordThread::~RecordThread()
5826{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005827 if (mFastCapture != 0) {
5828 FastCaptureStateQueue *sq = mFastCapture->sq();
5829 FastCaptureState *state = sq->begin();
5830 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5831 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5832 if (old == -1) {
5833 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5834 }
5835 }
5836 state->mCommand = FastCaptureState::EXIT;
5837 sq->end();
5838 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5839 mFastCapture->join();
5840 mFastCapture.clear();
5841 }
5842 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07005843 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07005844 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08005845}
5846
5847void AudioFlinger::RecordThread::onFirstRef()
5848{
Glenn Kastend7dca052015-03-05 16:05:54 -08005849 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08005850}
5851
Eric Laurent81784c32012-11-19 14:55:58 -08005852bool AudioFlinger::RecordThread::threadLoop()
5853{
Eric Laurent81784c32012-11-19 14:55:58 -08005854 nsecs_t lastWarning = 0;
5855
5856 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08005857
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005858reacquire_wakelock:
5859 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08005860 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005861 {
5862 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005863 size_t size = mActiveTracks.size();
5864 activeTracksGen = mActiveTracksGen;
5865 if (size > 0) {
5866 // FIXME an arbitrary choice
5867 activeTrack = mActiveTracks[0];
5868 acquireWakeLock_l(activeTrack->uid());
5869 if (size > 1) {
5870 SortedVector<int> tmp;
5871 for (size_t i = 0; i < size; i++) {
5872 tmp.add(mActiveTracks[i]->uid());
5873 }
5874 updateWakeLockUids_l(tmp);
5875 }
5876 } else {
5877 acquireWakeLock_l(-1);
5878 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005879 }
5880
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005881 // used to request a deferred sleep, to be executed later while mutex is unlocked
5882 uint32_t sleepUs = 0;
5883
5884 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005885 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005886 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07005887
Glenn Kasten5edadd42013-08-14 16:30:49 -07005888 // sleep with mutex unlocked
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005889 if (sleepUs > 0) {
Glenn Kastene7754022014-10-31 12:11:26 -07005890 ATRACE_BEGIN("sleep");
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005891 usleep(sleepUs);
Glenn Kastene7754022014-10-31 12:11:26 -07005892 ATRACE_END();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005893 sleepUs = 0;
Glenn Kasten5edadd42013-08-14 16:30:49 -07005894 }
5895
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005896 // activeTracks accumulates a copy of a subset of mActiveTracks
5897 Vector< sp<RecordTrack> > activeTracks;
5898
Glenn Kasten735f45f2014-08-18 15:51:59 -07005899 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005900 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07005901
Glenn Kasten735f45f2014-08-18 15:51:59 -07005902 // reference to a fast track which is about to be removed
5903 sp<RecordTrack> fastTrackToRemove;
5904
Eric Laurent81784c32012-11-19 14:55:58 -08005905 { // scope for mLock
5906 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08005907
Eric Laurent021cf962014-05-13 10:18:14 -07005908 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005909
Eric Laurent000a4192014-01-29 15:17:32 -08005910 // check exitPending here because checkForNewParameters_l() and
5911 // checkForNewParameters_l() can temporarily release mLock
5912 if (exitPending()) {
5913 break;
5914 }
5915
Glenn Kasten2b806402013-11-20 16:37:38 -08005916 // if no active track(s), then standby and release wakelock
5917 size_t size = mActiveTracks.size();
5918 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07005919 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005920 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08005921 releaseWakeLock_l();
5922 ALOGV("RecordThread: loop stopping");
5923 // go to sleep
5924 mWaitWorkCV.wait(mLock);
5925 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005926 goto reacquire_wakelock;
5927 }
5928
Glenn Kasten2b806402013-11-20 16:37:38 -08005929 if (mActiveTracksGen != activeTracksGen) {
5930 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005931 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08005932 for (size_t i = 0; i < size; i++) {
5933 tmp.add(mActiveTracks[i]->uid());
5934 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005935 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08005936 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005937
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005938 bool doBroadcast = false;
5939 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07005940
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005941 activeTrack = mActiveTracks[i];
5942 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07005943 if (activeTrack->isFastTrack()) {
5944 ALOG_ASSERT(fastTrackToRemove == 0);
5945 fastTrackToRemove = activeTrack;
5946 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005947 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08005948 mActiveTracks.remove(activeTrack);
5949 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005950 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07005951 continue;
5952 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005953
5954 TrackBase::track_state activeTrackState = activeTrack->mState;
5955 switch (activeTrackState) {
5956
5957 case TrackBase::PAUSING:
5958 mActiveTracks.remove(activeTrack);
5959 mActiveTracksGen++;
5960 doBroadcast = true;
5961 size--;
5962 continue;
5963
5964 case TrackBase::STARTING_1:
5965 sleepUs = 10000;
5966 i++;
5967 continue;
5968
5969 case TrackBase::STARTING_2:
5970 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005971 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07005972 activeTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005973 break;
5974
5975 case TrackBase::ACTIVE:
5976 break;
5977
5978 case TrackBase::IDLE:
5979 i++;
5980 continue;
5981
5982 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08005983 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07005984 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005985
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005986 activeTracks.add(activeTrack);
5987 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07005988
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005989 if (activeTrack->isFastTrack()) {
5990 ALOG_ASSERT(!mFastTrackAvail);
5991 ALOG_ASSERT(fastTrack == 0);
5992 fastTrack = activeTrack;
5993 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005994 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005995 if (doBroadcast) {
5996 mStartStopCond.broadcast();
5997 }
5998
5999 // sleep if there are no active tracks to process
6000 if (activeTracks.size() == 0) {
6001 if (sleepUs == 0) {
6002 sleepUs = kRecordThreadSleepUs;
6003 }
6004 continue;
6005 }
6006 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07006007
Eric Laurent81784c32012-11-19 14:55:58 -08006008 lockEffectChains_l(effectChains);
6009 }
6010
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006011 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07006012
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006013 size_t size = effectChains.size();
6014 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006015 // thread mutex is not locked, but effect chain is locked
6016 effectChains[i]->process_l();
6017 }
6018
Glenn Kasten735f45f2014-08-18 15:51:59 -07006019 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006020 if (mFastCapture != 0) {
6021 FastCaptureStateQueue *sq = mFastCapture->sq();
6022 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07006023 bool didModify = false;
6024 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006025 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
6026 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
6027 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6028 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6029 if (old == -1) {
6030 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6031 }
6032 }
6033 state->mCommand = FastCaptureState::READ_WRITE;
6034#if 0 // FIXME
6035 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08006036 FastThreadDumpState::kSamplingNforLowRamDevice :
6037 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006038#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07006039 didModify = true;
6040 }
6041 audio_track_cblk_t *cblkOld = state->mCblk;
6042 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
6043 if (cblkNew != cblkOld) {
6044 state->mCblk = cblkNew;
6045 // block until acked if removing a fast track
6046 if (cblkOld != NULL) {
6047 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
6048 }
6049 didModify = true;
6050 }
6051 sq->end(didModify);
6052 if (didModify) {
6053 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006054#if 0
6055 if (kUseFastCapture == FastCapture_Dynamic) {
6056 mNormalSource = mPipeSource;
6057 }
6058#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006059 }
6060 }
6061
Glenn Kasten735f45f2014-08-18 15:51:59 -07006062 // now run the fast track destructor with thread mutex unlocked
6063 fastTrackToRemove.clear();
6064
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006065 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
6066 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
6067 // slow, then this RecordThread will overrun by not calling HAL read often enough.
6068 // If destination is non-contiguous, first read past the nominal end of buffer, then
6069 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006070
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006071 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006072 ssize_t framesRead;
6073
6074 // If an NBAIO source is present, use it to read the normal capture's data
6075 if (mPipeSource != 0) {
6076 size_t framesToRead = mBufferSize / mFrameSize;
Andy Hung57446612015-04-19 23:56:46 -07006077 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
Glenn Kastend79072e2016-01-06 08:41:20 -08006078 framesToRead);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006079 if (framesRead == 0) {
6080 // since pipe is non-blocking, simulate blocking input
6081 sleepUs = (framesToRead * 1000000LL) / mSampleRate;
6082 }
6083 // otherwise use the HAL / AudioStreamIn directly
6084 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07006085 ATRACE_BEGIN("read");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006086 ssize_t bytesRead = mInput->stream->read(mInput->stream,
Andy Hung57446612015-04-19 23:56:46 -07006087 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize);
Glenn Kastenec6a7032016-03-14 07:40:23 -07006088 ATRACE_END();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006089 if (bytesRead < 0) {
6090 framesRead = bytesRead;
6091 } else {
6092 framesRead = bytesRead / mFrameSize;
6093 }
6094 }
6095
Andy Hung3f0c9022016-01-15 17:49:46 -08006096 // Update server timestamp with server stats
6097 // systemTime() is optional if the hardware supports timestamps.
6098 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
6099 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6100
6101 // Update server timestamp with kernel stats
6102 if (mInput->stream->get_capture_position != nullptr) {
6103 int64_t position, time;
6104 int ret = mInput->stream->get_capture_position(mInput->stream, &position, &time);
6105 if (ret == NO_ERROR) {
6106 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
6107 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
6108 // Note: In general record buffers should tend to be empty in
6109 // a properly running pipeline.
6110 //
6111 // Also, it is not advantageous to call get_presentation_position during the read
6112 // as the read obtains a lock, preventing the timestamp call from executing.
6113 }
6114 }
6115 // Use this to track timestamp information
6116 // ALOGD("%s", mTimestamp.toString().c_str());
6117
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006118 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006119 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006120 // Force input into standby so that it tries to recover at next read attempt
6121 inputStandBy();
6122 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006123 }
6124 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006125 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006126 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006127 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006128
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006129 if (mTeeSink != 0) {
Andy Hung57446612015-04-19 23:56:46 -07006130 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006131 }
6132 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006133 {
6134 size_t part1 = mRsmpInFramesP2 - rear;
6135 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07006136 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006137 (framesRead - part1) * mFrameSize);
6138 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006139 }
6140 rear = mRsmpInRear += framesRead;
6141
6142 size = activeTracks.size();
6143 // loop over each active track
6144 for (size_t i = 0; i < size; i++) {
6145 activeTrack = activeTracks[i];
6146
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006147 // skip fast tracks, as those are handled directly by FastCapture
6148 if (activeTrack->isFastTrack()) {
6149 continue;
6150 }
6151
Andy Hung73c02e42015-03-29 01:13:58 -07006152 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07006153 // TODO: Update the activeTrack buffer converter in case of reconfigure.
6154
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006155 enum {
6156 OVERRUN_UNKNOWN,
6157 OVERRUN_TRUE,
6158 OVERRUN_FALSE
6159 } overrun = OVERRUN_UNKNOWN;
6160
6161 // loop over getNextBuffer to handle circular sink
6162 for (;;) {
6163
6164 activeTrack->mSink.frameCount = ~0;
6165 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
6166 size_t framesOut = activeTrack->mSink.frameCount;
6167 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
6168
Andy Hung73c02e42015-03-29 01:13:58 -07006169 // check available frames and handle overrun conditions
6170 // if the record track isn't draining fast enough.
6171 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006172 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07006173 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
6174 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006175 overrun = OVERRUN_TRUE;
6176 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006177 if (framesOut == 0 || framesIn == 0) {
6178 break;
6179 }
6180
Andy Hung6770c6f2015-04-07 13:43:36 -07006181 // Don't allow framesOut to be larger than what is possible with resampling
6182 // from framesIn.
6183 // This isn't strictly necessary but helps limit buffer resizing in
6184 // RecordBufferConverter. TODO: remove when no longer needed.
6185 framesOut = min(framesOut,
6186 destinationFramesPossible(
6187 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07006188 // process frames from the RecordThread buffer provider to the RecordTrack buffer
6189 framesOut = activeTrack->mRecordBufferConverter->convert(
6190 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006191
6192 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
6193 overrun = OVERRUN_FALSE;
6194 }
6195
6196 if (activeTrack->mFramesToDrop == 0) {
6197 if (framesOut > 0) {
6198 activeTrack->mSink.frameCount = framesOut;
6199 activeTrack->releaseBuffer(&activeTrack->mSink);
6200 }
6201 } else {
6202 // FIXME could do a partial drop of framesOut
6203 if (activeTrack->mFramesToDrop > 0) {
6204 activeTrack->mFramesToDrop -= framesOut;
6205 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006206 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006207 }
6208 } else {
6209 activeTrack->mFramesToDrop += framesOut;
6210 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
6211 activeTrack->mSyncStartEvent->isCancelled()) {
6212 ALOGW("Synced record %s, session %d, trigger session %d",
6213 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
6214 activeTrack->sessionId(),
6215 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08006216 activeTrack->mSyncStartEvent->triggerSession() :
6217 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006218 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006219 }
6220 }
6221 }
6222
6223 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006224 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006225 }
6226 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006227
6228 switch (overrun) {
6229 case OVERRUN_TRUE:
6230 // client isn't retrieving buffers fast enough
6231 if (!activeTrack->setOverflow()) {
6232 nsecs_t now = systemTime();
6233 // FIXME should lastWarning per track?
6234 if ((now - lastWarning) > kWarningThrottleNs) {
6235 ALOGW("RecordThread: buffer overflow");
6236 lastWarning = now;
6237 }
6238 }
6239 break;
6240 case OVERRUN_FALSE:
6241 activeTrack->clearOverflow();
6242 break;
6243 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006244 break;
6245 }
6246
Andy Hung3f0c9022016-01-15 17:49:46 -08006247 // update frame information and push timestamp out
6248 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08006249 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08006250 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
6251 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006252 }
6253
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006254unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08006255 // enable changes in effect chain
6256 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006257 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08006258 }
6259
Glenn Kasten93e471f2013-08-19 08:40:07 -07006260 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08006261
6262 {
6263 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07006264 for (size_t i = 0; i < mTracks.size(); i++) {
6265 sp<RecordTrack> track = mTracks[i];
6266 track->invalidate();
6267 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006268 mActiveTracks.clear();
6269 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08006270 mStartStopCond.broadcast();
6271 }
6272
6273 releaseWakeLock();
6274
6275 ALOGV("RecordThread %p exiting", this);
6276 return false;
6277}
6278
Glenn Kasten93e471f2013-08-19 08:40:07 -07006279void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08006280{
6281 if (!mStandby) {
6282 inputStandBy();
6283 mStandby = true;
6284 }
6285}
6286
6287void AudioFlinger::RecordThread::inputStandBy()
6288{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006289 // Idle the fast capture if it's currently running
6290 if (mFastCapture != 0) {
6291 FastCaptureStateQueue *sq = mFastCapture->sq();
6292 FastCaptureState *state = sq->begin();
6293 if (!(state->mCommand & FastCaptureState::IDLE)) {
6294 state->mCommand = FastCaptureState::COLD_IDLE;
6295 state->mColdFutexAddr = &mFastCaptureFutex;
6296 state->mColdGen++;
6297 mFastCaptureFutex = 0;
6298 sq->end();
6299 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
6300 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
6301#if 0
6302 if (kUseFastCapture == FastCapture_Dynamic) {
6303 // FIXME
6304 }
6305#endif
6306#ifdef AUDIO_WATCHDOG
6307 // FIXME
6308#endif
6309 } else {
6310 sq->end(false /*didModify*/);
6311 }
6312 }
Eric Laurent81784c32012-11-19 14:55:58 -08006313 mInput->stream->common.standby(&mInput->stream->common);
6314}
6315
Glenn Kasten05997e22014-03-13 15:08:33 -07006316// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07006317sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08006318 const sp<AudioFlinger::Client>& client,
6319 uint32_t sampleRate,
6320 audio_format_t format,
6321 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08006322 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08006323 audio_session_t sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07006324 size_t *notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006325 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07006326 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08006327 pid_t tid,
6328 status_t *status)
6329{
Glenn Kasten74935e42013-12-19 08:56:45 -08006330 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08006331 sp<RecordTrack> track;
6332 status_t lStatus;
6333
Glenn Kasten90e58b12013-07-31 16:16:02 -07006334 // client expresses a preference for FAST, but we get the final say
6335 if (*flags & IAudioFlinger::TRACK_FAST) {
6336 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07006337 // we formerly checked for a callback handler (non-0 tid),
6338 // but that is no longer required for TRANSFER_OBTAIN mode
6339 //
Glenn Kasten74105912014-07-03 12:28:53 -07006340 // frame count is not specified, or is exactly the pipe depth
6341 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006342 // PCM data
6343 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006344 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006345 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006346 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006347 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006348 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07006349 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006350 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006351 hasFastCapture() &&
6352 // there are sufficient fast track slots available
6353 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07006354 ) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006355 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
Glenn Kasten90e58b12013-07-31 16:16:02 -07006356 frameCount, mFrameCount);
6357 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006358 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
Glenn Kasten74105912014-07-03 12:28:53 -07006359 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006360 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07006361 frameCount, mFrameCount, mPipeFramesP2,
6362 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
6363 hasFastCapture(), tid, mFastTrackAvail);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006364 *flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kasten74105912014-07-03 12:28:53 -07006365 }
6366 }
6367
6368 // compute track buffer size in frames, and suggest the notification frame count
6369 if (*flags & IAudioFlinger::TRACK_FAST) {
6370 // fast track: frame count is exactly the pipe depth
6371 frameCount = mPipeFramesP2;
6372 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
6373 *notificationFrames = mFrameCount;
6374 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006375 // not fast track: max notification period is resampled equivalent of one HAL buffer time
6376 // or 20 ms if there is a fast capture
6377 // TODO This could be a roundupRatio inline, and const
6378 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
6379 * sampleRate + mSampleRate - 1) / mSampleRate;
6380 // minimum number of notification periods is at least kMinNotifications,
6381 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
6382 static const size_t kMinNotifications = 3;
6383 static const uint32_t kMinMs = 30;
6384 // TODO This could be a roundupRatio inline
6385 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
6386 // TODO This could be a roundupRatio inline
6387 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
6388 maxNotificationFrames;
6389 const size_t minFrameCount = maxNotificationFrames *
6390 max(kMinNotifications, minNotificationsByMs);
6391 frameCount = max(frameCount, minFrameCount);
6392 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
6393 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07006394 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07006395 }
Glenn Kasten74935e42013-12-19 08:56:45 -08006396 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07006397
Glenn Kasten15e57982013-09-24 11:52:37 -07006398 lStatus = initCheck();
6399 if (lStatus != NO_ERROR) {
6400 ALOGE("createRecordTrack_l() audio driver not initialized");
6401 goto Exit;
6402 }
Eric Laurent81784c32012-11-19 14:55:58 -08006403
6404 { // scope for mLock
6405 Mutex::Autolock _l(mLock);
6406
6407 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07006408 format, channelMask, frameCount, NULL, sessionId, uid,
6409 *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08006410
Glenn Kasten03003332013-08-06 15:40:54 -07006411 lStatus = track->initCheck();
6412 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07006413 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08006414 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08006415 goto Exit;
6416 }
6417 mTracks.add(track);
6418
6419 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6420 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6421 mAudioFlinger->btNrecIsOff();
6422 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6423 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006424
6425 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
6426 pid_t callingPid = IPCThreadState::self()->getCallingPid();
6427 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
6428 // so ask activity manager to do this on our behalf
6429 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
6430 }
Eric Laurent81784c32012-11-19 14:55:58 -08006431 }
Glenn Kasten05997e22014-03-13 15:08:33 -07006432
Eric Laurent81784c32012-11-19 14:55:58 -08006433 lStatus = NO_ERROR;
6434
6435Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07006436 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08006437 return track;
6438}
6439
6440status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6441 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08006442 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08006443{
6444 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6445 sp<ThreadBase> strongMe = this;
6446 status_t status = NO_ERROR;
6447
6448 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006449 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006450 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006451 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08006452 triggerSession,
6453 recordTrack->sessionId(),
6454 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006455 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08006456 // Sync event can be cancelled by the trigger session if the track is not in a
6457 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006458 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006459 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006460 } else {
6461 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006462 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006463 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08006464 }
6465 }
6466
6467 {
Glenn Kasten47c20702013-08-13 15:37:35 -07006468 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08006469 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006470 if (mActiveTracks.indexOf(recordTrack) >= 0) {
6471 if (recordTrack->mState == TrackBase::PAUSING) {
6472 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006473 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006474 } else {
6475 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08006476 }
6477 return status;
6478 }
6479
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006480 // TODO consider other ways of handling this, such as changing the state to :STARTING and
6481 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6482 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006483 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08006484 mActiveTracks.add(recordTrack);
6485 mActiveTracksGen++;
Eric Laurent83b88082014-06-20 18:31:16 -07006486 status_t status = NO_ERROR;
6487 if (recordTrack->isExternalTrack()) {
6488 mLock.unlock();
Glenn Kastend848eb42016-03-08 13:42:11 -08006489 status = AudioSystem::startInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006490 mLock.lock();
6491 // FIXME should verify that recordTrack is still in mActiveTracks
6492 if (status != NO_ERROR) {
6493 mActiveTracks.remove(recordTrack);
6494 mActiveTracksGen++;
6495 recordTrack->clearSyncStartEvent();
6496 ALOGV("RecordThread::start error %d", status);
6497 return status;
6498 }
Eric Laurent81784c32012-11-19 14:55:58 -08006499 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006500 // Catch up with current buffer indices if thread is already running.
6501 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
6502 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6503 // see previously buffered data before it called start(), but with greater risk of overrun.
6504
Andy Hung73c02e42015-03-29 01:13:58 -07006505 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07006506 // clear any converter state as new data will be discontinuous
6507 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006508 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08006509 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08006510 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08006511 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006512 ALOGV("Record failed to start");
6513 status = BAD_VALUE;
6514 goto startError;
6515 }
Eric Laurent81784c32012-11-19 14:55:58 -08006516 return status;
6517 }
Glenn Kasten7c027242012-12-26 14:43:16 -08006518
Eric Laurent81784c32012-11-19 14:55:58 -08006519startError:
Eric Laurent83b88082014-06-20 18:31:16 -07006520 if (recordTrack->isExternalTrack()) {
Glenn Kastend848eb42016-03-08 13:42:11 -08006521 AudioSystem::stopInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006522 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006523 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006524 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08006525 return status;
6526}
6527
Eric Laurent81784c32012-11-19 14:55:58 -08006528void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6529{
6530 sp<SyncEvent> strongEvent = event.promote();
6531
6532 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08006533 sp<RefBase> ptr = strongEvent->cookie().promote();
6534 if (ptr != 0) {
6535 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6536 recordTrack->handleSyncStartEvent(strongEvent);
6537 }
Eric Laurent81784c32012-11-19 14:55:58 -08006538 }
6539}
6540
Glenn Kastena8356f62013-07-25 14:37:52 -07006541bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08006542 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07006543 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006544 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08006545 return false;
6546 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006547 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006548 recordTrack->mState = TrackBase::PAUSING;
6549 // do not wait for mStartStopCond if exiting
6550 if (exitPending()) {
6551 return true;
6552 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006553 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08006554 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006555 // if we have been restarted, recordTrack is in mActiveTracks here
6556 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006557 ALOGV("Record stopped OK");
6558 return true;
6559 }
6560 return false;
6561}
6562
Glenn Kasten0f11b512014-01-31 16:18:54 -08006563bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08006564{
6565 return false;
6566}
6567
Glenn Kasten0f11b512014-01-31 16:18:54 -08006568status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006569{
6570#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6571 if (!isValidSyncEvent(event)) {
6572 return BAD_VALUE;
6573 }
6574
Glenn Kastend848eb42016-03-08 13:42:11 -08006575 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08006576 status_t ret = NAME_NOT_FOUND;
6577
6578 Mutex::Autolock _l(mLock);
6579
6580 for (size_t i = 0; i < mTracks.size(); i++) {
6581 sp<RecordTrack> track = mTracks[i];
6582 if (eventSession == track->sessionId()) {
6583 (void) track->setSyncEvent(event);
6584 ret = NO_ERROR;
6585 }
6586 }
6587 return ret;
6588#else
6589 return BAD_VALUE;
6590#endif
6591}
6592
6593// destroyTrack_l() must be called with ThreadBase::mLock held
6594void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6595{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006596 track->terminate();
6597 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006598 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006599 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006600 removeTrack_l(track);
6601 }
6602}
6603
6604void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6605{
6606 mTracks.remove(track);
6607 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006608 if (track->isFastTrack()) {
6609 ALOG_ASSERT(!mFastTrackAvail);
6610 mFastTrackAvail = true;
6611 }
Eric Laurent81784c32012-11-19 14:55:58 -08006612}
6613
6614void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6615{
6616 dumpInternals(fd, args);
6617 dumpTracks(fd, args);
6618 dumpEffectChains(fd, args);
6619}
6620
6621void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6622{
Elliott Hughes87cebad2014-05-22 10:14:43 -07006623 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08006624
Glenn Kasten44182c22015-03-05 17:12:23 -08006625 dumpBase(fd, args);
6626
6627 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006628 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006629 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006630 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006631 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08006632
Glenn Kasten2f90c512015-12-02 11:40:09 -08006633 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
6634 // while we are dumping it. It may be inconsistent, but it won't mutate!
6635 // This is a large object so we place it on the heap.
6636 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
6637 const FastCaptureDumpState *copy = new FastCaptureDumpState(mFastCaptureDumpState);
6638 copy->dump(fd);
6639 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08006640}
6641
Glenn Kasten0f11b512014-01-31 16:18:54 -08006642void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006643{
6644 const size_t SIZE = 256;
6645 char buffer[SIZE];
6646 String8 result;
6647
Marco Nelissenb2208842014-02-07 14:00:50 -08006648 size_t numtracks = mTracks.size();
6649 size_t numactive = mActiveTracks.size();
6650 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006651 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006652 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006653 dprintf(fd, " of which %zu are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006654 RecordTrack::appendDumpHeader(result);
6655 for (size_t i = 0; i < numtracks ; ++i) {
6656 sp<RecordTrack> track = mTracks[i];
6657 if (track != 0) {
6658 bool active = mActiveTracks.indexOf(track) >= 0;
6659 if (active) {
6660 numactiveseen++;
6661 }
6662 track->dump(buffer, SIZE, active);
6663 result.append(buffer);
6664 }
Eric Laurent81784c32012-11-19 14:55:58 -08006665 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006666 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006667 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006668 }
6669
Marco Nelissenb2208842014-02-07 14:00:50 -08006670 if (numactiveseen != numactive) {
6671 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6672 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006673 result.append(buffer);
6674 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006675 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006676 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006677 if (mTracks.indexOf(track) < 0) {
6678 track->dump(buffer, SIZE, true);
6679 result.append(buffer);
6680 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006681 }
Eric Laurent81784c32012-11-19 14:55:58 -08006682
6683 }
6684 write(fd, result.string(), result.size());
6685}
6686
Andy Hung73c02e42015-03-29 01:13:58 -07006687
6688void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
6689{
6690 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6691 RecordThread *recordThread = (RecordThread *) threadBase.get();
6692 mRsmpInFront = recordThread->mRsmpInRear;
6693 mRsmpInUnrel = 0;
6694}
6695
6696void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
6697 size_t *framesAvailable, bool *hasOverrun)
6698{
6699 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6700 RecordThread *recordThread = (RecordThread *) threadBase.get();
6701 const int32_t rear = recordThread->mRsmpInRear;
6702 const int32_t front = mRsmpInFront;
6703 const ssize_t filled = rear - front;
6704
6705 size_t framesIn;
6706 bool overrun = false;
6707 if (filled < 0) {
6708 // should not happen, but treat like a massive overrun and re-sync
6709 framesIn = 0;
6710 mRsmpInFront = rear;
6711 overrun = true;
6712 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
6713 framesIn = (size_t) filled;
6714 } else {
6715 // client is not keeping up with server, but give it latest data
6716 framesIn = recordThread->mRsmpInFrames;
6717 mRsmpInFront = /* front = */ rear - framesIn;
6718 overrun = true;
6719 }
6720 if (framesAvailable != NULL) {
6721 *framesAvailable = framesIn;
6722 }
6723 if (hasOverrun != NULL) {
6724 *hasOverrun = overrun;
6725 }
6726}
6727
Eric Laurent81784c32012-11-19 14:55:58 -08006728// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006729status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08006730 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006731{
Andy Hung73c02e42015-03-29 01:13:58 -07006732 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006733 if (threadBase == 0) {
6734 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006735 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006736 return NOT_ENOUGH_DATA;
6737 }
6738 RecordThread *recordThread = (RecordThread *) threadBase.get();
6739 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07006740 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07006741 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006742 // FIXME should not be P2 (don't want to increase latency)
6743 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006744 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07006745 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006746 front &= recordThread->mRsmpInFramesP2 - 1;
6747 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07006748 if (part1 > (size_t) filled) {
6749 part1 = filled;
6750 }
6751 size_t ask = buffer->frameCount;
6752 ALOG_ASSERT(ask > 0);
6753 if (part1 > ask) {
6754 part1 = ask;
6755 }
6756 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07006757 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07006758 buffer->raw = NULL;
6759 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07006760 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07006761 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08006762 }
6763
Andy Hung57446612015-04-19 23:56:46 -07006764 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07006765 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07006766 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08006767 return NO_ERROR;
6768}
6769
6770// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006771void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
6772 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006773{
Glenn Kasten85948432013-08-19 12:09:05 -07006774 size_t stepCount = buffer->frameCount;
6775 if (stepCount == 0) {
6776 return;
6777 }
Andy Hung73c02e42015-03-29 01:13:58 -07006778 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
6779 mRsmpInUnrel -= stepCount;
6780 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006781 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006782 buffer->frameCount = 0;
6783}
6784
Andy Hung97a893e2015-03-29 01:03:07 -07006785AudioFlinger::RecordThread::RecordBufferConverter::RecordBufferConverter(
6786 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6787 uint32_t srcSampleRate,
6788 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6789 uint32_t dstSampleRate) :
6790 mSrcChannelMask(AUDIO_CHANNEL_INVALID), // updateParameters will set following vars
6791 // mSrcFormat
6792 // mSrcSampleRate
6793 // mDstChannelMask
6794 // mDstFormat
6795 // mDstSampleRate
6796 // mSrcChannelCount
6797 // mDstChannelCount
6798 // mDstFrameSize
6799 mBuf(NULL), mBufFrames(0), mBufFrameSize(0),
Andy Hungd330ee42015-04-20 13:23:41 -07006800 mResampler(NULL),
6801 mIsLegacyDownmix(false),
6802 mIsLegacyUpmix(false),
6803 mRequiresFloat(false),
6804 mInputConverterProvider(NULL)
Andy Hung97a893e2015-03-29 01:03:07 -07006805{
6806 (void)updateParameters(srcChannelMask, srcFormat, srcSampleRate,
6807 dstChannelMask, dstFormat, dstSampleRate);
6808}
6809
6810AudioFlinger::RecordThread::RecordBufferConverter::~RecordBufferConverter() {
6811 free(mBuf);
6812 delete mResampler;
Andy Hungd330ee42015-04-20 13:23:41 -07006813 delete mInputConverterProvider;
Andy Hung97a893e2015-03-29 01:03:07 -07006814}
6815
6816size_t AudioFlinger::RecordThread::RecordBufferConverter::convert(void *dst,
6817 AudioBufferProvider *provider, size_t frames)
6818{
Andy Hungd330ee42015-04-20 13:23:41 -07006819 if (mInputConverterProvider != NULL) {
6820 mInputConverterProvider->setBufferProvider(provider);
6821 provider = mInputConverterProvider;
6822 }
6823
6824 if (mResampler == NULL) {
Andy Hung97a893e2015-03-29 01:03:07 -07006825 ALOGVV("NO RESAMPLING sampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6826 mSrcSampleRate, mSrcFormat, mDstFormat);
6827
6828 AudioBufferProvider::Buffer buffer;
6829 for (size_t i = frames; i > 0; ) {
6830 buffer.frameCount = i;
Glenn Kastend79072e2016-01-06 08:41:20 -08006831 status_t status = provider->getNextBuffer(&buffer);
Andy Hung97a893e2015-03-29 01:03:07 -07006832 if (status != OK || buffer.frameCount == 0) {
6833 frames -= i; // cannot fill request.
6834 break;
6835 }
Andy Hungd330ee42015-04-20 13:23:41 -07006836 // format convert to destination buffer
6837 convertNoResampler(dst, buffer.raw, buffer.frameCount);
Andy Hung97a893e2015-03-29 01:03:07 -07006838
6839 dst = (int8_t*)dst + buffer.frameCount * mDstFrameSize;
6840 i -= buffer.frameCount;
6841 provider->releaseBuffer(&buffer);
6842 }
6843 } else {
6844 ALOGVV("RESAMPLING mSrcSampleRate:%u mDstSampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6845 mSrcSampleRate, mDstSampleRate, mSrcFormat, mDstFormat);
6846
Andy Hungd330ee42015-04-20 13:23:41 -07006847 // reallocate buffer if needed
6848 if (mBufFrameSize != 0 && mBufFrames < frames) {
6849 free(mBuf);
6850 mBufFrames = frames;
6851 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6852 }
Andy Hung97a893e2015-03-29 01:03:07 -07006853 // resampler accumulates, but we only have one source track
Andy Hungd330ee42015-04-20 13:23:41 -07006854 memset(mBuf, 0, frames * mBufFrameSize);
6855 frames = mResampler->resample((int32_t*)mBuf, frames, provider);
6856 // format convert to destination buffer
6857 convertResampler(dst, mBuf, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006858 }
6859 return frames;
6860}
6861
6862status_t AudioFlinger::RecordThread::RecordBufferConverter::updateParameters(
6863 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6864 uint32_t srcSampleRate,
6865 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6866 uint32_t dstSampleRate)
6867{
6868 // quick evaluation if there is any change.
6869 if (mSrcFormat == srcFormat
6870 && mSrcChannelMask == srcChannelMask
6871 && mSrcSampleRate == srcSampleRate
6872 && mDstFormat == dstFormat
6873 && mDstChannelMask == dstChannelMask
6874 && mDstSampleRate == dstSampleRate) {
6875 return NO_ERROR;
6876 }
6877
Andy Hungdb4c0312015-05-06 08:46:52 -07006878 ALOGV("RecordBufferConverter updateParameters srcMask:%#x dstMask:%#x"
6879 " srcFormat:%#x dstFormat:%#x srcRate:%u dstRate:%u",
6880 srcChannelMask, dstChannelMask, srcFormat, dstFormat, srcSampleRate, dstSampleRate);
Andy Hung97a893e2015-03-29 01:03:07 -07006881 const bool valid =
6882 audio_is_input_channel(srcChannelMask)
6883 && audio_is_input_channel(dstChannelMask)
6884 && audio_is_valid_format(srcFormat) && audio_is_linear_pcm(srcFormat)
6885 && audio_is_valid_format(dstFormat) && audio_is_linear_pcm(dstFormat)
6886 && (srcSampleRate <= dstSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX)
6887 ; // no upsampling checks for now
6888 if (!valid) {
6889 return BAD_VALUE;
6890 }
6891
6892 mSrcFormat = srcFormat;
6893 mSrcChannelMask = srcChannelMask;
6894 mSrcSampleRate = srcSampleRate;
6895 mDstFormat = dstFormat;
6896 mDstChannelMask = dstChannelMask;
6897 mDstSampleRate = dstSampleRate;
6898
6899 // compute derived parameters
6900 mSrcChannelCount = audio_channel_count_from_in_mask(srcChannelMask);
6901 mDstChannelCount = audio_channel_count_from_in_mask(dstChannelMask);
6902 mDstFrameSize = mDstChannelCount * audio_bytes_per_sample(mDstFormat);
6903
Andy Hungd330ee42015-04-20 13:23:41 -07006904 // do we need to resample?
6905 delete mResampler;
6906 mResampler = NULL;
6907 if (mSrcSampleRate != mDstSampleRate) {
6908 mResampler = AudioResampler::create(AUDIO_FORMAT_PCM_FLOAT,
6909 mSrcChannelCount, mDstSampleRate);
6910 mResampler->setSampleRate(mSrcSampleRate);
6911 mResampler->setVolume(AudioMixer::UNITY_GAIN_FLOAT, AudioMixer::UNITY_GAIN_FLOAT);
6912 }
6913
6914 // are we running legacy channel conversion modes?
6915 mIsLegacyDownmix = (mSrcChannelMask == AUDIO_CHANNEL_IN_STEREO
6916 || mSrcChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK)
6917 && mDstChannelMask == AUDIO_CHANNEL_IN_MONO;
6918 mIsLegacyUpmix = mSrcChannelMask == AUDIO_CHANNEL_IN_MONO
6919 && (mDstChannelMask == AUDIO_CHANNEL_IN_STEREO
6920 || mDstChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK);
6921
6922 // do we need to process in float?
6923 mRequiresFloat = mResampler != NULL || mIsLegacyDownmix || mIsLegacyUpmix;
6924
6925 // do we need a staging buffer to convert for destination (we can still optimize this)?
6926 // we use mBufFrameSize > 0 to indicate both frame size as well as buffer necessity
6927 if (mResampler != NULL) {
6928 mBufFrameSize = max(mSrcChannelCount, FCC_2)
6929 * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
Andy Hunga97630b2015-07-22 23:27:24 -07006930 } else if (mIsLegacyUpmix || mIsLegacyDownmix) { // legacy modes always float
Andy Hungd330ee42015-04-20 13:23:41 -07006931 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
6932 } else if (mSrcChannelMask != mDstChannelMask && mDstFormat != mSrcFormat) {
Andy Hung97a893e2015-03-29 01:03:07 -07006933 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(mSrcFormat);
6934 } else {
6935 mBufFrameSize = 0;
6936 }
6937 mBufFrames = 0; // force the buffer to be resized.
6938
Andy Hungd330ee42015-04-20 13:23:41 -07006939 // do we need an input converter buffer provider to give us float?
6940 delete mInputConverterProvider;
6941 mInputConverterProvider = NULL;
6942 if (mRequiresFloat && mSrcFormat != AUDIO_FORMAT_PCM_FLOAT) {
6943 mInputConverterProvider = new ReformatBufferProvider(
6944 audio_channel_count_from_in_mask(mSrcChannelMask),
6945 mSrcFormat,
6946 AUDIO_FORMAT_PCM_FLOAT,
6947 256 /* provider buffer frame count */);
6948 }
6949
6950 // do we need a remixer to do channel mask conversion
6951 if (!mIsLegacyDownmix && !mIsLegacyUpmix && mSrcChannelMask != mDstChannelMask) {
6952 (void) memcpy_by_index_array_initialization_from_channel_mask(
6953 mIdxAry, ARRAY_SIZE(mIdxAry), mDstChannelMask, mSrcChannelMask);
Andy Hung97a893e2015-03-29 01:03:07 -07006954 }
6955 return NO_ERROR;
6956}
6957
Andy Hungd330ee42015-04-20 13:23:41 -07006958void AudioFlinger::RecordThread::RecordBufferConverter::convertNoResampler(
6959 void *dst, const void *src, size_t frames)
Andy Hung97a893e2015-03-29 01:03:07 -07006960{
Andy Hungd330ee42015-04-20 13:23:41 -07006961 // src is native type unless there is legacy upmix or downmix, whereupon it is float.
Andy Hung97a893e2015-03-29 01:03:07 -07006962 if (mBufFrameSize != 0 && mBufFrames < frames) {
6963 free(mBuf);
6964 mBufFrames = frames;
6965 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6966 }
Andy Hungd330ee42015-04-20 13:23:41 -07006967 // do we need to do legacy upmix and downmix?
6968 if (mIsLegacyUpmix || mIsLegacyDownmix) {
Andy Hung97a893e2015-03-29 01:03:07 -07006969 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07006970 if (mIsLegacyUpmix) {
6971 upmix_to_stereo_float_from_mono_float((float *)dstBuf,
6972 (const float *)src, frames);
6973 } else /*mIsLegacyDownmix */ {
6974 downmix_to_mono_float_from_stereo_float((float *)dstBuf,
6975 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006976 }
Andy Hungd330ee42015-04-20 13:23:41 -07006977 if (mBuf != NULL) {
6978 memcpy_by_audio_format(dst, mDstFormat, mBuf, AUDIO_FORMAT_PCM_FLOAT,
6979 frames * mDstChannelCount);
6980 }
6981 return;
6982 }
6983 // do we need to do channel mask conversion?
6984 if (mSrcChannelMask != mDstChannelMask) {
Andy Hung97a893e2015-03-29 01:03:07 -07006985 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07006986 memcpy_by_index_array(dstBuf, mDstChannelCount,
6987 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mSrcFormat), frames);
6988 if (dstBuf == dst) {
6989 return; // format is the same
6990 }
6991 }
6992 // convert to destination buffer
6993 const void *convertBuf = mBuf != NULL ? mBuf : src;
6994 memcpy_by_audio_format(dst, mDstFormat, convertBuf, mSrcFormat,
6995 frames * mDstChannelCount);
6996}
6997
6998void AudioFlinger::RecordThread::RecordBufferConverter::convertResampler(
6999 void *dst, /*not-a-const*/ void *src, size_t frames)
7000{
7001 // src buffer format is ALWAYS float when entering this routine
7002 if (mIsLegacyUpmix) {
7003 ; // mono to stereo already handled by resampler
7004 } else if (mIsLegacyDownmix
7005 || (mSrcChannelMask == mDstChannelMask && mSrcChannelCount == 1)) {
7006 // the resampler outputs stereo for mono input channel (a feature?)
7007 // must convert to mono
7008 downmix_to_mono_float_from_stereo_float((float *)src,
7009 (const float *)src, frames);
7010 } else if (mSrcChannelMask != mDstChannelMask) {
7011 // convert to mono channel again for channel mask conversion (could be skipped
7012 // with further optimization).
Andy Hung97a893e2015-03-29 01:03:07 -07007013 if (mSrcChannelCount == 1) {
Andy Hungd330ee42015-04-20 13:23:41 -07007014 downmix_to_mono_float_from_stereo_float((float *)src,
7015 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07007016 }
Andy Hungd330ee42015-04-20 13:23:41 -07007017 // convert to destination format (in place, OK as float is larger than other types)
7018 if (mDstFormat != AUDIO_FORMAT_PCM_FLOAT) {
7019 memcpy_by_audio_format(src, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
7020 frames * mSrcChannelCount);
7021 }
7022 // channel convert and save to dst
7023 memcpy_by_index_array(dst, mDstChannelCount,
7024 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mDstFormat), frames);
7025 return;
Andy Hung97a893e2015-03-29 01:03:07 -07007026 }
Andy Hungd330ee42015-04-20 13:23:41 -07007027 // convert to destination format and save to dst
7028 memcpy_by_audio_format(dst, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
7029 frames * mDstChannelCount);
Andy Hung97a893e2015-03-29 01:03:07 -07007030}
7031
Eric Laurent10351942014-05-08 18:49:52 -07007032bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
7033 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007034{
7035 bool reconfig = false;
7036
Eric Laurent10351942014-05-08 18:49:52 -07007037 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007038
Eric Laurent10351942014-05-08 18:49:52 -07007039 audio_format_t reqFormat = mFormat;
7040 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07007041 // 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 -07007042 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
7043
7044 AudioParameter param = AudioParameter(keyValuePair);
7045 int value;
7046 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
7047 // channel count change can be requested. Do we mandate the first client defines the
7048 // HAL sampling rate and channel count or do we allow changes on the fly?
7049 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
7050 samplingRate = value;
7051 reconfig = true;
7052 }
7053 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07007054 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07007055 status = BAD_VALUE;
7056 } else {
7057 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08007058 reconfig = true;
7059 }
Eric Laurent10351942014-05-08 18:49:52 -07007060 }
7061 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
7062 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07007063 if (!audio_is_input_channel(mask) ||
7064 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007065 status = BAD_VALUE;
7066 } else {
7067 channelMask = mask;
7068 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007069 }
Eric Laurent10351942014-05-08 18:49:52 -07007070 }
7071 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7072 // do not accept frame count changes if tracks are open as the track buffer
7073 // size depends on frame count and correct behavior would not be guaranteed
7074 // if frame count is changed after track creation
7075 if (mActiveTracks.size() > 0) {
7076 status = INVALID_OPERATION;
7077 } else {
7078 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007079 }
Eric Laurent10351942014-05-08 18:49:52 -07007080 }
7081 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7082 // forward device change to effects that have requested to be
7083 // aware of attached audio device.
7084 for (size_t i = 0; i < mEffectChains.size(); i++) {
7085 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08007086 }
Eric Laurent81784c32012-11-19 14:55:58 -08007087
Eric Laurent10351942014-05-08 18:49:52 -07007088 // store input device and output device but do not forward output device to audio HAL.
7089 // Note that status is ignored by the caller for output device
7090 // (see AudioFlinger::setParameters()
7091 if (audio_is_output_devices(value)) {
7092 mOutDevice = value;
7093 status = BAD_VALUE;
7094 } else {
7095 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07007096 if (value != AUDIO_DEVICE_NONE) {
7097 mPrevInDevice = value;
7098 }
Eric Laurent10351942014-05-08 18:49:52 -07007099 // disable AEC and NS if the device is a BT SCO headset supporting those
7100 // pre processings
7101 if (mTracks.size() > 0) {
7102 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7103 mAudioFlinger->btNrecIsOff();
7104 for (size_t i = 0; i < mTracks.size(); i++) {
7105 sp<RecordTrack> track = mTracks[i];
7106 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7107 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08007108 }
7109 }
7110 }
Eric Laurent10351942014-05-08 18:49:52 -07007111 }
7112 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
7113 mAudioSource != (audio_source_t)value) {
7114 // forward device change to effects that have requested to be
7115 // aware of attached audio device.
7116 for (size_t i = 0; i < mEffectChains.size(); i++) {
7117 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08007118 }
Eric Laurent10351942014-05-08 18:49:52 -07007119 mAudioSource = (audio_source_t)value;
7120 }
Glenn Kastene198c362013-08-13 09:13:36 -07007121
Eric Laurent10351942014-05-08 18:49:52 -07007122 if (status == NO_ERROR) {
7123 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7124 keyValuePair.string());
7125 if (status == INVALID_OPERATION) {
7126 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08007127 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7128 keyValuePair.string());
Eric Laurent10351942014-05-08 18:49:52 -07007129 }
7130 if (reconfig) {
7131 if (status == BAD_VALUE &&
Andy Hung97a893e2015-03-29 01:03:07 -07007132 audio_is_linear_pcm(mInput->stream->common.get_format(&mInput->stream->common)) &&
7133 audio_is_linear_pcm(reqFormat) &&
Eric Laurent10351942014-05-08 18:49:52 -07007134 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
Andy Hung97a893e2015-03-29 01:03:07 -07007135 <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate)) &&
Andy Hunge5412692014-05-16 11:25:07 -07007136 audio_channel_count_from_in_mask(
Andy Hungd1abb8f2015-05-05 23:42:34 -07007137 mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007138 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007139 }
Eric Laurent10351942014-05-08 18:49:52 -07007140 if (status == NO_ERROR) {
7141 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007142 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08007143 }
7144 }
Eric Laurent81784c32012-11-19 14:55:58 -08007145 }
Eric Laurent10351942014-05-08 18:49:52 -07007146
Eric Laurent81784c32012-11-19 14:55:58 -08007147 return reconfig;
7148}
7149
7150String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
7151{
Eric Laurent81784c32012-11-19 14:55:58 -08007152 Mutex::Autolock _l(mLock);
7153 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07007154 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08007155 }
7156
Glenn Kastend8ea6992013-07-16 14:17:15 -07007157 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
7158 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08007159 free(s);
7160 return out_s8;
7161}
7162
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007163void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007164 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7165
7166 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08007167
7168 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007169 case AUDIO_INPUT_OPENED:
7170 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07007171 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07007172 desc->mChannelMask = mChannelMask;
7173 desc->mSamplingRate = mSampleRate;
7174 desc->mFormat = mFormat;
7175 desc->mFrameCount = mFrameCount;
7176 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007177 break;
7178
Eric Laurent73e26b62015-04-27 16:55:58 -07007179 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08007180 default:
7181 break;
7182 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007183 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08007184}
7185
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007186void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007187{
Eric Laurent81784c32012-11-19 14:55:58 -08007188 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
7189 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Andy Hunge5412692014-05-16 11:25:07 -07007190 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Andy Hungd330ee42015-04-20 13:23:41 -07007191 if (mChannelCount > FCC_8) {
7192 ALOGE("HAL channel count %d > %d", mChannelCount, FCC_8);
7193 }
Andy Hung463be252014-07-10 16:56:07 -07007194 mHALFormat = mInput->stream->common.get_format(&mInput->stream->common);
7195 mFormat = mHALFormat;
Andy Hungd330ee42015-04-20 13:23:41 -07007196 if (!audio_is_linear_pcm(mFormat)) {
7197 ALOGE("HAL format %#x is not linear pcm", mFormat);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07007198 }
Eric Laurent665470b2014-07-03 16:37:08 -07007199 mFrameSize = audio_stream_in_frame_size(mInput->stream);
Glenn Kasten548efc92012-11-29 08:48:51 -08007200 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
7201 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007202 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08007203 // 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 -07007204 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08007205 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007206 // A larger value should allow more old data to be read after a track calls start(),
7207 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07007208 //
7209 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08007210 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07007211 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07007212 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07007213 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007214
7215 // TODO optimize audio capture buffer sizes ...
7216 // Here we calculate the size of the sliding buffer used as a source
7217 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
7218 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
7219 // be better to have it derived from the pipe depth in the long term.
7220 // The current value is higher than necessary. However it should not add to latency.
7221
Glenn Kasten85948432013-08-19 12:09:05 -07007222 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Andy Hung0a01c2f2015-09-21 12:44:54 -07007223 size_t bufferSize = (mRsmpInFramesP2 + mFrameCount - 1) * mFrameSize;
7224 (void)posix_memalign(&mRsmpInBuffer, 32, bufferSize);
7225 memset(mRsmpInBuffer, 0, bufferSize); // if posix_memalign fails, will segv here.
Eric Laurent81784c32012-11-19 14:55:58 -08007226
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007227 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
7228 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08007229}
7230
Glenn Kasten5f972c02014-01-13 09:59:31 -08007231uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08007232{
7233 Mutex::Autolock _l(mLock);
7234 if (initCheck() != NO_ERROR) {
7235 return 0;
7236 }
7237
7238 return mInput->stream->get_input_frames_lost(mInput->stream);
7239}
7240
Glenn Kastend848eb42016-03-08 13:42:11 -08007241uint32_t AudioFlinger::RecordThread::hasAudioSession(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08007242{
7243 Mutex::Autolock _l(mLock);
7244 uint32_t result = 0;
7245 if (getEffectChain_l(sessionId) != 0) {
7246 result = EFFECT_SESSION;
7247 }
7248
7249 for (size_t i = 0; i < mTracks.size(); ++i) {
7250 if (sessionId == mTracks[i]->sessionId()) {
7251 result |= TRACK_SESSION;
7252 break;
7253 }
7254 }
7255
7256 return result;
7257}
7258
Glenn Kastend848eb42016-03-08 13:42:11 -08007259KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08007260{
Glenn Kastend848eb42016-03-08 13:42:11 -08007261 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08007262 Mutex::Autolock _l(mLock);
7263 for (size_t j = 0; j < mTracks.size(); ++j) {
7264 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08007265 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08007266 if (ids.indexOfKey(sessionId) < 0) {
7267 ids.add(sessionId, true);
7268 }
7269 }
7270 return ids;
7271}
7272
7273AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7274{
7275 Mutex::Autolock _l(mLock);
7276 AudioStreamIn *input = mInput;
7277 mInput = NULL;
7278 return input;
7279}
7280
7281// this method must always be called either with ThreadBase mLock held or inside the thread loop
7282audio_stream_t* AudioFlinger::RecordThread::stream() const
7283{
7284 if (mInput == NULL) {
7285 return NULL;
7286 }
7287 return &mInput->stream->common;
7288}
7289
7290status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7291{
7292 // only one chain per input thread
7293 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07007294 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08007295 return INVALID_OPERATION;
7296 }
7297 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07007298 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08007299 chain->setInBuffer(NULL);
7300 chain->setOutBuffer(NULL);
7301
7302 checkSuspendOnAddEffectChain_l(chain);
7303
Eric Laurent1b928682014-10-02 19:41:47 -07007304 // make sure enabled pre processing effects state is communicated to the HAL as we
7305 // just moved them to a new input stream.
7306 chain->syncHalEffectsState();
7307
Eric Laurent81784c32012-11-19 14:55:58 -08007308 mEffectChains.add(chain);
7309
7310 return NO_ERROR;
7311}
7312
7313size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7314{
7315 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7316 ALOGW_IF(mEffectChains.size() != 1,
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007317 "removeEffectChain_l() %p invalid chain size %zu on thread %p",
Eric Laurent81784c32012-11-19 14:55:58 -08007318 chain.get(), mEffectChains.size(), this);
7319 if (mEffectChains.size() == 1) {
7320 mEffectChains.removeAt(0);
7321 }
7322 return 0;
7323}
7324
Eric Laurent1c333e22014-05-20 10:48:17 -07007325status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7326 audio_patch_handle_t *handle)
7327{
7328 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007329
7330 // store new device and send to effects
7331 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07007332 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07007333 for (size_t i = 0; i < mEffectChains.size(); i++) {
7334 mEffectChains[i]->setDevice_l(mInDevice);
7335 }
7336
7337 // disable AEC and NS if the device is a BT SCO headset supporting those
7338 // pre processings
7339 if (mTracks.size() > 0) {
7340 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7341 mAudioFlinger->btNrecIsOff();
7342 for (size_t i = 0; i < mTracks.size(); i++) {
7343 sp<RecordTrack> track = mTracks[i];
7344 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7345 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
7346 }
7347 }
7348
7349 // store new source and send to effects
7350 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7351 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07007352 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07007353 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07007354 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007355 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007356
Eric Laurent054d9d32015-04-24 08:48:48 -07007357 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007358 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
7359 status = hwDevice->create_audio_patch(hwDevice,
7360 patch->num_sources,
7361 patch->sources,
7362 patch->num_sinks,
7363 patch->sinks,
7364 handle);
7365 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007366 char *address;
7367 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7368 address = audio_device_address_to_parameter(
7369 patch->sources[0].ext.device.type,
7370 patch->sources[0].ext.device.address);
7371 } else {
7372 address = (char *)calloc(1, 1);
7373 }
7374 AudioParameter param = AudioParameter(String8(address));
7375 free(address);
7376 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING),
7377 (int)patch->sources[0].ext.device.type);
7378 param.addInt(String8(AUDIO_PARAMETER_STREAM_INPUT_SOURCE),
7379 (int)patch->sinks[0].ext.mix.usecase.source);
7380 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7381 param.toString().string());
7382 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07007383 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007384
Eric Laurente8726fe2015-06-26 09:39:24 -07007385 if (mInDevice != mPrevInDevice) {
7386 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7387 mPrevInDevice = mInDevice;
7388 }
Eric Laurent296fb132015-05-01 11:38:42 -07007389
Eric Laurent1c333e22014-05-20 10:48:17 -07007390 return status;
7391}
7392
7393status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7394{
7395 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007396
7397 mInDevice = AUDIO_DEVICE_NONE;
7398
Eric Laurent1c333e22014-05-20 10:48:17 -07007399 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
7400 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
7401 status = hwDevice->release_audio_patch(hwDevice, handle);
7402 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007403 AudioParameter param;
7404 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
7405 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7406 param.toString().string());
Eric Laurent1c333e22014-05-20 10:48:17 -07007407 }
7408 return status;
7409}
7410
Eric Laurent83b88082014-06-20 18:31:16 -07007411void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
7412{
7413 Mutex::Autolock _l(mLock);
7414 mTracks.add(record);
7415}
7416
7417void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
7418{
7419 Mutex::Autolock _l(mLock);
7420 destroyTrack_l(record);
7421}
7422
7423void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
7424{
7425 ThreadBase::getAudioPortConfig(config);
7426 config->role = AUDIO_PORT_ROLE_SINK;
7427 config->ext.mix.hw_module = mInput->audioHwDev->handle();
7428 config->ext.mix.usecase.source = mAudioSource;
7429}
Eric Laurent1c333e22014-05-20 10:48:17 -07007430
Glenn Kasten63238ef2015-03-02 15:50:29 -08007431} // namespace android