blob: 973c98323f91911cf4ba2e784135e5b1d4b156e5 [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 // either of these use cases:
1788 (
1789 // use case 1: shared buffer with any frame count
1790 (
1791 (sharedBuffer != 0)
1792 ) ||
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001793 // use case 2: frame count is default or at least as large as HAL
Eric Laurent81784c32012-11-19 14:55:58 -08001794 (
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001795 // we formerly checked for a callback handler (non-0 tid),
1796 // but that is no longer required for TRANSFER_OBTAIN mode
Eric Laurent81784c32012-11-19 14:55:58 -08001797 ((frameCount == 0) ||
Glenn Kastenb5fed682013-12-03 09:06:43 -08001798 (frameCount >= mFrameCount))
Eric Laurent81784c32012-11-19 14:55:58 -08001799 )
1800 ) &&
1801 // PCM data
1802 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001803 // TODO: extract as a data library function that checks that a computationally
1804 // expensive downmixer is not required: isFastOutputChannelConversion()
Andy Hung9a592762014-07-21 21:56:01 -07001805 (channelMask == mChannelMask ||
Andy Hung1f439e12015-05-19 12:57:41 -07001806 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1807 (channelMask == AUDIO_CHANNEL_OUT_MONO
1808 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001809 // hardware sample rate
1810 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001811 // normal mixer has an associated fast mixer
1812 hasFastMixer() &&
1813 // there are sufficient fast track slots available
1814 (mFastTrackAvailMask != 0)
1815 // FIXME test that MixerThread for this fast track has a capable output HAL
1816 // FIXME add a permission test also?
1817 ) {
1818 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1819 if (frameCount == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001820 // read the fast track multiplier property the first time it is needed
1821 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1822 if (ok != 0) {
1823 ALOGE("%s pthread_once failed: %d", __func__, ok);
1824 }
1825 frameCount = mFrameCount * sFastTrackMultiplier;
Eric Laurent81784c32012-11-19 14:55:58 -08001826 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001827 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08001828 frameCount, mFrameCount);
1829 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001830 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
1831 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07001832 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001833 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08001834 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001835 audio_is_linear_pcm(format),
1836 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1837 *flags &= ~IAudioFlinger::TRACK_FAST;
Andy Hung0e48d252015-01-26 11:43:15 -08001838 }
1839 }
1840 // For normal PCM streaming tracks, update minimum frame count.
1841 // For compatibility with AudioTrack calculation, buffer depth is forced
1842 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1843 // This is probably too conservative, but legacy application code may depend on it.
1844 // If you change this calculation, also review the start threshold which is related.
1845 if (!(*flags & IAudioFlinger::TRACK_FAST)
Phil Burkfdb3c072016-02-09 10:47:02 -08001846 && audio_has_proportional_frames(format) && sharedBuffer == 0) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001847 // this must match AudioTrack.cpp calculateMinFrameCount().
1848 // TODO: Move to a common library
Eric Laurent81784c32012-11-19 14:55:58 -08001849 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1850 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1851 if (minBufCount < 2) {
1852 minBufCount = 2;
1853 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07001854 // For normal mixing tracks, if speed is > 1.0f (normal), AudioTrack
1855 // or the client should compute and pass in a larger buffer request.
Andy Hung0e48d252015-01-26 11:43:15 -08001856 size_t minFrameCount =
Andy Hung8edb8dc2015-03-26 19:13:55 -07001857 minBufCount * sourceFramesNeededWithTimestretch(
1858 sampleRate, mNormalFrameCount,
1859 mSampleRate, AUDIO_TIMESTRETCH_SPEED_NORMAL /*speed*/);
Andy Hung0e48d252015-01-26 11:43:15 -08001860 if (frameCount < minFrameCount) { // including frameCount == 0
Eric Laurent81784c32012-11-19 14:55:58 -08001861 frameCount = minFrameCount;
1862 }
Eric Laurent81784c32012-11-19 14:55:58 -08001863 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001864 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001865
Glenn Kastenc3df8382014-03-13 15:05:25 -07001866 switch (mType) {
1867
1868 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08001869 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08001870 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001871 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1872 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001873 sampleRate, format, channelMask, mOutput, mFormat);
1874 lStatus = BAD_VALUE;
1875 goto Exit;
1876 }
1877 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001878 break;
1879
1880 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001881 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001882 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1883 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001884 sampleRate, format, channelMask, mOutput, mFormat);
1885 lStatus = BAD_VALUE;
1886 goto Exit;
1887 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001888 break;
1889
1890 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001891 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001892 ALOGE("createTrack_l() Bad parameter: format %#x \""
1893 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001894 format, mOutput, mFormat);
1895 lStatus = BAD_VALUE;
1896 goto Exit;
1897 }
Andy Hungcd044842014-08-07 11:04:34 -07001898 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08001899 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1900 lStatus = BAD_VALUE;
1901 goto Exit;
1902 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001903 break;
1904
Eric Laurent81784c32012-11-19 14:55:58 -08001905 }
1906
1907 lStatus = initCheck();
1908 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001909 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08001910 goto Exit;
1911 }
1912
1913 { // scope for mLock
1914 Mutex::Autolock _l(mLock);
1915
1916 // all tracks in same audio session must share the same routing strategy otherwise
1917 // conflicts will happen when tracks are moved from one output to another by audio policy
1918 // manager
1919 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1920 for (size_t i = 0; i < mTracks.size(); ++i) {
1921 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07001922 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001923 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1924 if (sessionId == t->sessionId() && strategy != actual) {
1925 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1926 strategy, actual);
1927 lStatus = BAD_VALUE;
1928 goto Exit;
1929 }
1930 }
1931 }
1932
Glenn Kastend79072e2016-01-06 08:41:20 -08001933 track = new Track(this, client, streamType, sampleRate, format,
1934 channelMask, frameCount, NULL, sharedBuffer,
1935 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT);
Glenn Kasten03003332013-08-06 15:40:54 -07001936
Glenn Kasten03003332013-08-06 15:40:54 -07001937 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1938 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08001939 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001940 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08001941 goto Exit;
1942 }
1943 mTracks.add(track);
1944
1945 sp<EffectChain> chain = getEffectChain_l(sessionId);
1946 if (chain != 0) {
1947 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1948 track->setMainBuffer(chain->inBuffer());
1949 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1950 chain->incTrackCnt();
1951 }
1952
1953 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1954 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1955 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1956 // so ask activity manager to do this on our behalf
1957 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1958 }
1959 }
1960
1961 lStatus = NO_ERROR;
1962
1963Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001964 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001965 return track;
1966}
1967
1968uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1969{
1970 return latency;
1971}
1972
1973uint32_t AudioFlinger::PlaybackThread::latency() const
1974{
1975 Mutex::Autolock _l(mLock);
1976 return latency_l();
1977}
1978uint32_t AudioFlinger::PlaybackThread::latency_l() const
1979{
1980 if (initCheck() == NO_ERROR) {
1981 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1982 } else {
1983 return 0;
1984 }
1985}
1986
1987void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1988{
1989 Mutex::Autolock _l(mLock);
1990 // Don't apply master volume in SW if our HAL can do it for us.
1991 if (mOutput && mOutput->audioHwDev &&
1992 mOutput->audioHwDev->canSetMasterVolume()) {
1993 mMasterVolume = 1.0;
1994 } else {
1995 mMasterVolume = value;
1996 }
1997}
1998
1999void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2000{
2001 Mutex::Autolock _l(mLock);
2002 // Don't apply master mute in SW if our HAL can do it for us.
2003 if (mOutput && mOutput->audioHwDev &&
2004 mOutput->audioHwDev->canSetMasterMute()) {
2005 mMasterMute = false;
2006 } else {
2007 mMasterMute = muted;
2008 }
2009}
2010
2011void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2012{
2013 Mutex::Autolock _l(mLock);
2014 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002015 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002016}
2017
2018void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2019{
2020 Mutex::Autolock _l(mLock);
2021 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002022 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002023}
2024
2025float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2026{
2027 Mutex::Autolock _l(mLock);
2028 return mStreamTypes[stream].volume;
2029}
2030
2031// addTrack_l() must be called with ThreadBase::mLock held
2032status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2033{
2034 status_t status = ALREADY_EXISTS;
2035
Eric Laurent81784c32012-11-19 14:55:58 -08002036 if (mActiveTracks.indexOf(track) < 0) {
2037 // the track is newly added, make sure it fills up all its
2038 // buffers before playing. This is to ensure the client will
2039 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002040 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002041 TrackBase::track_state state = track->mState;
2042 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002043 status = AudioSystem::startOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002044 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002045 mLock.lock();
2046 // abort track was stopped/paused while we released the lock
2047 if (state != track->mState) {
2048 if (status == NO_ERROR) {
2049 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002050 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002051 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002052 mLock.lock();
2053 }
2054 return INVALID_OPERATION;
2055 }
2056 // abort if start is rejected by audio policy manager
2057 if (status != NO_ERROR) {
2058 return PERMISSION_DENIED;
2059 }
2060#ifdef ADD_BATTERY_DATA
2061 // to track the speaker usage
2062 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2063#endif
2064 }
2065
Eric Laurent51716182016-02-29 18:00:56 -08002066 // set retry count for buffer fill
2067 if (track->isOffloaded()) {
2068 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2069 } else {
2070 track->mRetryCount = kMaxTrackStartupRetries;
2071 }
2072
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002073 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08002074 track->mResetDone = false;
2075 track->mPresentationCompleteFrames = 0;
2076 mActiveTracks.add(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002077 mWakeLockUids.add(track->uid());
2078 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07002079 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07002080 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2081 if (chain != 0) {
2082 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2083 track->sessionId());
2084 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002085 }
2086
2087 status = NO_ERROR;
2088 }
2089
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002090 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002091 return status;
2092}
2093
Eric Laurentbfb1b832013-01-07 09:53:42 -08002094bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002095{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002096 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002097 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002098 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2099 track->mState = TrackBase::STOPPED;
2100 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002101 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002102 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002103 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002104 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002105
2106 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002107}
2108
2109void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2110{
2111 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
2112 mTracks.remove(track);
2113 deleteTrackName_l(track->name());
2114 // redundant as track is about to be destroyed, for dumpsys only
2115 track->mName = -1;
2116 if (track->isFastTrack()) {
2117 int index = track->mFastIndex;
2118 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
2119 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2120 mFastTrackAvailMask |= 1 << index;
2121 // redundant as track is about to be destroyed, for dumpsys only
2122 track->mFastIndex = -1;
2123 }
2124 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2125 if (chain != 0) {
2126 chain->decTrackCnt();
2127 }
2128}
2129
Eric Laurentede6c3b2013-09-19 14:37:46 -07002130void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002131{
2132 // Thread could be blocked waiting for async
2133 // so signal it to handle state changes immediately
2134 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
2135 // be lost so we also flag to prevent it blocking on mWaitWorkCV
2136 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002137 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002138}
2139
Eric Laurent81784c32012-11-19 14:55:58 -08002140String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2141{
Eric Laurent81784c32012-11-19 14:55:58 -08002142 Mutex::Autolock _l(mLock);
2143 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07002144 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002145 }
2146
Glenn Kastend8ea6992013-07-16 14:17:15 -07002147 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
2148 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08002149 free(s);
2150 return out_s8;
2151}
2152
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002153void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002154 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2155 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002156
Eric Laurent73e26b62015-04-27 16:55:58 -07002157 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002158
2159 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002160 case AUDIO_OUTPUT_OPENED:
2161 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002162 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002163 desc->mChannelMask = mChannelMask;
2164 desc->mSamplingRate = mSampleRate;
2165 desc->mFormat = mFormat;
2166 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002167 // AudioFlinger::frameCount(audio_io_handle_t)
Eric Laurent73e26b62015-04-27 16:55:58 -07002168 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002169 break;
2170
Eric Laurent73e26b62015-04-27 16:55:58 -07002171 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002172 default:
2173 break;
2174 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002175 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002176}
2177
Eric Laurentbfb1b832013-01-07 09:53:42 -08002178void AudioFlinger::PlaybackThread::writeCallback()
2179{
2180 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002181 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002182}
2183
2184void AudioFlinger::PlaybackThread::drainCallback()
2185{
2186 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002187 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002188}
2189
Eric Laurent3b4529e2013-09-05 18:09:19 -07002190void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002191{
2192 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002193 // reject out of sequence requests
2194 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2195 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002196 mWaitWorkCV.signal();
2197 }
2198}
2199
Eric Laurent3b4529e2013-09-05 18:09:19 -07002200void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002201{
2202 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002203 // reject out of sequence requests
2204 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
2205 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002206 mWaitWorkCV.signal();
2207 }
2208}
2209
2210// static
2211int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
Glenn Kasten0f11b512014-01-31 16:18:54 -08002212 void *param __unused,
Eric Laurentbfb1b832013-01-07 09:53:42 -08002213 void *cookie)
2214{
2215 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
2216 ALOGV("asyncCallback() event %d", event);
2217 switch (event) {
2218 case STREAM_CBK_EVENT_WRITE_READY:
2219 me->writeCallback();
2220 break;
2221 case STREAM_CBK_EVENT_DRAIN_READY:
2222 me->drainCallback();
2223 break;
2224 default:
2225 ALOGW("asyncCallback() unknown event %d", event);
2226 break;
2227 }
2228 return 0;
2229}
2230
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002231void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002232{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002233 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002234 mSampleRate = mOutput->getSampleRate();
2235 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002236 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002237 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002238 }
Andy Hung9a592762014-07-21 21:56:01 -07002239 if ((mType == MIXER || mType == DUPLICATING)
2240 && !isValidPcmSinkChannelMask(mChannelMask)) {
2241 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2242 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002243 }
Andy Hunge5412692014-05-16 11:25:07 -07002244 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002245
2246 // Get actual HAL format.
Andy Hung463be252014-07-10 16:56:07 -07002247 mHALFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Phil Burkca5e6142015-07-14 09:42:29 -07002248 // Get format from the shim, which will be different than the HAL format
2249 // if playing compressed audio over HDMI passthrough.
2250 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002251 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002252 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002253 }
Andy Hung6146c082014-03-18 11:56:15 -07002254 if ((mType == MIXER || mType == DUPLICATING)
2255 && !isValidPcmSinkFormat(mFormat)) {
2256 LOG_FATAL("HAL format %#x not supported for mixed output",
2257 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002258 }
Phil Burk062e67a2015-02-11 13:40:50 -08002259 mFrameSize = mOutput->getFrameSize();
Glenn Kasten70949c42013-08-06 07:40:12 -07002260 mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
2261 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002262 if (mFrameCount & 15) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002263 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002264 mFrameCount);
2265 }
2266
Eric Laurentbfb1b832013-01-07 09:53:42 -08002267 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
2268 (mOutput->stream->set_callback != NULL)) {
2269 if (mOutput->stream->set_callback(mOutput->stream,
2270 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
2271 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002272 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002273 }
2274 }
2275
Eric Laurentd1f69b02014-12-15 14:33:13 -08002276 mHwSupportsPause = false;
2277 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
2278 if (mOutput->stream->pause != NULL) {
2279 if (mOutput->stream->resume != NULL) {
2280 mHwSupportsPause = true;
2281 } else {
2282 ALOGW("direct output implements pause but not resume");
2283 }
2284 } else if (mOutput->stream->resume != NULL) {
2285 ALOGW("direct output implements resume but not pause");
2286 }
2287 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002288 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2289 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2290 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002291
Andy Hungfbfc3952015-01-15 13:33:51 -08002292 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2293 // For best precision, we use float instead of the associated output
2294 // device format (typically PCM 16 bit).
2295
2296 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2297 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2298 mBufferSize = mFrameSize * mFrameCount;
2299
2300 // TODO: We currently use the associated output device channel mask and sample rate.
2301 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2302 // (if a valid mask) to avoid premature downmix.
2303 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2304 // instead of the output device sample rate to avoid loss of high frequency information.
2305 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2306 }
2307
Andy Hung09a50072014-02-27 14:30:47 -08002308 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002309 double multiplier = 1.0;
2310 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2311 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002312 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2313 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Eric Laurent81784c32012-11-19 14:55:58 -08002314 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2315 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2316 maxNormalFrameCount = maxNormalFrameCount & ~15;
2317 if (maxNormalFrameCount < minNormalFrameCount) {
2318 maxNormalFrameCount = minNormalFrameCount;
2319 }
2320 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2321 if (multiplier <= 1.0) {
2322 multiplier = 1.0;
2323 } else if (multiplier <= 2.0) {
2324 if (2 * mFrameCount <= maxNormalFrameCount) {
2325 multiplier = 2.0;
2326 } else {
2327 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2328 }
2329 } else {
2330 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
Andy Hung09a50072014-02-27 14:30:47 -08002331 // 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 -08002332 // track, but we sometimes have to do this to satisfy the maximum frame count
2333 // constraint)
2334 // FIXME this rounding up should not be done if no HAL SRC
2335 uint32_t truncMult = (uint32_t) multiplier;
2336 if ((truncMult & 1)) {
2337 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2338 ++truncMult;
2339 }
2340 }
2341 multiplier = (double) truncMult;
2342 }
2343 }
2344 mNormalFrameCount = multiplier * mFrameCount;
2345 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002346 if (mType == MIXER || mType == DUPLICATING) {
2347 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2348 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002349 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002350 mNormalFrameCount);
2351
Andy Hung08fb1742015-05-31 23:22:10 -07002352 // Check if we want to throttle the processing to no more than 2x normal rate
2353 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002354 mThreadThrottleTimeMs = 0;
2355 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002356 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2357
Andy Hung010a1a12014-03-13 13:57:33 -07002358 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2359 // Originally this was int16_t[] array, need to remove legacy implications.
2360 free(mSinkBuffer);
2361 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002362 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2363 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2364 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002365 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002366
Andy Hung69aed5f2014-02-25 17:24:40 -08002367 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2368 // drives the output.
2369 free(mMixerBuffer);
2370 mMixerBuffer = NULL;
2371 if (mMixerBufferEnabled) {
2372 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2373 mMixerBufferSize = mNormalFrameCount * mChannelCount
2374 * audio_bytes_per_sample(mMixerBufferFormat);
2375 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2376 }
Andy Hung98ef9782014-03-04 14:46:50 -08002377 free(mEffectBuffer);
2378 mEffectBuffer = NULL;
2379 if (mEffectBufferEnabled) {
2380 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2381 mEffectBufferSize = mNormalFrameCount * mChannelCount
2382 * audio_bytes_per_sample(mEffectBufferFormat);
2383 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2384 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002385
Eric Laurent81784c32012-11-19 14:55:58 -08002386 // force reconfiguration of effect chains and engines to take new buffer size and audio
2387 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002388 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002389 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2390 // matter.
2391 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2392 Vector< sp<EffectChain> > effectChains = mEffectChains;
2393 for (size_t i = 0; i < effectChains.size(); i ++) {
2394 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2395 }
2396}
2397
2398
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002399status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002400{
2401 if (halFrames == NULL || dspFrames == NULL) {
2402 return BAD_VALUE;
2403 }
2404 Mutex::Autolock _l(mLock);
2405 if (initCheck() != NO_ERROR) {
2406 return INVALID_OPERATION;
2407 }
Andy Hung818e7a32016-02-16 18:08:07 -08002408 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002409 *halFrames = framesWritten;
2410
2411 if (isSuspended()) {
2412 // return an estimation of rendered frames when the output is suspended
2413 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002414 *dspFrames = (uint32_t)
2415 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002416 return NO_ERROR;
2417 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002418 status_t status;
2419 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002420 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002421 *dspFrames = (size_t)frames;
2422 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002423 }
2424}
2425
Glenn Kastend848eb42016-03-08 13:42:11 -08002426uint32_t AudioFlinger::PlaybackThread::hasAudioSession(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08002427{
2428 Mutex::Autolock _l(mLock);
2429 uint32_t result = 0;
2430 if (getEffectChain_l(sessionId) != 0) {
2431 result = EFFECT_SESSION;
2432 }
2433
2434 for (size_t i = 0; i < mTracks.size(); ++i) {
2435 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002436 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002437 result |= TRACK_SESSION;
2438 break;
2439 }
2440 }
2441
2442 return result;
2443}
2444
Glenn Kastend848eb42016-03-08 13:42:11 -08002445uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08002446{
2447 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2448 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2449 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2450 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2451 }
2452 for (size_t i = 0; i < mTracks.size(); i++) {
2453 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002454 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002455 return AudioSystem::getStrategyForStream(track->streamType());
2456 }
2457 }
2458 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2459}
2460
2461
Phil Burk062e67a2015-02-11 13:40:50 -08002462AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002463{
2464 Mutex::Autolock _l(mLock);
2465 return mOutput;
2466}
2467
Phil Burk062e67a2015-02-11 13:40:50 -08002468AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002469{
2470 Mutex::Autolock _l(mLock);
2471 AudioStreamOut *output = mOutput;
2472 mOutput = NULL;
2473 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2474 // must push a NULL and wait for ack
2475 mOutputSink.clear();
2476 mPipeSink.clear();
2477 mNormalSink.clear();
2478 return output;
2479}
2480
2481// this method must always be called either with ThreadBase mLock held or inside the thread loop
2482audio_stream_t* AudioFlinger::PlaybackThread::stream() const
2483{
2484 if (mOutput == NULL) {
2485 return NULL;
2486 }
2487 return &mOutput->stream->common;
2488}
2489
2490uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2491{
2492 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2493}
2494
2495status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2496{
2497 if (!isValidSyncEvent(event)) {
2498 return BAD_VALUE;
2499 }
2500
2501 Mutex::Autolock _l(mLock);
2502
2503 for (size_t i = 0; i < mTracks.size(); ++i) {
2504 sp<Track> track = mTracks[i];
2505 if (event->triggerSession() == track->sessionId()) {
2506 (void) track->setSyncEvent(event);
2507 return NO_ERROR;
2508 }
2509 }
2510
2511 return NAME_NOT_FOUND;
2512}
2513
2514bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2515{
2516 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2517}
2518
2519void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2520 const Vector< sp<Track> >& tracksToRemove)
2521{
2522 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002523 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002524 for (size_t i = 0 ; i < count ; i++) {
2525 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002526 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002527 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002528 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002529#ifdef ADD_BATTERY_DATA
2530 // to track the speaker usage
2531 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2532#endif
2533 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002534 AudioSystem::releaseOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002535 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002536 }
Eric Laurent81784c32012-11-19 14:55:58 -08002537 }
2538 }
2539 }
Eric Laurent81784c32012-11-19 14:55:58 -08002540}
2541
2542void AudioFlinger::PlaybackThread::checkSilentMode_l()
2543{
2544 if (!mMasterMute) {
2545 char value[PROPERTY_VALUE_MAX];
2546 if (property_get("ro.audio.silent", value, "0") > 0) {
2547 char *endptr;
2548 unsigned long ul = strtoul(value, &endptr, 0);
2549 if (*endptr == '\0' && ul != 0) {
2550 ALOGD("Silence is golden");
2551 // The setprop command will not allow a property to be changed after
2552 // the first time it is set, so we don't have to worry about un-muting.
2553 setMasterMute_l(true);
2554 }
2555 }
2556 }
2557}
2558
2559// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002560ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002561{
2562 // FIXME rewrite to reduce number of system calls
2563 mLastWriteTime = systemTime();
2564 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002565 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002566 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002567
2568 // If an NBAIO sink is present, use it to write the normal mixer's submix
2569 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002570
Andy Hung010a1a12014-03-13 13:57:33 -07002571 const size_t count = mBytesRemaining / mFrameSize;
2572
Simon Wilson2d590962012-11-29 15:18:50 -08002573 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002574 // update the setpoint when AudioFlinger::mScreenState changes
2575 uint32_t screenState = AudioFlinger::mScreenState;
2576 if (screenState != mScreenState) {
2577 mScreenState = screenState;
2578 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2579 if (pipe != NULL) {
2580 pipe->setAvgFrames((mScreenState & 1) ?
2581 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2582 }
2583 }
Andy Hung010a1a12014-03-13 13:57:33 -07002584 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002585 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002586 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002587 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002588 } else {
2589 bytesWritten = framesWritten;
2590 }
2591 // otherwise use the HAL / AudioStreamOut directly
2592 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002593 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002594
Eric Laurentbfb1b832013-01-07 09:53:42 -08002595 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002596 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2597 mWriteAckSequence += 2;
2598 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002599 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002600 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002601 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002602 // FIXME We should have an implementation of timestamps for direct output threads.
2603 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002604 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurent51716182016-02-29 18:00:56 -08002605
Eric Laurentbfb1b832013-01-07 09:53:42 -08002606 if (mUseAsyncWrite &&
2607 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2608 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002609 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002610 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002611 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002612 }
Eric Laurent81784c32012-11-19 14:55:58 -08002613 }
2614
Eric Laurent81784c32012-11-19 14:55:58 -08002615 mNumWrites++;
2616 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002617 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002618 return bytesWritten;
2619}
2620
2621void AudioFlinger::PlaybackThread::threadLoop_drain()
2622{
2623 if (mOutput->stream->drain) {
2624 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2625 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002626 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2627 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002628 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002629 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002630 }
2631 mOutput->stream->drain(mOutput->stream,
2632 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2633 : AUDIO_DRAIN_ALL);
2634 }
2635}
2636
2637void AudioFlinger::PlaybackThread::threadLoop_exit()
2638{
Eric Laurent275e8e92014-11-30 15:14:47 -08002639 {
2640 Mutex::Autolock _l(mLock);
2641 for (size_t i = 0; i < mTracks.size(); i++) {
2642 sp<Track> track = mTracks[i];
2643 track->invalidate();
2644 }
2645 }
Eric Laurent81784c32012-11-19 14:55:58 -08002646}
2647
2648/*
2649The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002650 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002651 - mActiveSleepTimeUs from activeSleepTimeUs()
2652 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08002653 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
2654 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08002655 - maxPeriod from frame count and sample rate (MIXER only)
2656
2657The parameters that affect these derived values are:
2658 - frame count
2659 - frame size
2660 - sample rate
2661 - device type: A2DP or not
2662 - device latency
2663 - format: PCM or not
2664 - active sleep time
2665 - idle sleep time
2666*/
2667
2668void AudioFlinger::PlaybackThread::cacheParameters_l()
2669{
Andy Hung25c2dac2014-02-27 14:56:00 -08002670 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002671 mActiveSleepTimeUs = activeSleepTimeUs();
2672 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08002673
2674 // make sure standby delay is not too short when connected to an A2DP sink to avoid
2675 // truncating audio when going to standby.
2676 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
2677 if ((mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != 0) {
2678 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
2679 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
2680 }
2681 }
Eric Laurent81784c32012-11-19 14:55:58 -08002682}
2683
2684void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2685{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002686 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08002687 this, streamType, mTracks.size());
2688 Mutex::Autolock _l(mLock);
2689
2690 size_t size = mTracks.size();
2691 for (size_t i = 0; i < size; i++) {
2692 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07002693 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002694 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08002695 }
2696 }
2697}
2698
2699status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2700{
Glenn Kastend848eb42016-03-08 13:42:11 -08002701 audio_session_t session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002702 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2703 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002704 bool ownsBuffer = false;
2705
2706 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Glenn Kastend848eb42016-03-08 13:42:11 -08002707 if (session > AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002708 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002709 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002710 if (mType != DIRECT) {
2711 size_t numSamples = mNormalFrameCount * mChannelCount;
2712 buffer = new int16_t[numSamples];
2713 memset(buffer, 0, numSamples * sizeof(int16_t));
2714 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2715 ownsBuffer = true;
2716 }
2717
2718 // Attach all tracks with same session ID to this chain.
2719 for (size_t i = 0; i < mTracks.size(); ++i) {
2720 sp<Track> track = mTracks[i];
2721 if (session == track->sessionId()) {
2722 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2723 buffer);
2724 track->setMainBuffer(buffer);
2725 chain->incTrackCnt();
2726 }
2727 }
2728
2729 // indicate all active tracks in the chain
2730 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2731 sp<Track> track = mActiveTracks[i].promote();
2732 if (track == 0) {
2733 continue;
2734 }
2735 if (session == track->sessionId()) {
2736 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2737 chain->incActiveTrackCnt();
2738 }
2739 }
2740 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002741 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08002742 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002743 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2744 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002745 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Glenn Kastend848eb42016-03-08 13:42:11 -08002746 // chains list in order to be processed last as it contains output stage effects.
Eric Laurent81784c32012-11-19 14:55:58 -08002747 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2748 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08002749 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08002750 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08002751 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08002752 // Effect chain for other sessions are inserted at beginning of effect
2753 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08002754 // sessions is not important.
2755 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
2756 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX,
2757 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08002758 size_t size = mEffectChains.size();
2759 size_t i = 0;
2760 for (i = 0; i < size; i++) {
2761 if (mEffectChains[i]->sessionId() < session) {
2762 break;
2763 }
2764 }
2765 mEffectChains.insertAt(chain, i);
2766 checkSuspendOnAddEffectChain_l(chain);
2767
2768 return NO_ERROR;
2769}
2770
2771size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2772{
Glenn Kastend848eb42016-03-08 13:42:11 -08002773 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08002774
2775 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2776
2777 for (size_t i = 0; i < mEffectChains.size(); i++) {
2778 if (chain == mEffectChains[i]) {
2779 mEffectChains.removeAt(i);
2780 // detach all active tracks from the chain
2781 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2782 sp<Track> track = mActiveTracks[i].promote();
2783 if (track == 0) {
2784 continue;
2785 }
2786 if (session == track->sessionId()) {
2787 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2788 chain.get(), session);
2789 chain->decActiveTrackCnt();
2790 }
2791 }
2792
2793 // detach all tracks with same session ID from this chain
2794 for (size_t i = 0; i < mTracks.size(); ++i) {
2795 sp<Track> track = mTracks[i];
2796 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002797 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002798 chain->decTrackCnt();
2799 }
2800 }
2801 break;
2802 }
2803 }
2804 return mEffectChains.size();
2805}
2806
2807status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2808 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2809{
2810 Mutex::Autolock _l(mLock);
2811 return attachAuxEffect_l(track, EffectId);
2812}
2813
2814status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2815 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2816{
2817 status_t status = NO_ERROR;
2818
2819 if (EffectId == 0) {
2820 track->setAuxBuffer(0, NULL);
2821 } else {
2822 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2823 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2824 if (effect != 0) {
2825 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2826 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2827 } else {
2828 status = INVALID_OPERATION;
2829 }
2830 } else {
2831 status = BAD_VALUE;
2832 }
2833 }
2834 return status;
2835}
2836
2837void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2838{
2839 for (size_t i = 0; i < mTracks.size(); ++i) {
2840 sp<Track> track = mTracks[i];
2841 if (track->auxEffectId() == effectId) {
2842 attachAuxEffect_l(track, 0);
2843 }
2844 }
2845}
2846
2847bool AudioFlinger::PlaybackThread::threadLoop()
2848{
2849 Vector< sp<Track> > tracksToRemove;
2850
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002851 mStandbyTimeNs = systemTime();
Eric Laurent81784c32012-11-19 14:55:58 -08002852
2853 // MIXER
2854 nsecs_t lastWarning = 0;
2855
2856 // DUPLICATING
2857 // FIXME could this be made local to while loop?
2858 writeFrames = 0;
2859
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002860 int lastGeneration = 0;
2861
Eric Laurent81784c32012-11-19 14:55:58 -08002862 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002863 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002864
2865 if (mType == MIXER) {
2866 sleepTimeShift = 0;
2867 }
2868
2869 CpuStats cpuStats;
2870 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2871
2872 acquireWakeLock();
2873
Glenn Kasten9e58b552013-01-18 15:09:48 -08002874 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2875 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2876 // and then that string will be logged at the next convenient opportunity.
2877 const char *logString = NULL;
2878
Eric Laurent664539d2013-09-23 18:24:31 -07002879 checkSilentMode_l();
2880
Eric Laurent81784c32012-11-19 14:55:58 -08002881 while (!exitPending())
2882 {
2883 cpuStats.sample(myName);
2884
2885 Vector< sp<EffectChain> > effectChains;
2886
Eric Laurent81784c32012-11-19 14:55:58 -08002887 { // scope for mLock
2888
2889 Mutex::Autolock _l(mLock);
2890
Eric Laurent021cf962014-05-13 10:18:14 -07002891 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002892
Glenn Kasten9e58b552013-01-18 15:09:48 -08002893 if (logString != NULL) {
2894 mNBLogWriter->logTimestamp();
2895 mNBLogWriter->log(logString);
2896 logString = NULL;
2897 }
2898
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002899 // Gather the framesReleased counters for all active tracks,
Andy Hunge10393e2015-06-12 13:59:33 -07002900 // and associate with the sink frames written out. We need
2901 // this to convert the sink timestamp to the track timestamp.
2902 if (mNormalSink != 0) {
Andy Hungc54b1ff2016-02-23 14:07:07 -08002903 // Note: The DuplicatingThread may not have a mNormalSink.
Andy Hung818e7a32016-02-16 18:08:07 -08002904 // We always fetch the timestamp here because often the downstream
2905 // sink will block whie writing.
2906 ExtendedTimestamp timestamp; // use private copy to fetch
2907 (void) mNormalSink->getTimestamp(timestamp);
2908 // copy over kernel info
2909 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
2910 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
2911 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
2912 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hungc54b1ff2016-02-23 14:07:07 -08002913 }
2914 // mFramesWritten for non-offloaded tracks are contiguous
2915 // even after standby() is called. This is useful for the track frame
2916 // to sink frame mapping.
2917 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
2918 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
2919 const size_t size = mActiveTracks.size();
2920 for (size_t i = 0; i < size; ++i) {
2921 sp<Track> t = mActiveTracks[i].promote();
2922 if (t != 0 && !t->isFastTrack()) {
2923 t->updateTrackFrameInfo(
2924 t->mAudioTrackServerProxy->framesReleased(),
2925 mFramesWritten,
2926 mTimestamp);
Andy Hunge10393e2015-06-12 13:59:33 -07002927 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002928 }
2929
Eric Laurent81784c32012-11-19 14:55:58 -08002930 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002931 if (mSignalPending) {
2932 // A signal was raised while we were unlocked
2933 mSignalPending = false;
2934 } else if (waitingAsyncCallback_l()) {
2935 if (exitPending()) {
2936 break;
2937 }
Marco Nelissen078538c2015-05-12 09:17:57 -07002938 bool released = false;
2939 // The following works around a bug in the offload driver. Ideally we would release
2940 // the wake lock every time, but that causes the last offload buffer(s) to be
2941 // dropped while the device is on battery, so we need to hold a wake lock during
2942 // the drain phase.
2943 if (mBytesRemaining && !(mDrainSequence & 1)) {
2944 releaseWakeLock_l();
2945 released = true;
2946 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002947 mWakeLockUids.clear();
2948 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002949 ALOGV("wait async completion");
2950 mWaitWorkCV.wait(mLock);
2951 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07002952 if (released) {
2953 acquireWakeLock_l();
2954 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002955 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
2956 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002957
2958 continue;
2959 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002960 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002961 isSuspended()) {
2962 // put audio hardware into standby after short delay
2963 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002964
2965 threadLoop_standby();
2966
2967 mStandby = true;
2968 }
2969
2970 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2971 // we're about to wait, flush the binder command buffer
2972 IPCThreadState::self()->flushCommands();
2973
2974 clearOutputTracks();
2975
2976 if (exitPending()) {
2977 break;
2978 }
2979
2980 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002981 mWakeLockUids.clear();
2982 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002983 // wait until we have something to do...
2984 ALOGV("%s going to sleep", myName.string());
2985 mWaitWorkCV.wait(mLock);
2986 ALOGV("%s waking up", myName.string());
2987 acquireWakeLock_l();
2988
2989 mMixerStatus = MIXER_IDLE;
2990 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2991 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002992 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002993 checkSilentMode_l();
2994
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002995 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
2996 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002997 if (mType == MIXER) {
2998 sleepTimeShift = 0;
2999 }
3000
3001 continue;
3002 }
3003 }
Eric Laurent81784c32012-11-19 14:55:58 -08003004 // mMixerStatusIgnoringFastTracks is also updated internally
3005 mMixerStatus = prepareTracks_l(&tracksToRemove);
3006
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003007 // compare with previously applied list
3008 if (lastGeneration != mActiveTracksGeneration) {
3009 // update wakelock
3010 updateWakeLockUids_l(mWakeLockUids);
3011 lastGeneration = mActiveTracksGeneration;
3012 }
3013
Eric Laurent81784c32012-11-19 14:55:58 -08003014 // prevent any changes in effect chain list and in each effect chain
3015 // during mixing and effect process as the audio buffers could be deleted
3016 // or modified if an effect is created or deleted
3017 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003018 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003019
Eric Laurentbfb1b832013-01-07 09:53:42 -08003020 if (mBytesRemaining == 0) {
3021 mCurrentWriteLength = 0;
3022 if (mMixerStatus == MIXER_TRACKS_READY) {
3023 // threadLoop_mix() sets mCurrentWriteLength
3024 threadLoop_mix();
3025 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3026 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003027 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003028 // must be written to HAL
3029 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003030 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003031 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003032 }
3033 }
Andy Hung98ef9782014-03-04 14:46:50 -08003034 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003035 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003036 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3037 // or mSinkBuffer (if there are no effects).
3038 //
3039 // This is done pre-effects computation; if effects change to
3040 // support higher precision, this needs to move.
3041 //
3042 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003043 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003044 if (mMixerBufferValid) {
3045 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3046 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3047
Andy Hung2ddee192015-12-18 17:34:44 -08003048 // mono blend occurs for mixer threads only (not direct or offloaded)
3049 // and is handled here if we're going directly to the sink.
3050 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003051 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3052 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003053 }
3054
Andy Hung98ef9782014-03-04 14:46:50 -08003055 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
3056 mNormalFrameCount * mChannelCount);
3057 }
3058
Eric Laurentbfb1b832013-01-07 09:53:42 -08003059 mBytesRemaining = mCurrentWriteLength;
3060 if (isSuspended()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003061 mSleepTimeUs = suspendSleepTimeUs();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003062 // simulate write to HAL when suspended
Andy Hung25c2dac2014-02-27 14:56:00 -08003063 mBytesWritten += mSinkBufferSize;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003064 mFramesWritten += mSinkBufferSize / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003065 mBytesRemaining = 0;
3066 }
Eric Laurent81784c32012-11-19 14:55:58 -08003067
Eric Laurentbfb1b832013-01-07 09:53:42 -08003068 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003069 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003070 for (size_t i = 0; i < effectChains.size(); i ++) {
3071 effectChains[i]->process_l();
3072 }
Eric Laurent81784c32012-11-19 14:55:58 -08003073 }
3074 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003075 // Process effect chains for offloaded thread even if no audio
3076 // was read from audio track: process only updates effect state
3077 // and thus does have to be synchronized with audio writes but may have
3078 // to be called while waiting for async write callback
3079 if (mType == OFFLOAD) {
3080 for (size_t i = 0; i < effectChains.size(); i ++) {
3081 effectChains[i]->process_l();
3082 }
3083 }
Eric Laurent81784c32012-11-19 14:55:58 -08003084
Andy Hung98ef9782014-03-04 14:46:50 -08003085 // Only if the Effects buffer is enabled and there is data in the
3086 // Effects buffer (buffer valid), we need to
3087 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003088 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003089 if (mEffectBufferValid) {
3090 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003091
3092 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003093 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3094 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003095 }
3096
Andy Hung98ef9782014-03-04 14:46:50 -08003097 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
3098 mNormalFrameCount * mChannelCount);
3099 }
3100
Eric Laurent81784c32012-11-19 14:55:58 -08003101 // enable changes in effect chain
3102 unlockEffectChains(effectChains);
3103
Eric Laurentbfb1b832013-01-07 09:53:42 -08003104 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003105 // mSleepTimeUs == 0 means we must write to audio hardware
3106 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003107 ssize_t ret = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003108 if (mBytesRemaining) {
Andy Hung08fb1742015-05-31 23:22:10 -07003109 ret = threadLoop_write();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003110 if (ret < 0) {
3111 mBytesRemaining = 0;
3112 } else {
3113 mBytesWritten += ret;
3114 mBytesRemaining -= ret;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003115 mFramesWritten += ret / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003116 }
3117 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3118 (mMixerStatus == MIXER_DRAIN_ALL)) {
3119 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003120 }
Andy Hung08fb1742015-05-31 23:22:10 -07003121 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003122 // write blocked detection
3123 nsecs_t now = systemTime();
3124 nsecs_t delta = now - mLastWriteTime;
Andy Hung08fb1742015-05-31 23:22:10 -07003125 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003126 mNumDelayedWrites++;
3127 if ((now - lastWarning) > kWarningThrottleNs) {
3128 ATRACE_NAME("underrun");
3129 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003130 (unsigned long long) ns2ms(delta), mNumDelayedWrites, this);
Glenn Kasten4944acb2013-08-19 08:39:20 -07003131 lastWarning = now;
3132 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003133 }
Andy Hung08fb1742015-05-31 23:22:10 -07003134
3135 if (mThreadThrottle
3136 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
3137 && ret > 0) { // we wrote something
3138 // Limit MixerThread data processing to no more than twice the
3139 // expected processing rate.
3140 //
3141 // This helps prevent underruns with NuPlayer and other applications
3142 // which may set up buffers that are close to the minimum size, or use
3143 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3144 //
3145 // The throttle smooths out sudden large data drains from the device,
3146 // e.g. when it comes out of standby, which often causes problems with
3147 // (1) mixer threads without a fast mixer (which has its own warm-up)
3148 // (2) minimum buffer sized tracks (even if the track is full,
3149 // the app won't fill fast enough to handle the sudden draw).
3150
3151 const int32_t deltaMs = delta / 1000000;
3152 const int32_t throttleMs = mHalfBufferMs - deltaMs;
3153 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3154 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003155 // notify of throttle start on verbose log
3156 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3157 "mixer(%p) throttle begin:"
3158 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003159 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003160 mThreadThrottleTimeMs += throttleMs;
3161 } else {
3162 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3163 if (diff > 0) {
3164 // notify of throttle end on debug log
3165 ALOGD("mixer(%p) throttle end: throttle time(%u)", this, diff);
3166 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3167 }
Andy Hung08fb1742015-05-31 23:22:10 -07003168 }
3169 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003170 }
Eric Laurent81784c32012-11-19 14:55:58 -08003171
Eric Laurentbfb1b832013-01-07 09:53:42 -08003172 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003173 ATRACE_BEGIN("sleep");
Eric Laurent51716182016-02-29 18:00:56 -08003174 if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
3175 Mutex::Autolock _l(mLock);
3176 if (!mSignalPending && !exitPending()) {
3177 // Do not sleep more than one buffer duration since last write and not
3178 // less than kDirectMinSleepTimeUs
3179 // Wake up if a command is received
3180 nsecs_t now = systemTime();
3181 uint32_t deltaUs = (uint32_t)((now - mLastWriteTime) / 1000);
3182 uint32_t timeoutUs = mSleepTimeUs;
3183 if (timeoutUs + deltaUs > mBufferDurationUs) {
3184 if (mBufferDurationUs > deltaUs) {
3185 timeoutUs = mBufferDurationUs - deltaUs;
3186 if (timeoutUs < kDirectMinSleepTimeUs) {
3187 timeoutUs = kDirectMinSleepTimeUs;
3188 }
3189 } else {
3190 timeoutUs = kDirectMinSleepTimeUs;
3191 }
3192 }
3193 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)timeoutUs));
3194 }
3195 } else {
3196 usleep(mSleepTimeUs);
3197 }
Glenn Kastene7754022014-10-31 12:11:26 -07003198 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003199 }
Eric Laurent81784c32012-11-19 14:55:58 -08003200 }
3201
3202 // Finally let go of removed track(s), without the lock held
3203 // since we can't guarantee the destructors won't acquire that
3204 // same lock. This will also mutate and push a new fast mixer state.
3205 threadLoop_removeTracks(tracksToRemove);
3206 tracksToRemove.clear();
3207
3208 // FIXME I don't understand the need for this here;
3209 // it was in the original code but maybe the
3210 // assignment in saveOutputTracks() makes this unnecessary?
3211 clearOutputTracks();
3212
3213 // Effect chains will be actually deleted here if they were removed from
3214 // mEffectChains list during mixing or effects processing
3215 effectChains.clear();
3216
3217 // FIXME Note that the above .clear() is no longer necessary since effectChains
3218 // is now local to this block, but will keep it for now (at least until merge done).
3219 }
3220
Eric Laurentbfb1b832013-01-07 09:53:42 -08003221 threadLoop_exit();
3222
Eric Laurentcf817a22014-08-04 20:36:31 -07003223 if (!mStandby) {
3224 threadLoop_standby();
3225 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003226 }
3227
3228 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003229 mWakeLockUids.clear();
3230 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08003231
3232 ALOGV("Thread %p type %d exiting", this, mType);
3233 return false;
3234}
3235
Eric Laurentbfb1b832013-01-07 09:53:42 -08003236// removeTracks_l() must be called with ThreadBase::mLock held
3237void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3238{
3239 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003240 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003241 for (size_t i=0 ; i<count ; i++) {
3242 const sp<Track>& track = tracksToRemove.itemAt(i);
3243 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003244 mWakeLockUids.remove(track->uid());
3245 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003246 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3247 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3248 if (chain != 0) {
3249 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3250 track->sessionId());
3251 chain->decActiveTrackCnt();
3252 }
3253 if (track->isTerminated()) {
3254 removeTrack_l(track);
3255 }
3256 }
3257 }
3258
3259}
Eric Laurent81784c32012-11-19 14:55:58 -08003260
Eric Laurentaccc1472013-09-20 09:36:34 -07003261status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3262{
3263 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08003264 ExtendedTimestamp ets;
3265 status_t status = mNormalSink->getTimestamp(ets);
3266 if (status == NO_ERROR) {
3267 status = ets.getBestTimestamp(&timestamp);
3268 }
3269 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07003270 }
Andy Hung9a1c8892014-12-03 11:37:42 -08003271 if ((mType == OFFLOAD || mType == DIRECT)
3272 && mOutput != NULL && mOutput->stream->get_presentation_position) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003273 uint64_t position64;
Phil Burk062e67a2015-02-11 13:40:50 -08003274 int ret = mOutput->getPresentationPosition(&position64, &timestamp.mTime);
Eric Laurentaccc1472013-09-20 09:36:34 -07003275 if (ret == 0) {
3276 timestamp.mPosition = (uint32_t)position64;
3277 return NO_ERROR;
3278 }
3279 }
3280 return INVALID_OPERATION;
3281}
Eric Laurent1c333e22014-05-20 10:48:17 -07003282
Eric Laurent054d9d32015-04-24 08:48:48 -07003283status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3284 audio_patch_handle_t *handle)
3285{
3286 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3287 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3288 if (mFastMixer != 0) {
3289 FastMixerStateQueue *sq = mFastMixer->sq();
3290 FastMixerState *state = sq->begin();
3291 if (!(state->mCommand & FastMixerState::IDLE)) {
3292 previousCommand = state->mCommand;
3293 state->mCommand = FastMixerState::HOT_IDLE;
3294 sq->end();
3295 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3296 } else {
3297 sq->end(false /*didModify*/);
3298 }
3299 }
3300 status_t status = PlaybackThread::createAudioPatch_l(patch, handle);
3301
3302 if (!(previousCommand & FastMixerState::IDLE)) {
3303 ALOG_ASSERT(mFastMixer != 0);
3304 FastMixerStateQueue *sq = mFastMixer->sq();
3305 FastMixerState *state = sq->begin();
3306 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3307 state->mCommand = previousCommand;
3308 sq->end();
3309 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3310 }
3311
3312 return status;
3313}
3314
Eric Laurent1c333e22014-05-20 10:48:17 -07003315status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3316 audio_patch_handle_t *handle)
3317{
3318 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003319
3320 // store new device and send to effects
3321 audio_devices_t type = AUDIO_DEVICE_NONE;
3322 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3323 type |= patch->sinks[i].ext.device.type;
3324 }
3325
3326#ifdef ADD_BATTERY_DATA
3327 // when changing the audio output device, call addBatteryData to notify
3328 // the change
3329 if (mOutDevice != type) {
3330 uint32_t params = 0;
3331 // check whether speaker is on
3332 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3333 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003334 }
3335
Eric Laurent054d9d32015-04-24 08:48:48 -07003336 audio_devices_t deviceWithoutSpeaker
3337 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3338 // check if any other device (except speaker) is on
3339 if (type & deviceWithoutSpeaker) {
3340 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3341 }
3342
3343 if (params != 0) {
3344 addBatteryData(params);
3345 }
3346 }
3347#endif
3348
3349 for (size_t i = 0; i < mEffectChains.size(); i++) {
3350 mEffectChains[i]->setDevice_l(type);
3351 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003352
3353 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3354 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3355 bool configChanged = mPrevOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003356 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003357 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003358
3359 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003360 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3361 status = hwDevice->create_audio_patch(hwDevice,
3362 patch->num_sources,
3363 patch->sources,
3364 patch->num_sinks,
3365 patch->sinks,
3366 handle);
3367 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003368 char *address;
3369 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3370 //FIXME: we only support address on first sink with HAL version < 3.0
3371 address = audio_device_address_to_parameter(
3372 patch->sinks[0].ext.device.type,
3373 patch->sinks[0].ext.device.address);
3374 } else {
3375 address = (char *)calloc(1, 1);
3376 }
3377 AudioParameter param = AudioParameter(String8(address));
3378 free(address);
3379 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), (int)type);
3380 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3381 param.toString().string());
3382 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003383 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003384 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003385 mPrevOutDevice = type;
Eric Laurente8726fe2015-06-26 09:39:24 -07003386 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3387 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003388 return status;
3389}
3390
Eric Laurent054d9d32015-04-24 08:48:48 -07003391status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3392{
3393 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3394 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3395 if (mFastMixer != 0) {
3396 FastMixerStateQueue *sq = mFastMixer->sq();
3397 FastMixerState *state = sq->begin();
3398 if (!(state->mCommand & FastMixerState::IDLE)) {
3399 previousCommand = state->mCommand;
3400 state->mCommand = FastMixerState::HOT_IDLE;
3401 sq->end();
3402 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3403 } else {
3404 sq->end(false /*didModify*/);
3405 }
3406 }
3407
3408 status_t status = PlaybackThread::releaseAudioPatch_l(handle);
3409
3410 if (!(previousCommand & FastMixerState::IDLE)) {
3411 ALOG_ASSERT(mFastMixer != 0);
3412 FastMixerStateQueue *sq = mFastMixer->sq();
3413 FastMixerState *state = sq->begin();
3414 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3415 state->mCommand = previousCommand;
3416 sq->end();
3417 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3418 }
3419
3420 return status;
3421}
3422
Eric Laurent1c333e22014-05-20 10:48:17 -07003423status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3424{
3425 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003426
3427 mOutDevice = AUDIO_DEVICE_NONE;
3428
Eric Laurent1c333e22014-05-20 10:48:17 -07003429 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
3430 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3431 status = hwDevice->release_audio_patch(hwDevice, handle);
3432 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003433 AudioParameter param;
3434 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
3435 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3436 param.toString().string());
Eric Laurent1c333e22014-05-20 10:48:17 -07003437 }
3438 return status;
3439}
3440
Eric Laurent83b88082014-06-20 18:31:16 -07003441void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3442{
3443 Mutex::Autolock _l(mLock);
3444 mTracks.add(track);
3445}
3446
3447void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3448{
3449 Mutex::Autolock _l(mLock);
3450 destroyTrack_l(track);
3451}
3452
3453void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3454{
3455 ThreadBase::getAudioPortConfig(config);
3456 config->role = AUDIO_PORT_ROLE_SOURCE;
3457 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3458 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3459}
3460
Eric Laurent81784c32012-11-19 14:55:58 -08003461// ----------------------------------------------------------------------------
3462
3463AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003464 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3465 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003466 // mAudioMixer below
3467 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08003468 mFastMixerFutex(0),
3469 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08003470 // mOutputSink below
3471 // mPipeSink below
3472 // mNormalSink below
3473{
3474 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003475 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%zu, "
3476 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003477 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3478 mNormalFrameCount);
3479 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3480
Andy Hungfbfc3952015-01-15 13:33:51 -08003481 if (type == DUPLICATING) {
3482 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3483 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3484 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3485 return;
3486 }
Eric Laurent81784c32012-11-19 14:55:58 -08003487 // create an NBAIO sink for the HAL output stream, and negotiate
3488 mOutputSink = new AudioStreamOutSink(output->stream);
3489 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003490 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003491#if !LOG_NDEBUG
3492 ssize_t index =
3493#else
3494 (void)
3495#endif
3496 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003497 ALOG_ASSERT(index == 0);
3498
3499 // initialize fast mixer depending on configuration
3500 bool initFastMixer;
3501 switch (kUseFastMixer) {
3502 case FastMixer_Never:
3503 initFastMixer = false;
3504 break;
3505 case FastMixer_Always:
3506 initFastMixer = true;
3507 break;
3508 case FastMixer_Static:
3509 case FastMixer_Dynamic:
3510 initFastMixer = mFrameCount < mNormalFrameCount;
3511 break;
3512 }
3513 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003514 audio_format_t fastMixerFormat;
3515 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3516 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3517 } else {
3518 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3519 }
3520 if (mFormat != fastMixerFormat) {
3521 // change our Sink format to accept our intermediate precision
3522 mFormat = fastMixerFormat;
3523 free(mSinkBuffer);
3524 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3525 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3526 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3527 }
Eric Laurent81784c32012-11-19 14:55:58 -08003528
3529 // create a MonoPipe to connect our submix to FastMixer
3530 NBAIO_Format format = mOutputSink->format();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003531#ifdef TEE_SINK
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003532 NBAIO_Format origformat = format;
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003533#endif
Andy Hung1258c1a2014-05-23 21:22:17 -07003534 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07003535 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003536 format.mFormat = fastMixerFormat;
3537 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3538
Eric Laurent81784c32012-11-19 14:55:58 -08003539 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3540 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3541 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3542 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3543 const NBAIO_Format offers[1] = {format};
3544 size_t numCounterOffers = 0;
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003545#if !LOG_NDEBUG
3546 ssize_t index =
3547#else
3548 (void)
3549#endif
3550 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003551 ALOG_ASSERT(index == 0);
3552 monoPipe->setAvgFrames((mScreenState & 1) ?
3553 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3554 mPipeSink = monoPipe;
3555
Glenn Kasten46909e72013-02-26 09:20:22 -08003556#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003557 if (mTeeSinkOutputEnabled) {
3558 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003559 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3560 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003561 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003562 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003563 ALOG_ASSERT(index == 0);
3564 mTeeSink = teeSink;
3565 PipeReader *teeSource = new PipeReader(*teeSink);
3566 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003567 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003568 ALOG_ASSERT(index == 0);
3569 mTeeSource = teeSource;
3570 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003571#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003572
3573 // create fast mixer and configure it initially with just one fast track for our submix
3574 mFastMixer = new FastMixer();
3575 FastMixerStateQueue *sq = mFastMixer->sq();
3576#ifdef STATE_QUEUE_DUMP
3577 sq->setObserverDump(&mStateQueueObserverDump);
3578 sq->setMutatorDump(&mStateQueueMutatorDump);
3579#endif
3580 FastMixerState *state = sq->begin();
3581 FastTrack *fastTrack = &state->mFastTracks[0];
3582 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3583 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3584 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003585 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3586 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003587 fastTrack->mGeneration++;
3588 state->mFastTracksGen++;
3589 state->mTrackMask = 1;
3590 // fast mixer will use the HAL output sink
3591 state->mOutputSink = mOutputSink.get();
3592 state->mOutputSinkGen++;
3593 state->mFrameCount = mFrameCount;
3594 state->mCommand = FastMixerState::COLD_IDLE;
3595 // already done in constructor initialization list
3596 //mFastMixerFutex = 0;
3597 state->mColdFutexAddr = &mFastMixerFutex;
3598 state->mColdGen++;
3599 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003600#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003601 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003602#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003603 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3604 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003605 sq->end();
3606 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3607
3608 // start the fast mixer
3609 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3610 pid_t tid = mFastMixer->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003611 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003612
3613#ifdef AUDIO_WATCHDOG
3614 // create and start the watchdog
3615 mAudioWatchdog = new AudioWatchdog();
3616 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3617 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3618 tid = mAudioWatchdog->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003619 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003620#endif
3621
Eric Laurent81784c32012-11-19 14:55:58 -08003622 }
3623
3624 switch (kUseFastMixer) {
3625 case FastMixer_Never:
3626 case FastMixer_Dynamic:
3627 mNormalSink = mOutputSink;
3628 break;
3629 case FastMixer_Always:
3630 mNormalSink = mPipeSink;
3631 break;
3632 case FastMixer_Static:
3633 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3634 break;
3635 }
3636}
3637
3638AudioFlinger::MixerThread::~MixerThread()
3639{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003640 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003641 FastMixerStateQueue *sq = mFastMixer->sq();
3642 FastMixerState *state = sq->begin();
3643 if (state->mCommand == FastMixerState::COLD_IDLE) {
3644 int32_t old = android_atomic_inc(&mFastMixerFutex);
3645 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003646 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003647 }
3648 }
3649 state->mCommand = FastMixerState::EXIT;
3650 sq->end();
3651 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3652 mFastMixer->join();
3653 // Though the fast mixer thread has exited, it's state queue is still valid.
3654 // We'll use that extract the final state which contains one remaining fast track
3655 // corresponding to our sub-mix.
3656 state = sq->begin();
3657 ALOG_ASSERT(state->mTrackMask == 1);
3658 FastTrack *fastTrack = &state->mFastTracks[0];
3659 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3660 delete fastTrack->mBufferProvider;
3661 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003662 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003663#ifdef AUDIO_WATCHDOG
3664 if (mAudioWatchdog != 0) {
3665 mAudioWatchdog->requestExit();
3666 mAudioWatchdog->requestExitAndWait();
3667 mAudioWatchdog.clear();
3668 }
3669#endif
3670 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003671 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003672 delete mAudioMixer;
3673}
3674
3675
3676uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3677{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003678 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003679 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3680 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3681 }
3682 return latency;
3683}
3684
3685
3686void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3687{
3688 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3689}
3690
Eric Laurentbfb1b832013-01-07 09:53:42 -08003691ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003692{
3693 // FIXME we should only do one push per cycle; confirm this is true
3694 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003695 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003696 FastMixerStateQueue *sq = mFastMixer->sq();
3697 FastMixerState *state = sq->begin();
3698 if (state->mCommand != FastMixerState::MIX_WRITE &&
3699 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3700 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07003701
3702 // FIXME workaround for first HAL write being CPU bound on some devices
3703 ATRACE_BEGIN("write");
3704 mOutput->write((char *)mSinkBuffer, 0);
3705 ATRACE_END();
3706
Eric Laurent81784c32012-11-19 14:55:58 -08003707 int32_t old = android_atomic_inc(&mFastMixerFutex);
3708 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003709 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003710 }
3711#ifdef AUDIO_WATCHDOG
3712 if (mAudioWatchdog != 0) {
3713 mAudioWatchdog->resume();
3714 }
3715#endif
3716 }
3717 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003718#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003719 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003720 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003721#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003722 sq->end();
3723 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3724 if (kUseFastMixer == FastMixer_Dynamic) {
3725 mNormalSink = mPipeSink;
3726 }
3727 } else {
3728 sq->end(false /*didModify*/);
3729 }
3730 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003731 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003732}
3733
3734void AudioFlinger::MixerThread::threadLoop_standby()
3735{
3736 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003737 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003738 FastMixerStateQueue *sq = mFastMixer->sq();
3739 FastMixerState *state = sq->begin();
3740 if (!(state->mCommand & FastMixerState::IDLE)) {
3741 state->mCommand = FastMixerState::COLD_IDLE;
3742 state->mColdFutexAddr = &mFastMixerFutex;
3743 state->mColdGen++;
3744 mFastMixerFutex = 0;
3745 sq->end();
3746 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3747 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3748 if (kUseFastMixer == FastMixer_Dynamic) {
3749 mNormalSink = mOutputSink;
3750 }
3751#ifdef AUDIO_WATCHDOG
3752 if (mAudioWatchdog != 0) {
3753 mAudioWatchdog->pause();
3754 }
3755#endif
3756 } else {
3757 sq->end(false /*didModify*/);
3758 }
3759 }
3760 PlaybackThread::threadLoop_standby();
3761}
3762
Eric Laurentbfb1b832013-01-07 09:53:42 -08003763bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3764{
3765 return false;
3766}
3767
3768bool AudioFlinger::PlaybackThread::shouldStandby_l()
3769{
3770 return !mStandby;
3771}
3772
3773bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3774{
3775 Mutex::Autolock _l(mLock);
3776 return waitingAsyncCallback_l();
3777}
3778
Eric Laurent81784c32012-11-19 14:55:58 -08003779// shared by MIXER and DIRECT, overridden by DUPLICATING
3780void AudioFlinger::PlaybackThread::threadLoop_standby()
3781{
3782 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08003783 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003784 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003785 // discard any pending drain or write ack by incrementing sequence
3786 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3787 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003788 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003789 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3790 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003791 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003792 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003793}
3794
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003795void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3796{
3797 ALOGV("signal playback thread");
3798 broadcast_l();
3799}
3800
Eric Laurent81784c32012-11-19 14:55:58 -08003801void AudioFlinger::MixerThread::threadLoop_mix()
3802{
Eric Laurent81784c32012-11-19 14:55:58 -08003803 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08003804 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08003805 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003806 // increase sleep time progressively when application underrun condition clears.
3807 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3808 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3809 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003810 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003811 sleepTimeShift--;
3812 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003813 mSleepTimeUs = 0;
3814 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08003815 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003816
Eric Laurent81784c32012-11-19 14:55:58 -08003817}
3818
3819void AudioFlinger::MixerThread::threadLoop_sleepTime()
3820{
3821 // If no tracks are ready, sleep once for the duration of an output
3822 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003823 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003824 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003825 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
3826 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
3827 mSleepTimeUs = kMinThreadSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003828 }
3829 // reduce sleep time in case of consecutive application underruns to avoid
3830 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3831 // duration we would end up writing less data than needed by the audio HAL if
3832 // the condition persists.
3833 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3834 sleepTimeShift++;
3835 }
3836 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003837 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003838 }
3839 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003840 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3841 // before effects processing or output.
3842 if (mMixerBufferValid) {
3843 memset(mMixerBuffer, 0, mMixerBufferSize);
3844 } else {
3845 memset(mSinkBuffer, 0, mSinkBufferSize);
3846 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003847 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003848 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3849 "anticipated start");
3850 }
3851 // TODO add standby time extension fct of effect tail
3852}
3853
3854// prepareTracks_l() must be called with ThreadBase::mLock held
3855AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3856 Vector< sp<Track> > *tracksToRemove)
3857{
3858
3859 mixer_state mixerStatus = MIXER_IDLE;
3860 // find out which tracks need to be processed
3861 size_t count = mActiveTracks.size();
3862 size_t mixedTracks = 0;
3863 size_t tracksWithEffect = 0;
3864 // counts only _active_ fast tracks
3865 size_t fastTracks = 0;
3866 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3867
3868 float masterVolume = mMasterVolume;
3869 bool masterMute = mMasterMute;
3870
3871 if (masterMute) {
3872 masterVolume = 0;
3873 }
3874 // Delegate master volume control to effect in output mix effect chain if needed
3875 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3876 if (chain != 0) {
3877 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3878 chain->setVolume_l(&v, &v);
3879 masterVolume = (float)((v + (1 << 23)) >> 24);
3880 chain.clear();
3881 }
3882
3883 // prepare a new state to push
3884 FastMixerStateQueue *sq = NULL;
3885 FastMixerState *state = NULL;
3886 bool didModify = false;
3887 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003888 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003889 sq = mFastMixer->sq();
3890 state = sq->begin();
3891 }
3892
Andy Hung69aed5f2014-02-25 17:24:40 -08003893 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003894 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003895
Eric Laurent81784c32012-11-19 14:55:58 -08003896 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003897 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003898 if (t == 0) {
3899 continue;
3900 }
3901
3902 // this const just means the local variable doesn't change
3903 Track* const track = t.get();
3904
3905 // process fast tracks
3906 if (track->isFastTrack()) {
3907
3908 // It's theoretically possible (though unlikely) for a fast track to be created
3909 // and then removed within the same normal mix cycle. This is not a problem, as
3910 // the track never becomes active so it's fast mixer slot is never touched.
3911 // The converse, of removing an (active) track and then creating a new track
3912 // at the identical fast mixer slot within the same normal mix cycle,
3913 // is impossible because the slot isn't marked available until the end of each cycle.
3914 int j = track->mFastIndex;
3915 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
3916 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3917 FastTrack *fastTrack = &state->mFastTracks[j];
3918
3919 // Determine whether the track is currently in underrun condition,
3920 // and whether it had a recent underrun.
3921 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3922 FastTrackUnderruns underruns = ftDump->mUnderruns;
3923 uint32_t recentFull = (underruns.mBitFields.mFull -
3924 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3925 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3926 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3927 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3928 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3929 uint32_t recentUnderruns = recentPartial + recentEmpty;
3930 track->mObservedUnderruns = underruns;
3931 // don't count underruns that occur while stopping or pausing
3932 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07003933 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3934 recentUnderruns > 0) {
3935 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3936 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Phil Burk2812d9e2016-01-04 10:34:30 -08003937 } else {
3938 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Eric Laurent81784c32012-11-19 14:55:58 -08003939 }
3940
3941 // This is similar to the state machine for normal tracks,
3942 // with a few modifications for fast tracks.
3943 bool isActive = true;
3944 switch (track->mState) {
3945 case TrackBase::STOPPING_1:
3946 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08003947 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003948 track->mState = TrackBase::STOPPING_2;
3949 }
3950 break;
3951 case TrackBase::PAUSING:
3952 // ramp down is not yet implemented
3953 track->setPaused();
3954 break;
3955 case TrackBase::RESUMING:
3956 // ramp up is not yet implemented
3957 track->mState = TrackBase::ACTIVE;
3958 break;
3959 case TrackBase::ACTIVE:
3960 if (recentFull > 0 || recentPartial > 0) {
3961 // track has provided at least some frames recently: reset retry count
3962 track->mRetryCount = kMaxTrackRetries;
3963 }
3964 if (recentUnderruns == 0) {
3965 // no recent underruns: stay active
3966 break;
3967 }
3968 // there has recently been an underrun of some kind
3969 if (track->sharedBuffer() == 0) {
3970 // were any of the recent underruns "empty" (no frames available)?
3971 if (recentEmpty == 0) {
3972 // no, then ignore the partial underruns as they are allowed indefinitely
3973 break;
3974 }
3975 // there has recently been an "empty" underrun: decrement the retry counter
3976 if (--(track->mRetryCount) > 0) {
3977 break;
3978 }
3979 // indicate to client process that the track was disabled because of underrun;
3980 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08003981 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08003982 // remove from active list, but state remains ACTIVE [confusing but true]
3983 isActive = false;
3984 break;
3985 }
3986 // fall through
3987 case TrackBase::STOPPING_2:
3988 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003989 case TrackBase::STOPPED:
3990 case TrackBase::FLUSHED: // flush() while active
3991 // Check for presentation complete if track is inactive
3992 // We have consumed all the buffers of this track.
3993 // This would be incomplete if we auto-paused on underrun
3994 {
3995 size_t audioHALFrames =
3996 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08003997 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003998 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
3999 // track stays in active list until presentation is complete
4000 break;
4001 }
4002 }
4003 if (track->isStopping_2()) {
4004 track->mState = TrackBase::STOPPED;
4005 }
4006 if (track->isStopped()) {
4007 // Can't reset directly, as fast mixer is still polling this track
4008 // track->reset();
4009 // So instead mark this track as needing to be reset after push with ack
4010 resetMask |= 1 << i;
4011 }
4012 isActive = false;
4013 break;
4014 case TrackBase::IDLE:
4015 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08004016 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08004017 }
4018
4019 if (isActive) {
4020 // was it previously inactive?
4021 if (!(state->mTrackMask & (1 << j))) {
4022 ExtendedAudioBufferProvider *eabp = track;
4023 VolumeProvider *vp = track;
4024 fastTrack->mBufferProvider = eabp;
4025 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08004026 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07004027 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08004028 fastTrack->mGeneration++;
4029 state->mTrackMask |= 1 << j;
4030 didModify = true;
4031 // no acknowledgement required for newly active tracks
4032 }
4033 // cache the combined master volume and stream type volume for fast mixer; this
4034 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08004035 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08004036 ++fastTracks;
4037 } else {
4038 // was it previously active?
4039 if (state->mTrackMask & (1 << j)) {
4040 fastTrack->mBufferProvider = NULL;
4041 fastTrack->mGeneration++;
4042 state->mTrackMask &= ~(1 << j);
4043 didModify = true;
4044 // If any fast tracks were removed, we must wait for acknowledgement
4045 // because we're about to decrement the last sp<> on those tracks.
4046 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4047 } else {
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08004048 LOG_ALWAYS_FATAL("fast track %d should have been active; "
4049 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
4050 j, track->mState, state->mTrackMask, recentUnderruns,
4051 track->sharedBuffer() != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004052 }
4053 tracksToRemove->add(track);
4054 // Avoids a misleading display in dumpsys
4055 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
4056 }
4057 continue;
4058 }
4059
4060 { // local variable scope to avoid goto warning
4061
4062 audio_track_cblk_t* cblk = track->cblk();
4063
4064 // The first time a track is added we wait
4065 // for all its buffers to be filled before processing it
4066 int name = track->name();
4067 // make sure that we have enough frames to mix one full buffer.
4068 // enforce this condition only once to enable draining the buffer in case the client
4069 // app does not call stop() and relies on underrun to stop:
4070 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
4071 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004072 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07004073 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004074 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004075
4076 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004077 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004078 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
4079 // add frames already consumed but not yet released by the resampler
4080 // because mAudioTrackServerProxy->framesReady() will include these frames
4081 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
4082
Eric Laurent81784c32012-11-19 14:55:58 -08004083 uint32_t minFrames = 1;
4084 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
4085 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004086 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08004087 }
Eric Laurent13e4c962013-12-20 17:36:01 -08004088
4089 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07004090 if (ATRACE_ENABLED()) {
4091 // I wish we had formatted trace names
4092 char traceName[16];
4093 strcpy(traceName, "nRdy");
4094 int name = track->name();
4095 if (AudioMixer::TRACK0 <= name &&
4096 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
4097 name -= AudioMixer::TRACK0;
4098 traceName[4] = (name / 10) + '0';
4099 traceName[5] = (name % 10) + '0';
4100 } else {
4101 traceName[4] = '?';
4102 traceName[5] = '?';
4103 }
4104 traceName[6] = '\0';
4105 ATRACE_INT(traceName, framesReady);
4106 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004107 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08004108 !track->isPaused() && !track->isTerminated())
4109 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004110 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004111
4112 mixedTracks++;
4113
Andy Hung69aed5f2014-02-25 17:24:40 -08004114 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
4115 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08004116 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08004117 if (track->mainBuffer() != mSinkBuffer &&
4118 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004119 if (mEffectBufferEnabled) {
4120 mEffectBufferValid = true; // Later can set directly.
4121 }
Eric Laurent81784c32012-11-19 14:55:58 -08004122 chain = getEffectChain_l(track->sessionId());
4123 // Delegate volume control to effect in track effect chain if needed
4124 if (chain != 0) {
4125 tracksWithEffect++;
4126 } else {
4127 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
4128 "session %d",
4129 name, track->sessionId());
4130 }
4131 }
4132
4133
4134 int param = AudioMixer::VOLUME;
4135 if (track->mFillingUpStatus == Track::FS_FILLED) {
4136 // no ramp for the first volume setting
4137 track->mFillingUpStatus = Track::FS_ACTIVE;
4138 if (track->mState == TrackBase::RESUMING) {
4139 track->mState = TrackBase::ACTIVE;
4140 param = AudioMixer::RAMP_VOLUME;
4141 }
4142 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004143 // FIXME should not make a decision based on mServer
4144 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004145 // If the track is stopped before the first frame was mixed,
4146 // do not apply ramp
4147 param = AudioMixer::RAMP_VOLUME;
4148 }
4149
4150 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07004151 uint32_t vl, vr; // in U8.24 integer format
4152 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08004153 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07004154 vl = vr = 0;
4155 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08004156 if (track->isPausing()) {
4157 track->setPaused();
4158 }
4159 } else {
4160
4161 // read original volumes with volume control
4162 float typeVolume = mStreamTypes[track->streamType()].volume;
4163 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004164 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004165 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07004166 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
4167 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08004168 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07004169 if (vlf > GAIN_FLOAT_UNITY) {
4170 ALOGV("Track left volume out of range: %.3g", vlf);
4171 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004172 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07004173 if (vrf > GAIN_FLOAT_UNITY) {
4174 ALOGV("Track right volume out of range: %.3g", vrf);
4175 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004176 }
4177 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07004178 vlf *= v;
4179 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08004180 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07004181 // then derive vl and vr as U8.24 versions for the effect chain
4182 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
4183 vl = (uint32_t) (scaleto8_24 * vlf);
4184 vr = (uint32_t) (scaleto8_24 * vrf);
4185 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08004186 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08004187 // send level comes from shared memory and so may be corrupt
4188 if (sendLevel > MAX_GAIN_INT) {
4189 ALOGV("Track send level out of range: %04X", sendLevel);
4190 sendLevel = MAX_GAIN_INT;
4191 }
Andy Hung6be49402014-05-30 10:42:03 -07004192 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4193 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08004194 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004195
Eric Laurent81784c32012-11-19 14:55:58 -08004196 // Delegate volume control to effect in track effect chain if needed
4197 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4198 // Do not ramp volume if volume is controlled by effect
4199 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08004200 // Update remaining floating point volume levels
4201 vlf = (float)vl / (1 << 24);
4202 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004203 track->mHasVolumeController = true;
4204 } else {
4205 // force no volume ramp when volume controller was just disabled or removed
4206 // from effect chain to avoid volume spike
4207 if (track->mHasVolumeController) {
4208 param = AudioMixer::VOLUME;
4209 }
4210 track->mHasVolumeController = false;
4211 }
4212
Eric Laurent81784c32012-11-19 14:55:58 -08004213 // XXX: these things DON'T need to be done each time
4214 mAudioMixer->setBufferProvider(name, track);
4215 mAudioMixer->enable(name);
4216
Andy Hung6be49402014-05-30 10:42:03 -07004217 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
4218 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
4219 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004220 mAudioMixer->setParameter(
4221 name,
4222 AudioMixer::TRACK,
4223 AudioMixer::FORMAT, (void *)track->format());
4224 mAudioMixer->setParameter(
4225 name,
4226 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004227 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004228 mAudioMixer->setParameter(
4229 name,
4230 AudioMixer::TRACK,
4231 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004232 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004233 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004234 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004235 if (reqSampleRate == 0) {
4236 reqSampleRate = mSampleRate;
4237 } else if (reqSampleRate > maxSampleRate) {
4238 reqSampleRate = maxSampleRate;
4239 }
Eric Laurent81784c32012-11-19 14:55:58 -08004240 mAudioMixer->setParameter(
4241 name,
4242 AudioMixer::RESAMPLE,
4243 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004244 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004245
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004246 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004247 mAudioMixer->setParameter(
4248 name,
4249 AudioMixer::TIMESTRETCH,
4250 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004251 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004252
Andy Hung69aed5f2014-02-25 17:24:40 -08004253 /*
4254 * Select the appropriate output buffer for the track.
4255 *
Andy Hung98ef9782014-03-04 14:46:50 -08004256 * Tracks with effects go into their own effects chain buffer
4257 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004258 *
4259 * Other tracks can use mMixerBuffer for higher precision
4260 * channel accumulation. If this buffer is enabled
4261 * (mMixerBufferEnabled true), then selected tracks will accumulate
4262 * into it.
4263 *
4264 */
4265 if (mMixerBufferEnabled
4266 && (track->mainBuffer() == mSinkBuffer
4267 || track->mainBuffer() == mMixerBuffer)) {
4268 mAudioMixer->setParameter(
4269 name,
4270 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004271 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004272 mAudioMixer->setParameter(
4273 name,
4274 AudioMixer::TRACK,
4275 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4276 // TODO: override track->mainBuffer()?
4277 mMixerBufferValid = true;
4278 } else {
4279 mAudioMixer->setParameter(
4280 name,
4281 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004282 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004283 mAudioMixer->setParameter(
4284 name,
4285 AudioMixer::TRACK,
4286 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4287 }
Eric Laurent81784c32012-11-19 14:55:58 -08004288 mAudioMixer->setParameter(
4289 name,
4290 AudioMixer::TRACK,
4291 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4292
4293 // reset retry count
4294 track->mRetryCount = kMaxTrackRetries;
4295
4296 // If one track is ready, set the mixer ready if:
4297 // - the mixer was not ready during previous round OR
4298 // - no other track is not ready
4299 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4300 mixerStatus != MIXER_TRACKS_ENABLED) {
4301 mixerStatus = MIXER_TRACKS_READY;
4302 }
4303 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004304 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hung08fb1742015-05-31 23:22:10 -07004305 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)",
4306 track, framesReady, desiredFrames);
Glenn Kasten82aaf942013-07-17 16:05:07 -07004307 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08004308 } else {
4309 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004310 }
Phil Burk2812d9e2016-01-04 10:34:30 -08004311
Eric Laurent81784c32012-11-19 14:55:58 -08004312 // clear effect chain input buffer if an active track underruns to avoid sending
4313 // previous audio buffer again to effects
4314 chain = getEffectChain_l(track->sessionId());
4315 if (chain != 0) {
4316 chain->clearInputBuffer();
4317 }
4318
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004319 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004320 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4321 track->isStopped() || track->isPaused()) {
4322 // We have consumed all the buffers of this track.
4323 // Remove it from the list of active tracks.
4324 // TODO: use actual buffer filling status instead of latency when available from
4325 // audio HAL
4326 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004327 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004328 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4329 if (track->isStopped()) {
4330 track->reset();
4331 }
4332 tracksToRemove->add(track);
4333 }
4334 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004335 // No buffers for this track. Give it a few chances to
4336 // fill a buffer, then remove it from active list.
4337 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004338 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004339 tracksToRemove->add(track);
4340 // indicate to client process that the track was disabled because of underrun;
4341 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004342 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004343 // If one track is not ready, mark the mixer also not ready if:
4344 // - the mixer was ready during previous round OR
4345 // - no other track is ready
4346 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4347 mixerStatus != MIXER_TRACKS_READY) {
4348 mixerStatus = MIXER_TRACKS_ENABLED;
4349 }
4350 }
4351 mAudioMixer->disable(name);
4352 }
4353
4354 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08004355
4356 }
4357
4358 // Push the new FastMixer state if necessary
4359 bool pauseAudioWatchdog = false;
4360 if (didModify) {
4361 state->mFastTracksGen++;
4362 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4363 if (kUseFastMixer == FastMixer_Dynamic &&
4364 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4365 state->mCommand = FastMixerState::COLD_IDLE;
4366 state->mColdFutexAddr = &mFastMixerFutex;
4367 state->mColdGen++;
4368 mFastMixerFutex = 0;
4369 if (kUseFastMixer == FastMixer_Dynamic) {
4370 mNormalSink = mOutputSink;
4371 }
4372 // If we go into cold idle, need to wait for acknowledgement
4373 // so that fast mixer stops doing I/O.
4374 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4375 pauseAudioWatchdog = true;
4376 }
Eric Laurent81784c32012-11-19 14:55:58 -08004377 }
4378 if (sq != NULL) {
4379 sq->end(didModify);
4380 sq->push(block);
4381 }
4382#ifdef AUDIO_WATCHDOG
4383 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4384 mAudioWatchdog->pause();
4385 }
4386#endif
4387
4388 // Now perform the deferred reset on fast tracks that have stopped
4389 while (resetMask != 0) {
4390 size_t i = __builtin_ctz(resetMask);
4391 ALOG_ASSERT(i < count);
4392 resetMask &= ~(1 << i);
4393 sp<Track> t = mActiveTracks[i].promote();
4394 if (t == 0) {
4395 continue;
4396 }
4397 Track* track = t.get();
4398 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4399 track->reset();
4400 }
4401
4402 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004403 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004404
Eric Laurent97d547d2014-09-02 14:45:53 -07004405 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4406 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004407 }
4408
4409 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004410 // as long as there are effects we should clear the effects buffer, to avoid
4411 // passing a non-clean buffer to the effect chain
4412 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004413 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004414 // sink or mix buffer must be cleared if all tracks are connected to an
4415 // effect chain as in this case the mixer will not write to the sink or mix buffer
4416 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004417 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4418 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004419 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004420 if (mMixerBufferValid) {
4421 memset(mMixerBuffer, 0, mMixerBufferSize);
4422 // TODO: In testing, mSinkBuffer below need not be cleared because
4423 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4424 // after mixing.
4425 //
4426 // To enforce this guarantee:
4427 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4428 // (mixedTracks == 0 && fastTracks > 0))
4429 // must imply MIXER_TRACKS_READY.
4430 // Later, we may clear buffers regardless, and skip much of this logic.
4431 }
Andy Hung98ef9782014-03-04 14:46:50 -08004432 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004433 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004434 }
4435
4436 // if any fast tracks, then status is ready
4437 mMixerStatusIgnoringFastTracks = mixerStatus;
4438 if (fastTracks > 0) {
4439 mixerStatus = MIXER_TRACKS_READY;
4440 }
4441 return mixerStatus;
4442}
4443
4444// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07004445int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
Glenn Kastend848eb42016-03-08 13:42:11 -08004446 audio_format_t format, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08004447{
Andy Hunge8a1ced2014-05-09 15:02:21 -07004448 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08004449}
4450
4451// deleteTrackName_l() must be called with ThreadBase::mLock held
4452void AudioFlinger::MixerThread::deleteTrackName_l(int name)
4453{
4454 ALOGV("remove track (%d) and delete from mixer", name);
4455 mAudioMixer->deleteTrackName(name);
4456}
4457
Eric Laurent10351942014-05-08 18:49:52 -07004458// checkForNewParameter_l() must be called with ThreadBase::mLock held
4459bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4460 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004461{
Eric Laurent81784c32012-11-19 14:55:58 -08004462 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08004463 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004464
Eric Laurent10351942014-05-08 18:49:52 -07004465 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004466
Eric Laurent10351942014-05-08 18:49:52 -07004467 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
4468 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004469 if (mFastMixer != 0) {
Eric Laurent10351942014-05-08 18:49:52 -07004470 FastMixerStateQueue *sq = mFastMixer->sq();
4471 FastMixerState *state = sq->begin();
4472 if (!(state->mCommand & FastMixerState::IDLE)) {
4473 previousCommand = state->mCommand;
4474 state->mCommand = FastMixerState::HOT_IDLE;
4475 sq->end();
4476 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
4477 } else {
4478 sq->end(false /*didModify*/);
Eric Laurent81784c32012-11-19 14:55:58 -08004479 }
Eric Laurent10351942014-05-08 18:49:52 -07004480 }
Eric Laurent81784c32012-11-19 14:55:58 -08004481
Eric Laurent10351942014-05-08 18:49:52 -07004482 AudioParameter param = AudioParameter(keyValuePair);
4483 int value;
4484 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4485 reconfig = true;
4486 }
4487 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004488 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004489 status = BAD_VALUE;
4490 } else {
4491 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004492 reconfig = true;
4493 }
Eric Laurent10351942014-05-08 18:49:52 -07004494 }
4495 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004496 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004497 status = BAD_VALUE;
4498 } else {
4499 // no need to save value, since it's constant
4500 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004501 }
Eric Laurent10351942014-05-08 18:49:52 -07004502 }
4503 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4504 // do not accept frame count changes if tracks are open as the track buffer
4505 // size depends on frame count and correct behavior would not be guaranteed
4506 // if frame count is changed after track creation
4507 if (!mTracks.isEmpty()) {
4508 status = INVALID_OPERATION;
4509 } else {
4510 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004511 }
Eric Laurent10351942014-05-08 18:49:52 -07004512 }
4513 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004514#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004515 // when changing the audio output device, call addBatteryData to notify
4516 // the change
4517 if (mOutDevice != value) {
4518 uint32_t params = 0;
4519 // check whether speaker is on
4520 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4521 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004522 }
Eric Laurent10351942014-05-08 18:49:52 -07004523
4524 audio_devices_t deviceWithoutSpeaker
4525 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4526 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07004527 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07004528 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4529 }
4530
4531 if (params != 0) {
4532 addBatteryData(params);
4533 }
4534 }
Eric Laurent81784c32012-11-19 14:55:58 -08004535#endif
4536
Eric Laurent10351942014-05-08 18:49:52 -07004537 // forward device change to effects that have requested to be
4538 // aware of attached audio device.
4539 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08004540 a2dpDeviceChanged =
4541 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07004542 mOutDevice = value;
4543 for (size_t i = 0; i < mEffectChains.size(); i++) {
4544 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004545 }
4546 }
Eric Laurent10351942014-05-08 18:49:52 -07004547 }
Eric Laurent81784c32012-11-19 14:55:58 -08004548
Eric Laurent10351942014-05-08 18:49:52 -07004549 if (status == NO_ERROR) {
4550 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4551 keyValuePair.string());
4552 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004553 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004554 mStandby = true;
4555 mBytesWritten = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004556 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Eric Laurent10351942014-05-08 18:49:52 -07004557 keyValuePair.string());
Eric Laurent81784c32012-11-19 14:55:58 -08004558 }
Eric Laurent10351942014-05-08 18:49:52 -07004559 if (status == NO_ERROR && reconfig) {
4560 readOutputParameters_l();
4561 delete mAudioMixer;
4562 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4563 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004564 int name = getTrackName_l(mTracks[i]->mChannelMask,
4565 mTracks[i]->mFormat, mTracks[i]->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07004566 if (name < 0) {
4567 break;
4568 }
4569 mTracks[i]->mName = name;
4570 }
Eric Laurent73e26b62015-04-27 16:55:58 -07004571 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004572 }
Eric Laurent81784c32012-11-19 14:55:58 -08004573 }
4574
4575 if (!(previousCommand & FastMixerState::IDLE)) {
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004576 ALOG_ASSERT(mFastMixer != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004577 FastMixerStateQueue *sq = mFastMixer->sq();
4578 FastMixerState *state = sq->begin();
4579 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
4580 state->mCommand = previousCommand;
4581 sq->end();
4582 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4583 }
4584
Eric Laurent42537be2016-01-08 17:16:42 -08004585 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08004586}
4587
4588
4589void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4590{
Eric Laurent81784c32012-11-19 14:55:58 -08004591 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07004592 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Elliott Hughes87cebad2014-05-22 10:14:43 -07004593 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Andy Hung2ddee192015-12-18 17:34:44 -08004594 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent81784c32012-11-19 14:55:58 -08004595
4596 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten2f90c512015-12-02 11:40:09 -08004597 // while we are dumping it. It may be inconsistent, but it won't mutate!
4598 // This is a large object so we place it on the heap.
4599 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
4600 const FastMixerDumpState *copy = new FastMixerDumpState(mFastMixerDumpState);
4601 copy->dump(fd);
4602 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08004603
4604#ifdef STATE_QUEUE_DUMP
4605 // Similar for state queue
4606 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4607 observerCopy.dump(fd);
4608 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4609 mutatorCopy.dump(fd);
4610#endif
4611
Glenn Kasten46909e72013-02-26 09:20:22 -08004612#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004613 // Write the tee output to a .wav file
4614 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08004615#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004616
4617#ifdef AUDIO_WATCHDOG
4618 if (mAudioWatchdog != 0) {
4619 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4620 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4621 wdCopy.dump(fd);
4622 }
4623#endif
4624}
4625
4626uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4627{
4628 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4629}
4630
4631uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4632{
4633 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4634}
4635
4636void AudioFlinger::MixerThread::cacheParameters_l()
4637{
4638 PlaybackThread::cacheParameters_l();
4639
4640 // FIXME: Relaxed timing because of a certain device that can't meet latency
4641 // Should be reduced to 2x after the vendor fixes the driver issue
4642 // increase threshold again due to low power audio mode. The way this warning
4643 // threshold is calculated and its usefulness should be reconsidered anyway.
4644 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4645}
4646
4647// ----------------------------------------------------------------------------
4648
4649AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent51716182016-02-29 18:00:56 -08004650 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady,
4651 uint32_t bitRate)
4652 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady, bitRate)
Eric Laurent81784c32012-11-19 14:55:58 -08004653 // mLeftVolFloat, mRightVolFloat
4654{
4655}
4656
Eric Laurentbfb1b832013-01-07 09:53:42 -08004657AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4658 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurent51716182016-02-29 18:00:56 -08004659 ThreadBase::type_t type, bool systemReady, uint32_t bitRate)
4660 : PlaybackThread(audioFlinger, output, id, device, type, systemReady, bitRate)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004661 // mLeftVolFloat, mRightVolFloat
4662{
4663}
4664
Eric Laurent81784c32012-11-19 14:55:58 -08004665AudioFlinger::DirectOutputThread::~DirectOutputThread()
4666{
4667}
4668
Eric Laurentbfb1b832013-01-07 09:53:42 -08004669void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
4670{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004671 float left, right;
4672
4673 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4674 left = right = 0;
4675 } else {
4676 float typeVolume = mStreamTypes[track->streamType()].volume;
4677 float v = mMasterVolume * typeVolume;
4678 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004679 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4680 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4681 if (left > GAIN_FLOAT_UNITY) {
4682 left = GAIN_FLOAT_UNITY;
4683 }
4684 left *= v;
4685 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4686 if (right > GAIN_FLOAT_UNITY) {
4687 right = GAIN_FLOAT_UNITY;
4688 }
4689 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004690 }
4691
4692 if (lastTrack) {
4693 if (left != mLeftVolFloat || right != mRightVolFloat) {
4694 mLeftVolFloat = left;
4695 mRightVolFloat = right;
4696
4697 // Convert volumes from float to 8.24
4698 uint32_t vl = (uint32_t)(left * (1 << 24));
4699 uint32_t vr = (uint32_t)(right * (1 << 24));
4700
4701 // Delegate volume control to effect in track effect chain if needed
4702 // only one effect chain can be present on DirectOutputThread, so if
4703 // there is one, the track is connected to it
4704 if (!mEffectChains.isEmpty()) {
4705 mEffectChains[0]->setVolume_l(&vl, &vr);
4706 left = (float)vl / (1 << 24);
4707 right = (float)vr / (1 << 24);
4708 }
4709 if (mOutput->stream->set_volume) {
4710 mOutput->stream->set_volume(mOutput->stream, left, right);
4711 }
4712 }
4713 }
4714}
4715
Phil Burk43b4dcc2015-06-09 16:53:44 -07004716void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
4717{
4718 sp<Track> previousTrack = mPreviousTrack.promote();
4719 sp<Track> latestTrack = mLatestActiveTrack.promote();
4720
Eric Laurent0f0631e2015-07-06 18:01:25 -07004721 if (previousTrack != 0 && latestTrack != 0) {
4722 if (mType == DIRECT) {
4723 if (previousTrack.get() != latestTrack.get()) {
4724 mFlushPending = true;
4725 }
4726 } else /* mType == OFFLOAD */ {
4727 if (previousTrack->sessionId() != latestTrack->sessionId()) {
4728 mFlushPending = true;
4729 }
4730 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004731 }
4732 PlaybackThread::onAddNewTrack_l();
4733}
Eric Laurentbfb1b832013-01-07 09:53:42 -08004734
Eric Laurent81784c32012-11-19 14:55:58 -08004735AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4736 Vector< sp<Track> > *tracksToRemove
4737)
4738{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004739 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004740 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004741 bool doHwPause = false;
4742 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004743
4744 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07004745 for (size_t i = 0; i < count; i++) {
4746 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08004747 // The track died recently
4748 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004749 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08004750 }
4751
Phil Burk43b4dcc2015-06-09 16:53:44 -07004752 if (t->isInvalid()) {
4753 ALOGW("An invalidated track shouldn't be in active list");
4754 tracksToRemove->add(t);
4755 continue;
4756 }
4757
Eric Laurent81784c32012-11-19 14:55:58 -08004758 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004759#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08004760 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004761#endif
Eric Laurentfd477972013-10-25 18:10:40 -07004762 // Only consider last track started for volume and mixer state control.
4763 // In theory an older track could underrun and restart after the new one starts
4764 // but as we only care about the transition phase between two tracks on a
4765 // direct output, it is not a problem to ignore the underrun case.
4766 sp<Track> l = mLatestActiveTrack.promote();
4767 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004768
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004769 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004770 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004771 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004772 doHwPause = true;
4773 mHwPaused = true;
4774 }
4775 tracksToRemove->add(track);
4776 } else if (track->isFlushPending()) {
4777 track->flushAck();
4778 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004779 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004780 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004781 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004782 track->resumeAck();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004783 if (last && mHwPaused) {
4784 doHwResume = true;
4785 mHwPaused = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004786 }
4787 }
4788
Eric Laurent81784c32012-11-19 14:55:58 -08004789 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004790 // for all its buffers to be filled before processing it.
4791 // Allow draining the buffer in case the client
4792 // app does not call stop() and relies on underrun to stop:
4793 // hence the test on (track->mRetryCount > 1).
4794 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07004795 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08004796 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004797 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08004798 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004799 minFrames = mNormalFrameCount;
4800 } else {
4801 minFrames = 1;
4802 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004803
Eric Laurentab5cdba2014-06-09 17:22:27 -07004804 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4805 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004806 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004807 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004808
4809 if (track->mFillingUpStatus == Track::FS_FILLED) {
4810 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004811 // make sure processVolume_l() will apply new volume even if 0
4812 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004813 if (!mHwSupportsPause) {
4814 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004815 }
4816 }
4817
4818 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004819 processVolume_l(track, last);
4820 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004821 sp<Track> previousTrack = mPreviousTrack.promote();
4822 if (previousTrack != 0) {
4823 if (track != previousTrack.get()) {
4824 // Flush any data still being written from last track
4825 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07004826 // Invalidate previous track to force a seek when resuming.
4827 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004828 }
4829 }
4830 mPreviousTrack = track;
4831
Eric Laurentd595b7c2013-04-03 17:27:56 -07004832 // reset retry count
4833 track->mRetryCount = kMaxTrackRetriesDirect;
4834 mActiveTrack = t;
4835 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07004836 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004837 doHwResume = true;
4838 mHwPaused = false;
4839 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004840 }
Eric Laurent81784c32012-11-19 14:55:58 -08004841 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004842 // clear effect chain input buffer if the last active track started underruns
4843 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004844 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004845 mEffectChains[0]->clearInputBuffer();
4846 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004847 if (track->isStopping_1()) {
4848 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07004849 if (last && mHwPaused) {
4850 doHwResume = true;
4851 mHwPaused = false;
4852 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004853 }
4854 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4855 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004856 // We have consumed all the buffers of this track.
4857 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004858 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08004859 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004860 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4861 } else {
4862 audioHALFrames = 0;
4863 }
4864
Andy Hung818e7a32016-02-16 18:08:07 -08004865 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004866 if (mStandby || !last ||
4867 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004868 if (track->isStopping_2()) {
4869 track->mState = TrackBase::STOPPED;
4870 }
Eric Laurent81784c32012-11-19 14:55:58 -08004871 if (track->isStopped()) {
4872 track->reset();
4873 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004874 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004875 }
4876 } else {
4877 // No buffers for this track. Give it a few chances to
4878 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004879 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004880 if (--(track->mRetryCount) <= 0) {
4881 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004882 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004883 // indicate to client process that the track was disabled because of underrun;
4884 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004885 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004886 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07004887 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
4888 "minFrames = %u, mFormat = %#x",
4889 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08004890 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07004891 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004892 doHwPause = true;
4893 mHwPaused = true;
4894 }
Eric Laurent81784c32012-11-19 14:55:58 -08004895 }
4896 }
4897 }
4898 }
4899
Eric Laurentd1f69b02014-12-15 14:33:13 -08004900 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07004901 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004902 for (size_t i = 0; i < mTracks.size(); i++) {
4903 if (mTracks[i]->isFlushPending()) {
4904 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004905 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004906 }
4907 }
4908 }
4909
4910 // make sure the pause/flush/resume sequence is executed in the right order.
4911 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4912 // before flush and then resume HW. This can happen in case of pause/flush/resume
4913 // if resume is received before pause is executed.
4914 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07004915 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004916 mOutput->stream->pause(mOutput->stream);
4917 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004918 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004919 flushHw_l();
4920 }
4921 if (mHwSupportsPause && !mStandby && doHwResume) {
4922 mOutput->stream->resume(mOutput->stream);
4923 }
Eric Laurent81784c32012-11-19 14:55:58 -08004924 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004925 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004926
4927 return mixerStatus;
4928}
4929
4930void AudioFlinger::DirectOutputThread::threadLoop_mix()
4931{
Eric Laurent81784c32012-11-19 14:55:58 -08004932 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08004933 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004934 // output audio to hardware
4935 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07004936 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004937 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08004938 status_t status = mActiveTrack->getNextBuffer(&buffer);
4939 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08004940 // no need to pad with 0 for compressed audio
4941 if (audio_has_proportional_frames(mFormat)) {
4942 memset(curBuf, 0, frameCount * mFrameSize);
4943 }
Eric Laurent81784c32012-11-19 14:55:58 -08004944 break;
4945 }
4946 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
4947 frameCount -= buffer.frameCount;
4948 curBuf += buffer.frameCount * mFrameSize;
4949 mActiveTrack->releaseBuffer(&buffer);
4950 }
Andy Hung2098f272014-02-27 14:00:06 -08004951 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004952 mSleepTimeUs = 0;
4953 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004954 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004955}
4956
4957void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
4958{
Eric Laurentd1f69b02014-12-15 14:33:13 -08004959 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004960 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004961 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004962 return;
4963 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004964 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004965 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurent51716182016-02-29 18:00:56 -08004966 // For compressed offload, use faster sleep time when underruning until more than an
4967 // entire buffer was written to the audio HAL
4968 if (!audio_has_proportional_frames(mFormat) &&
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004969 (mType == OFFLOAD) && (mBytesWritten < (int64_t) mBufferSize)) {
Eric Laurent51716182016-02-29 18:00:56 -08004970 mSleepTimeUs = kDirectMinSleepTimeUs;
4971 } else {
4972 mSleepTimeUs = mActiveSleepTimeUs;
4973 }
Eric Laurent81784c32012-11-19 14:55:58 -08004974 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004975 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004976 }
Phil Burkfdb3c072016-02-09 10:47:02 -08004977 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08004978 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004979 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004980 }
4981}
4982
Eric Laurentd1f69b02014-12-15 14:33:13 -08004983void AudioFlinger::DirectOutputThread::threadLoop_exit()
4984{
4985 {
4986 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08004987 for (size_t i = 0; i < mTracks.size(); i++) {
4988 if (mTracks[i]->isFlushPending()) {
4989 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004990 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004991 }
4992 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004993 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004994 flushHw_l();
4995 }
4996 }
4997 PlaybackThread::threadLoop_exit();
4998}
4999
5000// must be called with thread mutex locked
5001bool AudioFlinger::DirectOutputThread::shouldStandby_l()
5002{
5003 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07005004 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005005
vivek mehta9cd7ad12016-03-17 00:18:29 -07005006 if ((mType == DIRECT) && audio_is_linear_pcm(mFormat) && !usesHwAvSync()) {
5007 return !mStandby;
5008 }
5009
Eric Laurentd1f69b02014-12-15 14:33:13 -08005010 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
5011 // after a timeout and we will enter standby then.
5012 if (mTracks.size() > 0) {
5013 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07005014 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
5015 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005016 }
5017
Eric Laurent5cff4032015-05-26 13:49:58 -07005018 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08005019}
5020
Eric Laurent81784c32012-11-19 14:55:58 -08005021// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005022int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Glenn Kastend848eb42016-03-08 13:42:11 -08005023 audio_format_t format __unused, audio_session_t sessionId __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005024{
5025 return 0;
5026}
5027
5028// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005029void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005030{
5031}
5032
Eric Laurent10351942014-05-08 18:49:52 -07005033// checkForNewParameter_l() must be called with ThreadBase::mLock held
5034bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
5035 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005036{
5037 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005038 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005039
Eric Laurent10351942014-05-08 18:49:52 -07005040 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005041
Eric Laurent10351942014-05-08 18:49:52 -07005042 AudioParameter param = AudioParameter(keyValuePair);
5043 int value;
5044 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5045 // forward device change to effects that have requested to be
5046 // aware of attached audio device.
5047 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005048 a2dpDeviceChanged =
5049 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005050 mOutDevice = value;
5051 for (size_t i = 0; i < mEffectChains.size(); i++) {
5052 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07005053 }
5054 }
Eric Laurent81784c32012-11-19 14:55:58 -08005055 }
Eric Laurent10351942014-05-08 18:49:52 -07005056 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5057 // do not accept frame count changes if tracks are open as the track buffer
5058 // size depends on frame count and correct behavior would not be garantied
5059 // if frame count is changed after track creation
5060 if (!mTracks.isEmpty()) {
5061 status = INVALID_OPERATION;
5062 } else {
5063 reconfig = true;
5064 }
5065 }
5066 if (status == NO_ERROR) {
5067 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
5068 keyValuePair.string());
5069 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005070 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005071 mStandby = true;
5072 mBytesWritten = 0;
5073 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
5074 keyValuePair.string());
5075 }
5076 if (status == NO_ERROR && reconfig) {
5077 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07005078 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005079 }
5080 }
5081
Eric Laurent42537be2016-01-08 17:16:42 -08005082 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005083}
5084
5085uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
5086{
5087 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005088 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005089 time = PlaybackThread::activeSleepTimeUs();
5090 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005091 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005092 }
5093 return time;
5094}
5095
5096uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
5097{
5098 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005099 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005100 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
5101 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005102 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005103 }
5104 return time;
5105}
5106
5107uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
5108{
5109 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005110 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005111 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
5112 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005113 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005114 }
5115 return time;
5116}
5117
5118void AudioFlinger::DirectOutputThread::cacheParameters_l()
5119{
5120 PlaybackThread::cacheParameters_l();
5121
5122 // use shorter standby delay as on normal output to release
5123 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07005124 // no delay on outputs with HW A/V sync
5125 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005126 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08005127 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005128 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07005129 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005130 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07005131 }
Eric Laurent81784c32012-11-19 14:55:58 -08005132}
5133
Eric Laurente659ef42014-09-29 13:06:46 -07005134void AudioFlinger::DirectOutputThread::flushHw_l()
5135{
Phil Burk062e67a2015-02-11 13:40:50 -08005136 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08005137 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005138 mFlushPending = false;
Eric Laurente659ef42014-09-29 13:06:46 -07005139}
5140
Eric Laurent81784c32012-11-19 14:55:58 -08005141// ----------------------------------------------------------------------------
5142
Eric Laurentbfb1b832013-01-07 09:53:42 -08005143AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07005144 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005145 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07005146 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07005147 mWriteAckSequence(0),
5148 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005149{
5150}
5151
5152AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
5153{
5154}
5155
5156void AudioFlinger::AsyncCallbackThread::onFirstRef()
5157{
5158 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
5159}
5160
5161bool AudioFlinger::AsyncCallbackThread::threadLoop()
5162{
5163 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005164 uint32_t writeAckSequence;
5165 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005166
5167 {
5168 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005169 while (!((mWriteAckSequence & 1) ||
5170 (mDrainSequence & 1) ||
5171 exitPending())) {
5172 mWaitWorkCV.wait(mLock);
5173 }
5174
Eric Laurentbfb1b832013-01-07 09:53:42 -08005175 if (exitPending()) {
5176 break;
5177 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005178 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
5179 mWriteAckSequence, mDrainSequence);
5180 writeAckSequence = mWriteAckSequence;
5181 mWriteAckSequence &= ~1;
5182 drainSequence = mDrainSequence;
5183 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005184 }
5185 {
Eric Laurent4de95592013-09-26 15:28:21 -07005186 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
5187 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005188 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005189 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005190 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005191 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005192 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005193 }
5194 }
5195 }
5196 }
5197 return false;
5198}
5199
5200void AudioFlinger::AsyncCallbackThread::exit()
5201{
5202 ALOGV("AsyncCallbackThread::exit");
5203 Mutex::Autolock _l(mLock);
5204 requestExit();
5205 mWaitWorkCV.broadcast();
5206}
5207
Eric Laurent3b4529e2013-09-05 18:09:19 -07005208void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005209{
5210 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005211 // bit 0 is cleared
5212 mWriteAckSequence = sequence << 1;
5213}
5214
5215void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5216{
5217 Mutex::Autolock _l(mLock);
5218 // ignore unexpected callbacks
5219 if (mWriteAckSequence & 2) {
5220 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005221 mWaitWorkCV.signal();
5222 }
5223}
5224
Eric Laurent3b4529e2013-09-05 18:09:19 -07005225void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005226{
5227 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005228 // bit 0 is cleared
5229 mDrainSequence = sequence << 1;
5230}
5231
5232void AudioFlinger::AsyncCallbackThread::resetDraining()
5233{
5234 Mutex::Autolock _l(mLock);
5235 // ignore unexpected callbacks
5236 if (mDrainSequence & 2) {
5237 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005238 mWaitWorkCV.signal();
5239 }
5240}
5241
5242
5243// ----------------------------------------------------------------------------
5244AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent51716182016-02-29 18:00:56 -08005245 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady,
5246 uint32_t bitRate)
5247 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady, bitRate),
Eric Laurentd7e59222013-11-15 12:02:28 -08005248 mPausedBytesRemaining(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005249{
Eric Laurentfd477972013-10-25 18:10:40 -07005250 //FIXME: mStandby should be set to true by ThreadBase constructor
5251 mStandby = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005252}
5253
Eric Laurentbfb1b832013-01-07 09:53:42 -08005254void AudioFlinger::OffloadThread::threadLoop_exit()
5255{
5256 if (mFlushPending || mHwPaused) {
5257 // If a flush is pending or track was paused, just discard buffered data
5258 flushHw_l();
5259 } else {
5260 mMixerStatus = MIXER_DRAIN_ALL;
5261 threadLoop_drain();
5262 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005263 if (mUseAsyncWrite) {
5264 ALOG_ASSERT(mCallbackThread != 0);
5265 mCallbackThread->exit();
5266 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005267 PlaybackThread::threadLoop_exit();
5268}
5269
5270AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5271 Vector< sp<Track> > *tracksToRemove
5272)
5273{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005274 size_t count = mActiveTracks.size();
5275
5276 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005277 bool doHwPause = false;
5278 bool doHwResume = false;
5279
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005280 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07005281
Eric Laurentbfb1b832013-01-07 09:53:42 -08005282 // find out which tracks need to be processed
5283 for (size_t i = 0; i < count; i++) {
5284 sp<Track> t = mActiveTracks[i].promote();
5285 // The track died recently
5286 if (t == 0) {
5287 continue;
5288 }
5289 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005290#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08005291 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005292#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005293 // Only consider last track started for volume and mixer state control.
5294 // In theory an older track could underrun and restart after the new one starts
5295 // but as we only care about the transition phase between two tracks on a
5296 // direct output, it is not a problem to ignore the underrun case.
5297 sp<Track> l = mLatestActiveTrack.promote();
5298 bool last = l.get() == track;
5299
Haynes Mathew George7844f672014-01-15 12:32:55 -08005300 if (track->isInvalid()) {
5301 ALOGW("An invalidated track shouldn't be in active list");
5302 tracksToRemove->add(track);
5303 continue;
5304 }
5305
5306 if (track->mState == TrackBase::IDLE) {
5307 ALOGW("An idle track shouldn't be in active list");
5308 continue;
5309 }
5310
Eric Laurentbfb1b832013-01-07 09:53:42 -08005311 if (track->isPausing()) {
5312 track->setPaused();
5313 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005314 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005315 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005316 mHwPaused = true;
5317 }
5318 // If we were part way through writing the mixbuffer to
5319 // the HAL we must save this until we resume
5320 // BUG - this will be wrong if a different track is made active,
5321 // in that case we want to discard the pending data in the
5322 // mixbuffer and tell the client to present it again when the
5323 // track is resumed
5324 mPausedWriteLength = mCurrentWriteLength;
5325 mPausedBytesRemaining = mBytesRemaining;
5326 mBytesRemaining = 0; // stop writing
5327 }
5328 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005329 } else if (track->isFlushPending()) {
Eric Laurent51716182016-02-29 18:00:56 -08005330 track->mRetryCount = kMaxTrackRetriesOffload;
Haynes Mathew George7844f672014-01-15 12:32:55 -08005331 track->flushAck();
5332 if (last) {
5333 mFlushPending = true;
5334 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005335 } else if (track->isResumePending()){
5336 track->resumeAck();
5337 if (last) {
5338 if (mPausedBytesRemaining) {
5339 // Need to continue write that was interrupted
5340 mCurrentWriteLength = mPausedWriteLength;
5341 mBytesRemaining = mPausedBytesRemaining;
5342 mPausedBytesRemaining = 0;
5343 }
5344 if (mHwPaused) {
5345 doHwResume = true;
5346 mHwPaused = false;
5347 // threadLoop_mix() will handle the case that we need to
5348 // resume an interrupted write
5349 }
5350 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005351 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005352
5353 // Do not handle new data in this iteration even if track->framesReady()
5354 mixerStatus = MIXER_TRACKS_ENABLED;
5355 }
5356 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005357 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005358 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005359 if (track->mFillingUpStatus == Track::FS_FILLED) {
5360 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07005361 // make sure processVolume_l() will apply new volume even if 0
5362 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005363 }
5364
5365 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005366 sp<Track> previousTrack = mPreviousTrack.promote();
5367 if (previousTrack != 0) {
5368 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005369 // Flush any data still being written from last track
5370 mBytesRemaining = 0;
5371 if (mPausedBytesRemaining) {
5372 // Last track was paused so we also need to flush saved
5373 // mixbuffer state and invalidate track so that it will
5374 // re-submit that unwritten data when it is next resumed
5375 mPausedBytesRemaining = 0;
5376 // Invalidate is a bit drastic - would be more efficient
5377 // to have a flag to tell client that some of the
5378 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005379 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005380 }
5381 // flush data already sent to the DSP if changing audio session as audio
5382 // comes from a different source. Also invalidate previous track to force a
5383 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005384 if (previousTrack->sessionId() != track->sessionId()) {
5385 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005386 }
5387 }
5388 }
5389 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005390 // reset retry count
5391 track->mRetryCount = kMaxTrackRetriesOffload;
5392 mActiveTrack = t;
5393 mixerStatus = MIXER_TRACKS_READY;
5394 }
5395 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005396 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005397 if (track->isStopping_1()) {
5398 // Hardware buffer can hold a large amount of audio so we must
5399 // wait for all current track's data to drain before we say
5400 // that the track is stopped.
5401 if (mBytesRemaining == 0) {
5402 // Only start draining when all data in mixbuffer
5403 // has been written
5404 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5405 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005406 // do not drain if no data was ever sent to HAL (mStandby == true)
5407 if (last && !mStandby) {
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005408 // do not modify drain sequence if we are already draining. This happens
5409 // when resuming from pause after drain.
5410 if ((mDrainSequence & 1) == 0) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005411 mSleepTimeUs = 0;
5412 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005413 mixerStatus = MIXER_DRAIN_TRACK;
5414 mDrainSequence += 2;
5415 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005416 if (mHwPaused) {
5417 // It is possible to move from PAUSED to STOPPING_1 without
5418 // a resume so we must ensure hardware is running
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005419 doHwResume = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005420 mHwPaused = false;
5421 }
5422 }
5423 }
5424 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005425 // Drain has completed or we are in standby, signal presentation complete
5426 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005427 track->mState = TrackBase::STOPPED;
5428 size_t audioHALFrames =
5429 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005430 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005431 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005432 track->presentationComplete(framesWritten, audioHALFrames);
5433 track->reset();
5434 tracksToRemove->add(track);
5435 }
5436 } else {
5437 // No buffers for this track. Give it a few chances to
5438 // fill a buffer, then remove it from active list.
5439 if (--(track->mRetryCount) <= 0) {
5440 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5441 track->name());
5442 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005443 // indicate to client process that the track was disabled because of underrun;
5444 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005445 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005446 } else if (last){
5447 mixerStatus = MIXER_TRACKS_ENABLED;
5448 }
5449 }
5450 }
5451 // compute volume for this track
5452 processVolume_l(track, last);
5453 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005454
Eric Laurentea0fade2013-10-04 16:23:48 -07005455 // make sure the pause/flush/resume sequence is executed in the right order.
5456 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5457 // before flush and then resume HW. This can happen in case of pause/flush/resume
5458 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07005459 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07005460 mOutput->stream->pause(mOutput->stream);
5461 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005462 if (mFlushPending) {
5463 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005464 }
Eric Laurentfd477972013-10-25 18:10:40 -07005465 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07005466 mOutput->stream->resume(mOutput->stream);
5467 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005468
Eric Laurentbfb1b832013-01-07 09:53:42 -08005469 // remove all the tracks that need to be...
5470 removeTracks_l(*tracksToRemove);
5471
5472 return mixerStatus;
5473}
5474
Eric Laurentbfb1b832013-01-07 09:53:42 -08005475// must be called with thread mutex locked
5476bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5477{
Eric Laurent3b4529e2013-09-05 18:09:19 -07005478 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5479 mWriteAckSequence, mDrainSequence);
5480 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005481 return true;
5482 }
5483 return false;
5484}
5485
Eric Laurentbfb1b832013-01-07 09:53:42 -08005486bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5487{
5488 Mutex::Autolock _l(mLock);
5489 return waitingAsyncCallback_l();
5490}
5491
5492void AudioFlinger::OffloadThread::flushHw_l()
5493{
Eric Laurente659ef42014-09-29 13:06:46 -07005494 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005495 // Flush anything still waiting in the mixbuffer
5496 mCurrentWriteLength = 0;
5497 mBytesRemaining = 0;
5498 mPausedWriteLength = 0;
5499 mPausedBytesRemaining = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08005500
Eric Laurentbfb1b832013-01-07 09:53:42 -08005501 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005502 // discard any pending drain or write ack by incrementing sequence
5503 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5504 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005505 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005506 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5507 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005508 }
5509}
5510
Eric Laurent51716182016-02-29 18:00:56 -08005511uint32_t AudioFlinger::OffloadThread::activeSleepTimeUs() const
5512{
5513 uint32_t time;
5514 if (audio_has_proportional_frames(mFormat)) {
5515 time = PlaybackThread::activeSleepTimeUs();
5516 } else {
5517 // sleep time is half the duration of an audio HAL buffer.
5518 // Note: This can be problematic in case of underrun with variable bit rate and
5519 // current rate is much less than initial rate.
5520 time = (uint32_t)max(kDirectMinSleepTimeUs, mBufferDurationUs / 2);
5521 }
5522 return time;
5523}
5524
Eric Laurentbfb1b832013-01-07 09:53:42 -08005525// ----------------------------------------------------------------------------
5526
Eric Laurent81784c32012-11-19 14:55:58 -08005527AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005528 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005529 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07005530 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08005531 mWaitTimeMs(UINT_MAX)
5532{
5533 addOutputTrack(mainThread);
5534}
5535
5536AudioFlinger::DuplicatingThread::~DuplicatingThread()
5537{
5538 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5539 mOutputTracks[i]->destroy();
5540 }
5541}
5542
5543void AudioFlinger::DuplicatingThread::threadLoop_mix()
5544{
5545 // mix buffers...
5546 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08005547 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08005548 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005549 if (mMixerBufferValid) {
5550 memset(mMixerBuffer, 0, mMixerBufferSize);
5551 } else {
5552 memset(mSinkBuffer, 0, mSinkBufferSize);
5553 }
Eric Laurent81784c32012-11-19 14:55:58 -08005554 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005555 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005556 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005557 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005558 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005559}
5560
5561void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5562{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005563 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005564 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005565 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005566 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005567 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005568 }
5569 } else if (mBytesWritten != 0) {
5570 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5571 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005572 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005573 } else {
5574 // flush remaining overflow buffers in output tracks
5575 writeFrames = 0;
5576 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005577 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005578 }
5579}
5580
Eric Laurentbfb1b832013-01-07 09:53:42 -08005581ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005582{
5583 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005584 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005585 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005586 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005587 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005588}
5589
5590void AudioFlinger::DuplicatingThread::threadLoop_standby()
5591{
5592 // DuplicatingThread implements standby by stopping all tracks
5593 for (size_t i = 0; i < outputTracks.size(); i++) {
5594 outputTracks[i]->stop();
5595 }
5596}
5597
5598void AudioFlinger::DuplicatingThread::saveOutputTracks()
5599{
5600 outputTracks = mOutputTracks;
5601}
5602
5603void AudioFlinger::DuplicatingThread::clearOutputTracks()
5604{
5605 outputTracks.clear();
5606}
5607
5608void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5609{
5610 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005611 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5612 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5613 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5614 const size_t frameCount =
5615 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5616 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5617 // from different OutputTracks and their associated MixerThreads (e.g. one may
5618 // nearly empty and the other may be dropping data).
5619
5620 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005621 this,
5622 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005623 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005624 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005625 frameCount,
5626 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08005627 if (outputTrack->cblk() != NULL) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005628 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
Eric Laurent81784c32012-11-19 14:55:58 -08005629 mOutputTracks.add(outputTrack);
Andy Hungc25b84a2015-01-14 19:04:10 -08005630 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005631 updateWaitTime_l();
5632 }
5633}
5634
5635void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5636{
5637 Mutex::Autolock _l(mLock);
5638 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5639 if (mOutputTracks[i]->thread() == thread) {
5640 mOutputTracks[i]->destroy();
5641 mOutputTracks.removeAt(i);
5642 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07005643 if (thread->getOutput() == mOutput) {
5644 mOutput = NULL;
5645 }
Eric Laurent81784c32012-11-19 14:55:58 -08005646 return;
5647 }
5648 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07005649 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005650}
5651
5652// caller must hold mLock
5653void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5654{
5655 mWaitTimeMs = UINT_MAX;
5656 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5657 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5658 if (strong != 0) {
5659 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5660 if (waitTimeMs < mWaitTimeMs) {
5661 mWaitTimeMs = waitTimeMs;
5662 }
5663 }
5664 }
5665}
5666
5667
5668bool AudioFlinger::DuplicatingThread::outputsReady(
5669 const SortedVector< sp<OutputTrack> > &outputTracks)
5670{
5671 for (size_t i = 0; i < outputTracks.size(); i++) {
5672 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5673 if (thread == 0) {
5674 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5675 outputTracks[i].get());
5676 return false;
5677 }
5678 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5679 // see note at standby() declaration
5680 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5681 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5682 thread.get());
5683 return false;
5684 }
5685 }
5686 return true;
5687}
5688
5689uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5690{
5691 return (mWaitTimeMs * 1000) / 2;
5692}
5693
5694void AudioFlinger::DuplicatingThread::cacheParameters_l()
5695{
5696 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5697 updateWaitTime_l();
5698
5699 MixerThread::cacheParameters_l();
5700}
5701
5702// ----------------------------------------------------------------------------
5703// Record
5704// ----------------------------------------------------------------------------
5705
5706AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5707 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005708 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005709 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07005710 audio_devices_t inDevice,
5711 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08005712#ifdef TEE_SINK
5713 , const sp<NBAIO_Sink>& teeSink
5714#endif
5715 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07005716 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005717 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005718 // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005719 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005720#ifdef TEE_SINK
5721 , mTeeSink(teeSink)
5722#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005723 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5724 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005725 // mFastCapture below
5726 , mFastCaptureFutex(0)
5727 // mInputSource
5728 // mPipeSink
5729 // mPipeSource
5730 , mPipeFramesP2(0)
5731 // mPipeMemory
5732 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005733 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005734{
Glenn Kastend7dca052015-03-05 16:05:54 -08005735 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5736 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08005737
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005738 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005739
5740 // create an NBAIO source for the HAL input stream, and negotiate
5741 mInputSource = new AudioStreamInSource(input->stream);
5742 size_t numCounterOffers = 0;
5743 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005744#if !LOG_NDEBUG
5745 ssize_t index =
5746#else
5747 (void)
5748#endif
5749 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005750 ALOG_ASSERT(index == 0);
5751
5752 // initialize fast capture depending on configuration
5753 bool initFastCapture;
5754 switch (kUseFastCapture) {
5755 case FastCapture_Never:
5756 initFastCapture = false;
5757 break;
5758 case FastCapture_Always:
5759 initFastCapture = true;
5760 break;
5761 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07005762 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005763 break;
5764 // case FastCapture_Dynamic:
5765 }
5766
5767 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07005768 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005769 NBAIO_Format format = mInputSource->format();
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005770 size_t pipeFramesP2 = roundup(mSampleRate / 25); // double-buffering of 20 ms each
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005771 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5772 void *pipeBuffer;
5773 const sp<MemoryDealer> roHeap(readOnlyHeap());
5774 sp<IMemory> pipeMemory;
5775 if ((roHeap == 0) ||
5776 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5777 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5778 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5779 goto failed;
5780 }
5781 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5782 memset(pipeBuffer, 0, pipeSize);
5783 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5784 const NBAIO_Format offers[1] = {format};
5785 size_t numCounterOffers = 0;
5786 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5787 ALOG_ASSERT(index == 0);
5788 mPipeSink = pipe;
5789 PipeReader *pipeReader = new PipeReader(*pipe);
5790 numCounterOffers = 0;
5791 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5792 ALOG_ASSERT(index == 0);
5793 mPipeSource = pipeReader;
5794 mPipeFramesP2 = pipeFramesP2;
5795 mPipeMemory = pipeMemory;
5796
5797 // create fast capture
5798 mFastCapture = new FastCapture();
5799 FastCaptureStateQueue *sq = mFastCapture->sq();
5800#ifdef STATE_QUEUE_DUMP
5801 // FIXME
5802#endif
5803 FastCaptureState *state = sq->begin();
5804 state->mCblk = NULL;
5805 state->mInputSource = mInputSource.get();
5806 state->mInputSourceGen++;
5807 state->mPipeSink = pipe;
5808 state->mPipeSinkGen++;
5809 state->mFrameCount = mFrameCount;
5810 state->mCommand = FastCaptureState::COLD_IDLE;
5811 // already done in constructor initialization list
5812 //mFastCaptureFutex = 0;
5813 state->mColdFutexAddr = &mFastCaptureFutex;
5814 state->mColdGen++;
5815 state->mDumpState = &mFastCaptureDumpState;
5816#ifdef TEE_SINK
5817 // FIXME
5818#endif
5819 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
5820 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
5821 sq->end();
5822 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5823
5824 // start the fast capture
5825 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
5826 pid_t tid = mFastCapture->getTid();
Glenn Kasten8379b722016-03-18 14:54:17 -07005827 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005828#ifdef AUDIO_WATCHDOG
5829 // FIXME
5830#endif
5831
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005832 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005833 }
5834failed: ;
5835
5836 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08005837}
5838
Eric Laurent81784c32012-11-19 14:55:58 -08005839AudioFlinger::RecordThread::~RecordThread()
5840{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005841 if (mFastCapture != 0) {
5842 FastCaptureStateQueue *sq = mFastCapture->sq();
5843 FastCaptureState *state = sq->begin();
5844 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5845 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5846 if (old == -1) {
5847 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5848 }
5849 }
5850 state->mCommand = FastCaptureState::EXIT;
5851 sq->end();
5852 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5853 mFastCapture->join();
5854 mFastCapture.clear();
5855 }
5856 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07005857 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07005858 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08005859}
5860
5861void AudioFlinger::RecordThread::onFirstRef()
5862{
Glenn Kastend7dca052015-03-05 16:05:54 -08005863 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08005864}
5865
Eric Laurent81784c32012-11-19 14:55:58 -08005866bool AudioFlinger::RecordThread::threadLoop()
5867{
Eric Laurent81784c32012-11-19 14:55:58 -08005868 nsecs_t lastWarning = 0;
5869
5870 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08005871
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005872reacquire_wakelock:
5873 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08005874 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005875 {
5876 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005877 size_t size = mActiveTracks.size();
5878 activeTracksGen = mActiveTracksGen;
5879 if (size > 0) {
5880 // FIXME an arbitrary choice
5881 activeTrack = mActiveTracks[0];
5882 acquireWakeLock_l(activeTrack->uid());
5883 if (size > 1) {
5884 SortedVector<int> tmp;
5885 for (size_t i = 0; i < size; i++) {
5886 tmp.add(mActiveTracks[i]->uid());
5887 }
5888 updateWakeLockUids_l(tmp);
5889 }
5890 } else {
5891 acquireWakeLock_l(-1);
5892 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005893 }
5894
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005895 // used to request a deferred sleep, to be executed later while mutex is unlocked
5896 uint32_t sleepUs = 0;
5897
5898 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005899 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005900 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07005901
Glenn Kasten5edadd42013-08-14 16:30:49 -07005902 // sleep with mutex unlocked
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005903 if (sleepUs > 0) {
Glenn Kastene7754022014-10-31 12:11:26 -07005904 ATRACE_BEGIN("sleep");
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005905 usleep(sleepUs);
Glenn Kastene7754022014-10-31 12:11:26 -07005906 ATRACE_END();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005907 sleepUs = 0;
Glenn Kasten5edadd42013-08-14 16:30:49 -07005908 }
5909
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005910 // activeTracks accumulates a copy of a subset of mActiveTracks
5911 Vector< sp<RecordTrack> > activeTracks;
5912
Glenn Kasten735f45f2014-08-18 15:51:59 -07005913 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005914 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07005915
Glenn Kasten735f45f2014-08-18 15:51:59 -07005916 // reference to a fast track which is about to be removed
5917 sp<RecordTrack> fastTrackToRemove;
5918
Eric Laurent81784c32012-11-19 14:55:58 -08005919 { // scope for mLock
5920 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08005921
Eric Laurent021cf962014-05-13 10:18:14 -07005922 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005923
Eric Laurent000a4192014-01-29 15:17:32 -08005924 // check exitPending here because checkForNewParameters_l() and
5925 // checkForNewParameters_l() can temporarily release mLock
5926 if (exitPending()) {
5927 break;
5928 }
5929
Glenn Kasten2b806402013-11-20 16:37:38 -08005930 // if no active track(s), then standby and release wakelock
5931 size_t size = mActiveTracks.size();
5932 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07005933 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005934 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08005935 releaseWakeLock_l();
5936 ALOGV("RecordThread: loop stopping");
5937 // go to sleep
5938 mWaitWorkCV.wait(mLock);
5939 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005940 goto reacquire_wakelock;
5941 }
5942
Glenn Kasten2b806402013-11-20 16:37:38 -08005943 if (mActiveTracksGen != activeTracksGen) {
5944 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005945 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08005946 for (size_t i = 0; i < size; i++) {
5947 tmp.add(mActiveTracks[i]->uid());
5948 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005949 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08005950 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005951
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005952 bool doBroadcast = false;
5953 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07005954
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005955 activeTrack = mActiveTracks[i];
5956 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07005957 if (activeTrack->isFastTrack()) {
5958 ALOG_ASSERT(fastTrackToRemove == 0);
5959 fastTrackToRemove = activeTrack;
5960 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005961 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08005962 mActiveTracks.remove(activeTrack);
5963 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005964 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07005965 continue;
5966 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005967
5968 TrackBase::track_state activeTrackState = activeTrack->mState;
5969 switch (activeTrackState) {
5970
5971 case TrackBase::PAUSING:
5972 mActiveTracks.remove(activeTrack);
5973 mActiveTracksGen++;
5974 doBroadcast = true;
5975 size--;
5976 continue;
5977
5978 case TrackBase::STARTING_1:
5979 sleepUs = 10000;
5980 i++;
5981 continue;
5982
5983 case TrackBase::STARTING_2:
5984 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005985 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07005986 activeTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005987 break;
5988
5989 case TrackBase::ACTIVE:
5990 break;
5991
5992 case TrackBase::IDLE:
5993 i++;
5994 continue;
5995
5996 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08005997 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07005998 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005999
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006000 activeTracks.add(activeTrack);
6001 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07006002
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006003 if (activeTrack->isFastTrack()) {
6004 ALOG_ASSERT(!mFastTrackAvail);
6005 ALOG_ASSERT(fastTrack == 0);
6006 fastTrack = activeTrack;
6007 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006008 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006009 if (doBroadcast) {
6010 mStartStopCond.broadcast();
6011 }
6012
6013 // sleep if there are no active tracks to process
6014 if (activeTracks.size() == 0) {
6015 if (sleepUs == 0) {
6016 sleepUs = kRecordThreadSleepUs;
6017 }
6018 continue;
6019 }
6020 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07006021
Eric Laurent81784c32012-11-19 14:55:58 -08006022 lockEffectChains_l(effectChains);
6023 }
6024
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006025 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07006026
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006027 size_t size = effectChains.size();
6028 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006029 // thread mutex is not locked, but effect chain is locked
6030 effectChains[i]->process_l();
6031 }
6032
Glenn Kasten735f45f2014-08-18 15:51:59 -07006033 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006034 if (mFastCapture != 0) {
6035 FastCaptureStateQueue *sq = mFastCapture->sq();
6036 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07006037 bool didModify = false;
6038 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006039 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
6040 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
6041 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6042 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6043 if (old == -1) {
6044 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6045 }
6046 }
6047 state->mCommand = FastCaptureState::READ_WRITE;
6048#if 0 // FIXME
6049 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08006050 FastThreadDumpState::kSamplingNforLowRamDevice :
6051 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006052#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07006053 didModify = true;
6054 }
6055 audio_track_cblk_t *cblkOld = state->mCblk;
6056 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
6057 if (cblkNew != cblkOld) {
6058 state->mCblk = cblkNew;
6059 // block until acked if removing a fast track
6060 if (cblkOld != NULL) {
6061 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
6062 }
6063 didModify = true;
6064 }
6065 sq->end(didModify);
6066 if (didModify) {
6067 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006068#if 0
6069 if (kUseFastCapture == FastCapture_Dynamic) {
6070 mNormalSource = mPipeSource;
6071 }
6072#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006073 }
6074 }
6075
Glenn Kasten735f45f2014-08-18 15:51:59 -07006076 // now run the fast track destructor with thread mutex unlocked
6077 fastTrackToRemove.clear();
6078
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006079 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
6080 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
6081 // slow, then this RecordThread will overrun by not calling HAL read often enough.
6082 // If destination is non-contiguous, first read past the nominal end of buffer, then
6083 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006084
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006085 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006086 ssize_t framesRead;
6087
6088 // If an NBAIO source is present, use it to read the normal capture's data
6089 if (mPipeSource != 0) {
6090 size_t framesToRead = mBufferSize / mFrameSize;
Andy Hung57446612015-04-19 23:56:46 -07006091 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
Glenn Kastend79072e2016-01-06 08:41:20 -08006092 framesToRead);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006093 if (framesRead == 0) {
6094 // since pipe is non-blocking, simulate blocking input
6095 sleepUs = (framesToRead * 1000000LL) / mSampleRate;
6096 }
6097 // otherwise use the HAL / AudioStreamIn directly
6098 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07006099 ATRACE_BEGIN("read");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006100 ssize_t bytesRead = mInput->stream->read(mInput->stream,
Andy Hung57446612015-04-19 23:56:46 -07006101 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize);
Glenn Kastenec6a7032016-03-14 07:40:23 -07006102 ATRACE_END();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006103 if (bytesRead < 0) {
6104 framesRead = bytesRead;
6105 } else {
6106 framesRead = bytesRead / mFrameSize;
6107 }
6108 }
6109
Andy Hung3f0c9022016-01-15 17:49:46 -08006110 // Update server timestamp with server stats
6111 // systemTime() is optional if the hardware supports timestamps.
6112 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
6113 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6114
6115 // Update server timestamp with kernel stats
6116 if (mInput->stream->get_capture_position != nullptr) {
6117 int64_t position, time;
6118 int ret = mInput->stream->get_capture_position(mInput->stream, &position, &time);
6119 if (ret == NO_ERROR) {
6120 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
6121 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
6122 // Note: In general record buffers should tend to be empty in
6123 // a properly running pipeline.
6124 //
6125 // Also, it is not advantageous to call get_presentation_position during the read
6126 // as the read obtains a lock, preventing the timestamp call from executing.
6127 }
6128 }
6129 // Use this to track timestamp information
6130 // ALOGD("%s", mTimestamp.toString().c_str());
6131
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006132 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006133 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006134 // Force input into standby so that it tries to recover at next read attempt
6135 inputStandBy();
6136 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006137 }
6138 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006139 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006140 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006141 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006142
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006143 if (mTeeSink != 0) {
Andy Hung57446612015-04-19 23:56:46 -07006144 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006145 }
6146 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006147 {
6148 size_t part1 = mRsmpInFramesP2 - rear;
6149 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07006150 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006151 (framesRead - part1) * mFrameSize);
6152 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006153 }
6154 rear = mRsmpInRear += framesRead;
6155
6156 size = activeTracks.size();
6157 // loop over each active track
6158 for (size_t i = 0; i < size; i++) {
6159 activeTrack = activeTracks[i];
6160
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006161 // skip fast tracks, as those are handled directly by FastCapture
6162 if (activeTrack->isFastTrack()) {
6163 continue;
6164 }
6165
Andy Hung73c02e42015-03-29 01:13:58 -07006166 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07006167 // TODO: Update the activeTrack buffer converter in case of reconfigure.
6168
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006169 enum {
6170 OVERRUN_UNKNOWN,
6171 OVERRUN_TRUE,
6172 OVERRUN_FALSE
6173 } overrun = OVERRUN_UNKNOWN;
6174
6175 // loop over getNextBuffer to handle circular sink
6176 for (;;) {
6177
6178 activeTrack->mSink.frameCount = ~0;
6179 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
6180 size_t framesOut = activeTrack->mSink.frameCount;
6181 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
6182
Andy Hung73c02e42015-03-29 01:13:58 -07006183 // check available frames and handle overrun conditions
6184 // if the record track isn't draining fast enough.
6185 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006186 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07006187 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
6188 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006189 overrun = OVERRUN_TRUE;
6190 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006191 if (framesOut == 0 || framesIn == 0) {
6192 break;
6193 }
6194
Andy Hung6770c6f2015-04-07 13:43:36 -07006195 // Don't allow framesOut to be larger than what is possible with resampling
6196 // from framesIn.
6197 // This isn't strictly necessary but helps limit buffer resizing in
6198 // RecordBufferConverter. TODO: remove when no longer needed.
6199 framesOut = min(framesOut,
6200 destinationFramesPossible(
6201 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07006202 // process frames from the RecordThread buffer provider to the RecordTrack buffer
6203 framesOut = activeTrack->mRecordBufferConverter->convert(
6204 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006205
6206 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
6207 overrun = OVERRUN_FALSE;
6208 }
6209
6210 if (activeTrack->mFramesToDrop == 0) {
6211 if (framesOut > 0) {
6212 activeTrack->mSink.frameCount = framesOut;
6213 activeTrack->releaseBuffer(&activeTrack->mSink);
6214 }
6215 } else {
6216 // FIXME could do a partial drop of framesOut
6217 if (activeTrack->mFramesToDrop > 0) {
6218 activeTrack->mFramesToDrop -= framesOut;
6219 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006220 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006221 }
6222 } else {
6223 activeTrack->mFramesToDrop += framesOut;
6224 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
6225 activeTrack->mSyncStartEvent->isCancelled()) {
6226 ALOGW("Synced record %s, session %d, trigger session %d",
6227 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
6228 activeTrack->sessionId(),
6229 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08006230 activeTrack->mSyncStartEvent->triggerSession() :
6231 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006232 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006233 }
6234 }
6235 }
6236
6237 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006238 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006239 }
6240 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006241
6242 switch (overrun) {
6243 case OVERRUN_TRUE:
6244 // client isn't retrieving buffers fast enough
6245 if (!activeTrack->setOverflow()) {
6246 nsecs_t now = systemTime();
6247 // FIXME should lastWarning per track?
6248 if ((now - lastWarning) > kWarningThrottleNs) {
6249 ALOGW("RecordThread: buffer overflow");
6250 lastWarning = now;
6251 }
6252 }
6253 break;
6254 case OVERRUN_FALSE:
6255 activeTrack->clearOverflow();
6256 break;
6257 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006258 break;
6259 }
6260
Andy Hung3f0c9022016-01-15 17:49:46 -08006261 // update frame information and push timestamp out
6262 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08006263 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08006264 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
6265 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006266 }
6267
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006268unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08006269 // enable changes in effect chain
6270 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006271 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08006272 }
6273
Glenn Kasten93e471f2013-08-19 08:40:07 -07006274 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08006275
6276 {
6277 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07006278 for (size_t i = 0; i < mTracks.size(); i++) {
6279 sp<RecordTrack> track = mTracks[i];
6280 track->invalidate();
6281 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006282 mActiveTracks.clear();
6283 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08006284 mStartStopCond.broadcast();
6285 }
6286
6287 releaseWakeLock();
6288
6289 ALOGV("RecordThread %p exiting", this);
6290 return false;
6291}
6292
Glenn Kasten93e471f2013-08-19 08:40:07 -07006293void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08006294{
6295 if (!mStandby) {
6296 inputStandBy();
6297 mStandby = true;
6298 }
6299}
6300
6301void AudioFlinger::RecordThread::inputStandBy()
6302{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006303 // Idle the fast capture if it's currently running
6304 if (mFastCapture != 0) {
6305 FastCaptureStateQueue *sq = mFastCapture->sq();
6306 FastCaptureState *state = sq->begin();
6307 if (!(state->mCommand & FastCaptureState::IDLE)) {
6308 state->mCommand = FastCaptureState::COLD_IDLE;
6309 state->mColdFutexAddr = &mFastCaptureFutex;
6310 state->mColdGen++;
6311 mFastCaptureFutex = 0;
6312 sq->end();
6313 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
6314 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
6315#if 0
6316 if (kUseFastCapture == FastCapture_Dynamic) {
6317 // FIXME
6318 }
6319#endif
6320#ifdef AUDIO_WATCHDOG
6321 // FIXME
6322#endif
6323 } else {
6324 sq->end(false /*didModify*/);
6325 }
6326 }
Eric Laurent81784c32012-11-19 14:55:58 -08006327 mInput->stream->common.standby(&mInput->stream->common);
6328}
6329
Glenn Kasten05997e22014-03-13 15:08:33 -07006330// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07006331sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08006332 const sp<AudioFlinger::Client>& client,
6333 uint32_t sampleRate,
6334 audio_format_t format,
6335 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08006336 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08006337 audio_session_t sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07006338 size_t *notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006339 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07006340 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08006341 pid_t tid,
6342 status_t *status)
6343{
Glenn Kasten74935e42013-12-19 08:56:45 -08006344 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08006345 sp<RecordTrack> track;
6346 status_t lStatus;
6347
Glenn Kasten90e58b12013-07-31 16:16:02 -07006348 // client expresses a preference for FAST, but we get the final say
6349 if (*flags & IAudioFlinger::TRACK_FAST) {
6350 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07006351 // we formerly checked for a callback handler (non-0 tid),
6352 // but that is no longer required for TRANSFER_OBTAIN mode
6353 //
Glenn Kasten74105912014-07-03 12:28:53 -07006354 // frame count is not specified, or is exactly the pipe depth
6355 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006356 // PCM data
6357 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006358 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006359 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006360 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006361 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006362 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07006363 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006364 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006365 hasFastCapture() &&
6366 // there are sufficient fast track slots available
6367 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07006368 ) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006369 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
Glenn Kasten90e58b12013-07-31 16:16:02 -07006370 frameCount, mFrameCount);
6371 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006372 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
Glenn Kasten74105912014-07-03 12:28:53 -07006373 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006374 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07006375 frameCount, mFrameCount, mPipeFramesP2,
6376 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
6377 hasFastCapture(), tid, mFastTrackAvail);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006378 *flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kasten74105912014-07-03 12:28:53 -07006379 }
6380 }
6381
6382 // compute track buffer size in frames, and suggest the notification frame count
6383 if (*flags & IAudioFlinger::TRACK_FAST) {
6384 // fast track: frame count is exactly the pipe depth
6385 frameCount = mPipeFramesP2;
6386 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
6387 *notificationFrames = mFrameCount;
6388 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006389 // not fast track: max notification period is resampled equivalent of one HAL buffer time
6390 // or 20 ms if there is a fast capture
6391 // TODO This could be a roundupRatio inline, and const
6392 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
6393 * sampleRate + mSampleRate - 1) / mSampleRate;
6394 // minimum number of notification periods is at least kMinNotifications,
6395 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
6396 static const size_t kMinNotifications = 3;
6397 static const uint32_t kMinMs = 30;
6398 // TODO This could be a roundupRatio inline
6399 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
6400 // TODO This could be a roundupRatio inline
6401 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
6402 maxNotificationFrames;
6403 const size_t minFrameCount = maxNotificationFrames *
6404 max(kMinNotifications, minNotificationsByMs);
6405 frameCount = max(frameCount, minFrameCount);
6406 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
6407 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07006408 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07006409 }
Glenn Kasten74935e42013-12-19 08:56:45 -08006410 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07006411
Glenn Kasten15e57982013-09-24 11:52:37 -07006412 lStatus = initCheck();
6413 if (lStatus != NO_ERROR) {
6414 ALOGE("createRecordTrack_l() audio driver not initialized");
6415 goto Exit;
6416 }
Eric Laurent81784c32012-11-19 14:55:58 -08006417
6418 { // scope for mLock
6419 Mutex::Autolock _l(mLock);
6420
6421 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07006422 format, channelMask, frameCount, NULL, sessionId, uid,
6423 *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08006424
Glenn Kasten03003332013-08-06 15:40:54 -07006425 lStatus = track->initCheck();
6426 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07006427 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08006428 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08006429 goto Exit;
6430 }
6431 mTracks.add(track);
6432
6433 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6434 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6435 mAudioFlinger->btNrecIsOff();
6436 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6437 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006438
6439 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
6440 pid_t callingPid = IPCThreadState::self()->getCallingPid();
6441 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
6442 // so ask activity manager to do this on our behalf
6443 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
6444 }
Eric Laurent81784c32012-11-19 14:55:58 -08006445 }
Glenn Kasten05997e22014-03-13 15:08:33 -07006446
Eric Laurent81784c32012-11-19 14:55:58 -08006447 lStatus = NO_ERROR;
6448
6449Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07006450 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08006451 return track;
6452}
6453
6454status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6455 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08006456 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08006457{
6458 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6459 sp<ThreadBase> strongMe = this;
6460 status_t status = NO_ERROR;
6461
6462 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006463 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006464 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006465 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08006466 triggerSession,
6467 recordTrack->sessionId(),
6468 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006469 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08006470 // Sync event can be cancelled by the trigger session if the track is not in a
6471 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006472 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006473 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006474 } else {
6475 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006476 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006477 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08006478 }
6479 }
6480
6481 {
Glenn Kasten47c20702013-08-13 15:37:35 -07006482 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08006483 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006484 if (mActiveTracks.indexOf(recordTrack) >= 0) {
6485 if (recordTrack->mState == TrackBase::PAUSING) {
6486 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006487 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006488 } else {
6489 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08006490 }
6491 return status;
6492 }
6493
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006494 // TODO consider other ways of handling this, such as changing the state to :STARTING and
6495 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6496 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006497 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08006498 mActiveTracks.add(recordTrack);
6499 mActiveTracksGen++;
Eric Laurent83b88082014-06-20 18:31:16 -07006500 status_t status = NO_ERROR;
6501 if (recordTrack->isExternalTrack()) {
6502 mLock.unlock();
Glenn Kastend848eb42016-03-08 13:42:11 -08006503 status = AudioSystem::startInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006504 mLock.lock();
6505 // FIXME should verify that recordTrack is still in mActiveTracks
6506 if (status != NO_ERROR) {
6507 mActiveTracks.remove(recordTrack);
6508 mActiveTracksGen++;
6509 recordTrack->clearSyncStartEvent();
6510 ALOGV("RecordThread::start error %d", status);
6511 return status;
6512 }
Eric Laurent81784c32012-11-19 14:55:58 -08006513 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006514 // Catch up with current buffer indices if thread is already running.
6515 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
6516 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6517 // see previously buffered data before it called start(), but with greater risk of overrun.
6518
Andy Hung73c02e42015-03-29 01:13:58 -07006519 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07006520 // clear any converter state as new data will be discontinuous
6521 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006522 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08006523 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08006524 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08006525 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006526 ALOGV("Record failed to start");
6527 status = BAD_VALUE;
6528 goto startError;
6529 }
Eric Laurent81784c32012-11-19 14:55:58 -08006530 return status;
6531 }
Glenn Kasten7c027242012-12-26 14:43:16 -08006532
Eric Laurent81784c32012-11-19 14:55:58 -08006533startError:
Eric Laurent83b88082014-06-20 18:31:16 -07006534 if (recordTrack->isExternalTrack()) {
Glenn Kastend848eb42016-03-08 13:42:11 -08006535 AudioSystem::stopInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006536 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006537 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006538 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08006539 return status;
6540}
6541
Eric Laurent81784c32012-11-19 14:55:58 -08006542void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6543{
6544 sp<SyncEvent> strongEvent = event.promote();
6545
6546 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08006547 sp<RefBase> ptr = strongEvent->cookie().promote();
6548 if (ptr != 0) {
6549 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6550 recordTrack->handleSyncStartEvent(strongEvent);
6551 }
Eric Laurent81784c32012-11-19 14:55:58 -08006552 }
6553}
6554
Glenn Kastena8356f62013-07-25 14:37:52 -07006555bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08006556 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07006557 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006558 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08006559 return false;
6560 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006561 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006562 recordTrack->mState = TrackBase::PAUSING;
6563 // do not wait for mStartStopCond if exiting
6564 if (exitPending()) {
6565 return true;
6566 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006567 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08006568 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006569 // if we have been restarted, recordTrack is in mActiveTracks here
6570 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006571 ALOGV("Record stopped OK");
6572 return true;
6573 }
6574 return false;
6575}
6576
Glenn Kasten0f11b512014-01-31 16:18:54 -08006577bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08006578{
6579 return false;
6580}
6581
Glenn Kasten0f11b512014-01-31 16:18:54 -08006582status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006583{
6584#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6585 if (!isValidSyncEvent(event)) {
6586 return BAD_VALUE;
6587 }
6588
Glenn Kastend848eb42016-03-08 13:42:11 -08006589 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08006590 status_t ret = NAME_NOT_FOUND;
6591
6592 Mutex::Autolock _l(mLock);
6593
6594 for (size_t i = 0; i < mTracks.size(); i++) {
6595 sp<RecordTrack> track = mTracks[i];
6596 if (eventSession == track->sessionId()) {
6597 (void) track->setSyncEvent(event);
6598 ret = NO_ERROR;
6599 }
6600 }
6601 return ret;
6602#else
6603 return BAD_VALUE;
6604#endif
6605}
6606
6607// destroyTrack_l() must be called with ThreadBase::mLock held
6608void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6609{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006610 track->terminate();
6611 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006612 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006613 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006614 removeTrack_l(track);
6615 }
6616}
6617
6618void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6619{
6620 mTracks.remove(track);
6621 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006622 if (track->isFastTrack()) {
6623 ALOG_ASSERT(!mFastTrackAvail);
6624 mFastTrackAvail = true;
6625 }
Eric Laurent81784c32012-11-19 14:55:58 -08006626}
6627
6628void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6629{
6630 dumpInternals(fd, args);
6631 dumpTracks(fd, args);
6632 dumpEffectChains(fd, args);
6633}
6634
6635void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6636{
Elliott Hughes87cebad2014-05-22 10:14:43 -07006637 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08006638
Glenn Kasten44182c22015-03-05 17:12:23 -08006639 dumpBase(fd, args);
6640
6641 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006642 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006643 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006644 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006645 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08006646
Glenn Kasten2f90c512015-12-02 11:40:09 -08006647 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
6648 // while we are dumping it. It may be inconsistent, but it won't mutate!
6649 // This is a large object so we place it on the heap.
6650 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
6651 const FastCaptureDumpState *copy = new FastCaptureDumpState(mFastCaptureDumpState);
6652 copy->dump(fd);
6653 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08006654}
6655
Glenn Kasten0f11b512014-01-31 16:18:54 -08006656void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006657{
6658 const size_t SIZE = 256;
6659 char buffer[SIZE];
6660 String8 result;
6661
Marco Nelissenb2208842014-02-07 14:00:50 -08006662 size_t numtracks = mTracks.size();
6663 size_t numactive = mActiveTracks.size();
6664 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006665 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006666 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006667 dprintf(fd, " of which %zu are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006668 RecordTrack::appendDumpHeader(result);
6669 for (size_t i = 0; i < numtracks ; ++i) {
6670 sp<RecordTrack> track = mTracks[i];
6671 if (track != 0) {
6672 bool active = mActiveTracks.indexOf(track) >= 0;
6673 if (active) {
6674 numactiveseen++;
6675 }
6676 track->dump(buffer, SIZE, active);
6677 result.append(buffer);
6678 }
Eric Laurent81784c32012-11-19 14:55:58 -08006679 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006680 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006681 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006682 }
6683
Marco Nelissenb2208842014-02-07 14:00:50 -08006684 if (numactiveseen != numactive) {
6685 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6686 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006687 result.append(buffer);
6688 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006689 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006690 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006691 if (mTracks.indexOf(track) < 0) {
6692 track->dump(buffer, SIZE, true);
6693 result.append(buffer);
6694 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006695 }
Eric Laurent81784c32012-11-19 14:55:58 -08006696
6697 }
6698 write(fd, result.string(), result.size());
6699}
6700
Andy Hung73c02e42015-03-29 01:13:58 -07006701
6702void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
6703{
6704 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6705 RecordThread *recordThread = (RecordThread *) threadBase.get();
6706 mRsmpInFront = recordThread->mRsmpInRear;
6707 mRsmpInUnrel = 0;
6708}
6709
6710void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
6711 size_t *framesAvailable, bool *hasOverrun)
6712{
6713 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6714 RecordThread *recordThread = (RecordThread *) threadBase.get();
6715 const int32_t rear = recordThread->mRsmpInRear;
6716 const int32_t front = mRsmpInFront;
6717 const ssize_t filled = rear - front;
6718
6719 size_t framesIn;
6720 bool overrun = false;
6721 if (filled < 0) {
6722 // should not happen, but treat like a massive overrun and re-sync
6723 framesIn = 0;
6724 mRsmpInFront = rear;
6725 overrun = true;
6726 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
6727 framesIn = (size_t) filled;
6728 } else {
6729 // client is not keeping up with server, but give it latest data
6730 framesIn = recordThread->mRsmpInFrames;
6731 mRsmpInFront = /* front = */ rear - framesIn;
6732 overrun = true;
6733 }
6734 if (framesAvailable != NULL) {
6735 *framesAvailable = framesIn;
6736 }
6737 if (hasOverrun != NULL) {
6738 *hasOverrun = overrun;
6739 }
6740}
6741
Eric Laurent81784c32012-11-19 14:55:58 -08006742// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006743status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08006744 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006745{
Andy Hung73c02e42015-03-29 01:13:58 -07006746 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006747 if (threadBase == 0) {
6748 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006749 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006750 return NOT_ENOUGH_DATA;
6751 }
6752 RecordThread *recordThread = (RecordThread *) threadBase.get();
6753 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07006754 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07006755 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006756 // FIXME should not be P2 (don't want to increase latency)
6757 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006758 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07006759 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006760 front &= recordThread->mRsmpInFramesP2 - 1;
6761 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07006762 if (part1 > (size_t) filled) {
6763 part1 = filled;
6764 }
6765 size_t ask = buffer->frameCount;
6766 ALOG_ASSERT(ask > 0);
6767 if (part1 > ask) {
6768 part1 = ask;
6769 }
6770 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07006771 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07006772 buffer->raw = NULL;
6773 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07006774 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07006775 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08006776 }
6777
Andy Hung57446612015-04-19 23:56:46 -07006778 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07006779 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07006780 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08006781 return NO_ERROR;
6782}
6783
6784// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006785void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
6786 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006787{
Glenn Kasten85948432013-08-19 12:09:05 -07006788 size_t stepCount = buffer->frameCount;
6789 if (stepCount == 0) {
6790 return;
6791 }
Andy Hung73c02e42015-03-29 01:13:58 -07006792 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
6793 mRsmpInUnrel -= stepCount;
6794 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006795 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006796 buffer->frameCount = 0;
6797}
6798
Andy Hung97a893e2015-03-29 01:03:07 -07006799AudioFlinger::RecordThread::RecordBufferConverter::RecordBufferConverter(
6800 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6801 uint32_t srcSampleRate,
6802 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6803 uint32_t dstSampleRate) :
6804 mSrcChannelMask(AUDIO_CHANNEL_INVALID), // updateParameters will set following vars
6805 // mSrcFormat
6806 // mSrcSampleRate
6807 // mDstChannelMask
6808 // mDstFormat
6809 // mDstSampleRate
6810 // mSrcChannelCount
6811 // mDstChannelCount
6812 // mDstFrameSize
6813 mBuf(NULL), mBufFrames(0), mBufFrameSize(0),
Andy Hungd330ee42015-04-20 13:23:41 -07006814 mResampler(NULL),
6815 mIsLegacyDownmix(false),
6816 mIsLegacyUpmix(false),
6817 mRequiresFloat(false),
6818 mInputConverterProvider(NULL)
Andy Hung97a893e2015-03-29 01:03:07 -07006819{
6820 (void)updateParameters(srcChannelMask, srcFormat, srcSampleRate,
6821 dstChannelMask, dstFormat, dstSampleRate);
6822}
6823
6824AudioFlinger::RecordThread::RecordBufferConverter::~RecordBufferConverter() {
6825 free(mBuf);
6826 delete mResampler;
Andy Hungd330ee42015-04-20 13:23:41 -07006827 delete mInputConverterProvider;
Andy Hung97a893e2015-03-29 01:03:07 -07006828}
6829
6830size_t AudioFlinger::RecordThread::RecordBufferConverter::convert(void *dst,
6831 AudioBufferProvider *provider, size_t frames)
6832{
Andy Hungd330ee42015-04-20 13:23:41 -07006833 if (mInputConverterProvider != NULL) {
6834 mInputConverterProvider->setBufferProvider(provider);
6835 provider = mInputConverterProvider;
6836 }
6837
6838 if (mResampler == NULL) {
Andy Hung97a893e2015-03-29 01:03:07 -07006839 ALOGVV("NO RESAMPLING sampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6840 mSrcSampleRate, mSrcFormat, mDstFormat);
6841
6842 AudioBufferProvider::Buffer buffer;
6843 for (size_t i = frames; i > 0; ) {
6844 buffer.frameCount = i;
Glenn Kastend79072e2016-01-06 08:41:20 -08006845 status_t status = provider->getNextBuffer(&buffer);
Andy Hung97a893e2015-03-29 01:03:07 -07006846 if (status != OK || buffer.frameCount == 0) {
6847 frames -= i; // cannot fill request.
6848 break;
6849 }
Andy Hungd330ee42015-04-20 13:23:41 -07006850 // format convert to destination buffer
6851 convertNoResampler(dst, buffer.raw, buffer.frameCount);
Andy Hung97a893e2015-03-29 01:03:07 -07006852
6853 dst = (int8_t*)dst + buffer.frameCount * mDstFrameSize;
6854 i -= buffer.frameCount;
6855 provider->releaseBuffer(&buffer);
6856 }
6857 } else {
6858 ALOGVV("RESAMPLING mSrcSampleRate:%u mDstSampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6859 mSrcSampleRate, mDstSampleRate, mSrcFormat, mDstFormat);
6860
Andy Hungd330ee42015-04-20 13:23:41 -07006861 // reallocate buffer if needed
6862 if (mBufFrameSize != 0 && mBufFrames < frames) {
6863 free(mBuf);
6864 mBufFrames = frames;
6865 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6866 }
Andy Hung97a893e2015-03-29 01:03:07 -07006867 // resampler accumulates, but we only have one source track
Andy Hungd330ee42015-04-20 13:23:41 -07006868 memset(mBuf, 0, frames * mBufFrameSize);
6869 frames = mResampler->resample((int32_t*)mBuf, frames, provider);
6870 // format convert to destination buffer
6871 convertResampler(dst, mBuf, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006872 }
6873 return frames;
6874}
6875
6876status_t AudioFlinger::RecordThread::RecordBufferConverter::updateParameters(
6877 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6878 uint32_t srcSampleRate,
6879 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6880 uint32_t dstSampleRate)
6881{
6882 // quick evaluation if there is any change.
6883 if (mSrcFormat == srcFormat
6884 && mSrcChannelMask == srcChannelMask
6885 && mSrcSampleRate == srcSampleRate
6886 && mDstFormat == dstFormat
6887 && mDstChannelMask == dstChannelMask
6888 && mDstSampleRate == dstSampleRate) {
6889 return NO_ERROR;
6890 }
6891
Andy Hungdb4c0312015-05-06 08:46:52 -07006892 ALOGV("RecordBufferConverter updateParameters srcMask:%#x dstMask:%#x"
6893 " srcFormat:%#x dstFormat:%#x srcRate:%u dstRate:%u",
6894 srcChannelMask, dstChannelMask, srcFormat, dstFormat, srcSampleRate, dstSampleRate);
Andy Hung97a893e2015-03-29 01:03:07 -07006895 const bool valid =
6896 audio_is_input_channel(srcChannelMask)
6897 && audio_is_input_channel(dstChannelMask)
6898 && audio_is_valid_format(srcFormat) && audio_is_linear_pcm(srcFormat)
6899 && audio_is_valid_format(dstFormat) && audio_is_linear_pcm(dstFormat)
6900 && (srcSampleRate <= dstSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX)
6901 ; // no upsampling checks for now
6902 if (!valid) {
6903 return BAD_VALUE;
6904 }
6905
6906 mSrcFormat = srcFormat;
6907 mSrcChannelMask = srcChannelMask;
6908 mSrcSampleRate = srcSampleRate;
6909 mDstFormat = dstFormat;
6910 mDstChannelMask = dstChannelMask;
6911 mDstSampleRate = dstSampleRate;
6912
6913 // compute derived parameters
6914 mSrcChannelCount = audio_channel_count_from_in_mask(srcChannelMask);
6915 mDstChannelCount = audio_channel_count_from_in_mask(dstChannelMask);
6916 mDstFrameSize = mDstChannelCount * audio_bytes_per_sample(mDstFormat);
6917
Andy Hungd330ee42015-04-20 13:23:41 -07006918 // do we need to resample?
6919 delete mResampler;
6920 mResampler = NULL;
6921 if (mSrcSampleRate != mDstSampleRate) {
6922 mResampler = AudioResampler::create(AUDIO_FORMAT_PCM_FLOAT,
6923 mSrcChannelCount, mDstSampleRate);
6924 mResampler->setSampleRate(mSrcSampleRate);
6925 mResampler->setVolume(AudioMixer::UNITY_GAIN_FLOAT, AudioMixer::UNITY_GAIN_FLOAT);
6926 }
6927
6928 // are we running legacy channel conversion modes?
6929 mIsLegacyDownmix = (mSrcChannelMask == AUDIO_CHANNEL_IN_STEREO
6930 || mSrcChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK)
6931 && mDstChannelMask == AUDIO_CHANNEL_IN_MONO;
6932 mIsLegacyUpmix = mSrcChannelMask == AUDIO_CHANNEL_IN_MONO
6933 && (mDstChannelMask == AUDIO_CHANNEL_IN_STEREO
6934 || mDstChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK);
6935
6936 // do we need to process in float?
6937 mRequiresFloat = mResampler != NULL || mIsLegacyDownmix || mIsLegacyUpmix;
6938
6939 // do we need a staging buffer to convert for destination (we can still optimize this)?
6940 // we use mBufFrameSize > 0 to indicate both frame size as well as buffer necessity
6941 if (mResampler != NULL) {
6942 mBufFrameSize = max(mSrcChannelCount, FCC_2)
6943 * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
Andy Hunga97630b2015-07-22 23:27:24 -07006944 } else if (mIsLegacyUpmix || mIsLegacyDownmix) { // legacy modes always float
Andy Hungd330ee42015-04-20 13:23:41 -07006945 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
6946 } else if (mSrcChannelMask != mDstChannelMask && mDstFormat != mSrcFormat) {
Andy Hung97a893e2015-03-29 01:03:07 -07006947 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(mSrcFormat);
6948 } else {
6949 mBufFrameSize = 0;
6950 }
6951 mBufFrames = 0; // force the buffer to be resized.
6952
Andy Hungd330ee42015-04-20 13:23:41 -07006953 // do we need an input converter buffer provider to give us float?
6954 delete mInputConverterProvider;
6955 mInputConverterProvider = NULL;
6956 if (mRequiresFloat && mSrcFormat != AUDIO_FORMAT_PCM_FLOAT) {
6957 mInputConverterProvider = new ReformatBufferProvider(
6958 audio_channel_count_from_in_mask(mSrcChannelMask),
6959 mSrcFormat,
6960 AUDIO_FORMAT_PCM_FLOAT,
6961 256 /* provider buffer frame count */);
6962 }
6963
6964 // do we need a remixer to do channel mask conversion
6965 if (!mIsLegacyDownmix && !mIsLegacyUpmix && mSrcChannelMask != mDstChannelMask) {
6966 (void) memcpy_by_index_array_initialization_from_channel_mask(
6967 mIdxAry, ARRAY_SIZE(mIdxAry), mDstChannelMask, mSrcChannelMask);
Andy Hung97a893e2015-03-29 01:03:07 -07006968 }
6969 return NO_ERROR;
6970}
6971
Andy Hungd330ee42015-04-20 13:23:41 -07006972void AudioFlinger::RecordThread::RecordBufferConverter::convertNoResampler(
6973 void *dst, const void *src, size_t frames)
Andy Hung97a893e2015-03-29 01:03:07 -07006974{
Andy Hungd330ee42015-04-20 13:23:41 -07006975 // src is native type unless there is legacy upmix or downmix, whereupon it is float.
Andy Hung97a893e2015-03-29 01:03:07 -07006976 if (mBufFrameSize != 0 && mBufFrames < frames) {
6977 free(mBuf);
6978 mBufFrames = frames;
6979 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6980 }
Andy Hungd330ee42015-04-20 13:23:41 -07006981 // do we need to do legacy upmix and downmix?
6982 if (mIsLegacyUpmix || mIsLegacyDownmix) {
Andy Hung97a893e2015-03-29 01:03:07 -07006983 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07006984 if (mIsLegacyUpmix) {
6985 upmix_to_stereo_float_from_mono_float((float *)dstBuf,
6986 (const float *)src, frames);
6987 } else /*mIsLegacyDownmix */ {
6988 downmix_to_mono_float_from_stereo_float((float *)dstBuf,
6989 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006990 }
Andy Hungd330ee42015-04-20 13:23:41 -07006991 if (mBuf != NULL) {
6992 memcpy_by_audio_format(dst, mDstFormat, mBuf, AUDIO_FORMAT_PCM_FLOAT,
6993 frames * mDstChannelCount);
6994 }
6995 return;
6996 }
6997 // do we need to do channel mask conversion?
6998 if (mSrcChannelMask != mDstChannelMask) {
Andy Hung97a893e2015-03-29 01:03:07 -07006999 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07007000 memcpy_by_index_array(dstBuf, mDstChannelCount,
7001 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mSrcFormat), frames);
7002 if (dstBuf == dst) {
7003 return; // format is the same
7004 }
7005 }
7006 // convert to destination buffer
7007 const void *convertBuf = mBuf != NULL ? mBuf : src;
7008 memcpy_by_audio_format(dst, mDstFormat, convertBuf, mSrcFormat,
7009 frames * mDstChannelCount);
7010}
7011
7012void AudioFlinger::RecordThread::RecordBufferConverter::convertResampler(
7013 void *dst, /*not-a-const*/ void *src, size_t frames)
7014{
7015 // src buffer format is ALWAYS float when entering this routine
7016 if (mIsLegacyUpmix) {
7017 ; // mono to stereo already handled by resampler
7018 } else if (mIsLegacyDownmix
7019 || (mSrcChannelMask == mDstChannelMask && mSrcChannelCount == 1)) {
7020 // the resampler outputs stereo for mono input channel (a feature?)
7021 // must convert to mono
7022 downmix_to_mono_float_from_stereo_float((float *)src,
7023 (const float *)src, frames);
7024 } else if (mSrcChannelMask != mDstChannelMask) {
7025 // convert to mono channel again for channel mask conversion (could be skipped
7026 // with further optimization).
Andy Hung97a893e2015-03-29 01:03:07 -07007027 if (mSrcChannelCount == 1) {
Andy Hungd330ee42015-04-20 13:23:41 -07007028 downmix_to_mono_float_from_stereo_float((float *)src,
7029 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07007030 }
Andy Hungd330ee42015-04-20 13:23:41 -07007031 // convert to destination format (in place, OK as float is larger than other types)
7032 if (mDstFormat != AUDIO_FORMAT_PCM_FLOAT) {
7033 memcpy_by_audio_format(src, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
7034 frames * mSrcChannelCount);
7035 }
7036 // channel convert and save to dst
7037 memcpy_by_index_array(dst, mDstChannelCount,
7038 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mDstFormat), frames);
7039 return;
Andy Hung97a893e2015-03-29 01:03:07 -07007040 }
Andy Hungd330ee42015-04-20 13:23:41 -07007041 // convert to destination format and save to dst
7042 memcpy_by_audio_format(dst, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
7043 frames * mDstChannelCount);
Andy Hung97a893e2015-03-29 01:03:07 -07007044}
7045
Eric Laurent10351942014-05-08 18:49:52 -07007046bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
7047 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007048{
7049 bool reconfig = false;
7050
Eric Laurent10351942014-05-08 18:49:52 -07007051 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007052
Eric Laurent10351942014-05-08 18:49:52 -07007053 audio_format_t reqFormat = mFormat;
7054 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07007055 // 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 -07007056 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
7057
7058 AudioParameter param = AudioParameter(keyValuePair);
7059 int value;
7060 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
7061 // channel count change can be requested. Do we mandate the first client defines the
7062 // HAL sampling rate and channel count or do we allow changes on the fly?
7063 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
7064 samplingRate = value;
7065 reconfig = true;
7066 }
7067 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07007068 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07007069 status = BAD_VALUE;
7070 } else {
7071 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08007072 reconfig = true;
7073 }
Eric Laurent10351942014-05-08 18:49:52 -07007074 }
7075 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
7076 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07007077 if (!audio_is_input_channel(mask) ||
7078 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007079 status = BAD_VALUE;
7080 } else {
7081 channelMask = mask;
7082 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007083 }
Eric Laurent10351942014-05-08 18:49:52 -07007084 }
7085 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7086 // do not accept frame count changes if tracks are open as the track buffer
7087 // size depends on frame count and correct behavior would not be guaranteed
7088 // if frame count is changed after track creation
7089 if (mActiveTracks.size() > 0) {
7090 status = INVALID_OPERATION;
7091 } else {
7092 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007093 }
Eric Laurent10351942014-05-08 18:49:52 -07007094 }
7095 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7096 // forward device change to effects that have requested to be
7097 // aware of attached audio device.
7098 for (size_t i = 0; i < mEffectChains.size(); i++) {
7099 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08007100 }
Eric Laurent81784c32012-11-19 14:55:58 -08007101
Eric Laurent10351942014-05-08 18:49:52 -07007102 // store input device and output device but do not forward output device to audio HAL.
7103 // Note that status is ignored by the caller for output device
7104 // (see AudioFlinger::setParameters()
7105 if (audio_is_output_devices(value)) {
7106 mOutDevice = value;
7107 status = BAD_VALUE;
7108 } else {
7109 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07007110 if (value != AUDIO_DEVICE_NONE) {
7111 mPrevInDevice = value;
7112 }
Eric Laurent10351942014-05-08 18:49:52 -07007113 // disable AEC and NS if the device is a BT SCO headset supporting those
7114 // pre processings
7115 if (mTracks.size() > 0) {
7116 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7117 mAudioFlinger->btNrecIsOff();
7118 for (size_t i = 0; i < mTracks.size(); i++) {
7119 sp<RecordTrack> track = mTracks[i];
7120 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7121 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08007122 }
7123 }
7124 }
Eric Laurent10351942014-05-08 18:49:52 -07007125 }
7126 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
7127 mAudioSource != (audio_source_t)value) {
7128 // forward device change to effects that have requested to be
7129 // aware of attached audio device.
7130 for (size_t i = 0; i < mEffectChains.size(); i++) {
7131 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08007132 }
Eric Laurent10351942014-05-08 18:49:52 -07007133 mAudioSource = (audio_source_t)value;
7134 }
Glenn Kastene198c362013-08-13 09:13:36 -07007135
Eric Laurent10351942014-05-08 18:49:52 -07007136 if (status == NO_ERROR) {
7137 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7138 keyValuePair.string());
7139 if (status == INVALID_OPERATION) {
7140 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08007141 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7142 keyValuePair.string());
Eric Laurent10351942014-05-08 18:49:52 -07007143 }
7144 if (reconfig) {
7145 if (status == BAD_VALUE &&
Andy Hung97a893e2015-03-29 01:03:07 -07007146 audio_is_linear_pcm(mInput->stream->common.get_format(&mInput->stream->common)) &&
7147 audio_is_linear_pcm(reqFormat) &&
Eric Laurent10351942014-05-08 18:49:52 -07007148 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
Andy Hung97a893e2015-03-29 01:03:07 -07007149 <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate)) &&
Andy Hunge5412692014-05-16 11:25:07 -07007150 audio_channel_count_from_in_mask(
Andy Hungd1abb8f2015-05-05 23:42:34 -07007151 mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007152 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007153 }
Eric Laurent10351942014-05-08 18:49:52 -07007154 if (status == NO_ERROR) {
7155 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007156 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08007157 }
7158 }
Eric Laurent81784c32012-11-19 14:55:58 -08007159 }
Eric Laurent10351942014-05-08 18:49:52 -07007160
Eric Laurent81784c32012-11-19 14:55:58 -08007161 return reconfig;
7162}
7163
7164String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
7165{
Eric Laurent81784c32012-11-19 14:55:58 -08007166 Mutex::Autolock _l(mLock);
7167 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07007168 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08007169 }
7170
Glenn Kastend8ea6992013-07-16 14:17:15 -07007171 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
7172 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08007173 free(s);
7174 return out_s8;
7175}
7176
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007177void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007178 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7179
7180 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08007181
7182 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007183 case AUDIO_INPUT_OPENED:
7184 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07007185 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07007186 desc->mChannelMask = mChannelMask;
7187 desc->mSamplingRate = mSampleRate;
7188 desc->mFormat = mFormat;
7189 desc->mFrameCount = mFrameCount;
7190 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007191 break;
7192
Eric Laurent73e26b62015-04-27 16:55:58 -07007193 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08007194 default:
7195 break;
7196 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007197 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08007198}
7199
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007200void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007201{
Eric Laurent81784c32012-11-19 14:55:58 -08007202 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
7203 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Andy Hunge5412692014-05-16 11:25:07 -07007204 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Andy Hungd330ee42015-04-20 13:23:41 -07007205 if (mChannelCount > FCC_8) {
7206 ALOGE("HAL channel count %d > %d", mChannelCount, FCC_8);
7207 }
Andy Hung463be252014-07-10 16:56:07 -07007208 mHALFormat = mInput->stream->common.get_format(&mInput->stream->common);
7209 mFormat = mHALFormat;
Andy Hungd330ee42015-04-20 13:23:41 -07007210 if (!audio_is_linear_pcm(mFormat)) {
7211 ALOGE("HAL format %#x is not linear pcm", mFormat);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07007212 }
Eric Laurent665470b2014-07-03 16:37:08 -07007213 mFrameSize = audio_stream_in_frame_size(mInput->stream);
Glenn Kasten548efc92012-11-29 08:48:51 -08007214 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
7215 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007216 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08007217 // 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 -07007218 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08007219 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007220 // A larger value should allow more old data to be read after a track calls start(),
7221 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07007222 //
7223 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08007224 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07007225 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07007226 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07007227 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007228
7229 // TODO optimize audio capture buffer sizes ...
7230 // Here we calculate the size of the sliding buffer used as a source
7231 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
7232 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
7233 // be better to have it derived from the pipe depth in the long term.
7234 // The current value is higher than necessary. However it should not add to latency.
7235
Glenn Kasten85948432013-08-19 12:09:05 -07007236 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Andy Hung0a01c2f2015-09-21 12:44:54 -07007237 size_t bufferSize = (mRsmpInFramesP2 + mFrameCount - 1) * mFrameSize;
7238 (void)posix_memalign(&mRsmpInBuffer, 32, bufferSize);
7239 memset(mRsmpInBuffer, 0, bufferSize); // if posix_memalign fails, will segv here.
Eric Laurent81784c32012-11-19 14:55:58 -08007240
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007241 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
7242 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08007243}
7244
Glenn Kasten5f972c02014-01-13 09:59:31 -08007245uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08007246{
7247 Mutex::Autolock _l(mLock);
7248 if (initCheck() != NO_ERROR) {
7249 return 0;
7250 }
7251
7252 return mInput->stream->get_input_frames_lost(mInput->stream);
7253}
7254
Glenn Kastend848eb42016-03-08 13:42:11 -08007255uint32_t AudioFlinger::RecordThread::hasAudioSession(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08007256{
7257 Mutex::Autolock _l(mLock);
7258 uint32_t result = 0;
7259 if (getEffectChain_l(sessionId) != 0) {
7260 result = EFFECT_SESSION;
7261 }
7262
7263 for (size_t i = 0; i < mTracks.size(); ++i) {
7264 if (sessionId == mTracks[i]->sessionId()) {
7265 result |= TRACK_SESSION;
7266 break;
7267 }
7268 }
7269
7270 return result;
7271}
7272
Glenn Kastend848eb42016-03-08 13:42:11 -08007273KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08007274{
Glenn Kastend848eb42016-03-08 13:42:11 -08007275 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08007276 Mutex::Autolock _l(mLock);
7277 for (size_t j = 0; j < mTracks.size(); ++j) {
7278 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08007279 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08007280 if (ids.indexOfKey(sessionId) < 0) {
7281 ids.add(sessionId, true);
7282 }
7283 }
7284 return ids;
7285}
7286
7287AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7288{
7289 Mutex::Autolock _l(mLock);
7290 AudioStreamIn *input = mInput;
7291 mInput = NULL;
7292 return input;
7293}
7294
7295// this method must always be called either with ThreadBase mLock held or inside the thread loop
7296audio_stream_t* AudioFlinger::RecordThread::stream() const
7297{
7298 if (mInput == NULL) {
7299 return NULL;
7300 }
7301 return &mInput->stream->common;
7302}
7303
7304status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7305{
7306 // only one chain per input thread
7307 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07007308 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08007309 return INVALID_OPERATION;
7310 }
7311 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07007312 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08007313 chain->setInBuffer(NULL);
7314 chain->setOutBuffer(NULL);
7315
7316 checkSuspendOnAddEffectChain_l(chain);
7317
Eric Laurent1b928682014-10-02 19:41:47 -07007318 // make sure enabled pre processing effects state is communicated to the HAL as we
7319 // just moved them to a new input stream.
7320 chain->syncHalEffectsState();
7321
Eric Laurent81784c32012-11-19 14:55:58 -08007322 mEffectChains.add(chain);
7323
7324 return NO_ERROR;
7325}
7326
7327size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7328{
7329 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7330 ALOGW_IF(mEffectChains.size() != 1,
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007331 "removeEffectChain_l() %p invalid chain size %zu on thread %p",
Eric Laurent81784c32012-11-19 14:55:58 -08007332 chain.get(), mEffectChains.size(), this);
7333 if (mEffectChains.size() == 1) {
7334 mEffectChains.removeAt(0);
7335 }
7336 return 0;
7337}
7338
Eric Laurent1c333e22014-05-20 10:48:17 -07007339status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7340 audio_patch_handle_t *handle)
7341{
7342 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007343
7344 // store new device and send to effects
7345 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07007346 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07007347 for (size_t i = 0; i < mEffectChains.size(); i++) {
7348 mEffectChains[i]->setDevice_l(mInDevice);
7349 }
7350
7351 // disable AEC and NS if the device is a BT SCO headset supporting those
7352 // pre processings
7353 if (mTracks.size() > 0) {
7354 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7355 mAudioFlinger->btNrecIsOff();
7356 for (size_t i = 0; i < mTracks.size(); i++) {
7357 sp<RecordTrack> track = mTracks[i];
7358 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7359 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
7360 }
7361 }
7362
7363 // store new source and send to effects
7364 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7365 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07007366 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07007367 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07007368 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007369 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007370
Eric Laurent054d9d32015-04-24 08:48:48 -07007371 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007372 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
7373 status = hwDevice->create_audio_patch(hwDevice,
7374 patch->num_sources,
7375 patch->sources,
7376 patch->num_sinks,
7377 patch->sinks,
7378 handle);
7379 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007380 char *address;
7381 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7382 address = audio_device_address_to_parameter(
7383 patch->sources[0].ext.device.type,
7384 patch->sources[0].ext.device.address);
7385 } else {
7386 address = (char *)calloc(1, 1);
7387 }
7388 AudioParameter param = AudioParameter(String8(address));
7389 free(address);
7390 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING),
7391 (int)patch->sources[0].ext.device.type);
7392 param.addInt(String8(AUDIO_PARAMETER_STREAM_INPUT_SOURCE),
7393 (int)patch->sinks[0].ext.mix.usecase.source);
7394 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7395 param.toString().string());
7396 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07007397 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007398
Eric Laurente8726fe2015-06-26 09:39:24 -07007399 if (mInDevice != mPrevInDevice) {
7400 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7401 mPrevInDevice = mInDevice;
7402 }
Eric Laurent296fb132015-05-01 11:38:42 -07007403
Eric Laurent1c333e22014-05-20 10:48:17 -07007404 return status;
7405}
7406
7407status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7408{
7409 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007410
7411 mInDevice = AUDIO_DEVICE_NONE;
7412
Eric Laurent1c333e22014-05-20 10:48:17 -07007413 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
7414 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
7415 status = hwDevice->release_audio_patch(hwDevice, handle);
7416 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007417 AudioParameter param;
7418 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
7419 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7420 param.toString().string());
Eric Laurent1c333e22014-05-20 10:48:17 -07007421 }
7422 return status;
7423}
7424
Eric Laurent83b88082014-06-20 18:31:16 -07007425void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
7426{
7427 Mutex::Autolock _l(mLock);
7428 mTracks.add(record);
7429}
7430
7431void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
7432{
7433 Mutex::Autolock _l(mLock);
7434 destroyTrack_l(record);
7435}
7436
7437void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
7438{
7439 ThreadBase::getAudioPortConfig(config);
7440 config->role = AUDIO_PORT_ROLE_SINK;
7441 config->ext.mix.hw_module = mInput->audioHwDev->handle();
7442 config->ext.mix.usecase.source = mAudioSource;
7443}
Eric Laurent1c333e22014-05-20 10:48:17 -07007444
Glenn Kasten63238ef2015-03-02 15:50:29 -08007445} // namespace android