blob: 68339d0b37b34894cac359da595360b1438e6347 [file] [log] [blame]
Eric Laurent81784c32012-11-19 14:55:58 -08001/*
2**
3** Copyright 2012, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
Alex Ray371eb972012-11-30 11:11:54 -080021#define ATRACE_TAG ATRACE_TAG_AUDIO
Eric Laurent81784c32012-11-19 14:55:58 -080022
Glenn Kasten153b9fe2013-07-15 11:23:36 -070023#include "Configuration.h"
Eric Laurent81784c32012-11-19 14:55:58 -080024#include <math.h>
25#include <fcntl.h>
Glenn Kastenad8510a2015-02-17 16:24:07 -080026#include <linux/futex.h>
Eric Laurent81784c32012-11-19 14:55:58 -080027#include <sys/stat.h>
Glenn Kastenad8510a2015-02-17 16:24:07 -080028#include <sys/syscall.h>
Eric Laurent81784c32012-11-19 14:55:58 -080029#include <cutils/properties.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070030#include <media/AudioParameter.h>
Andy Hungcd044842014-08-07 11:04:34 -070031#include <media/AudioResamplerPublic.h>
Eric Laurent81784c32012-11-19 14:55:58 -080032#include <utils/Log.h>
Alex Ray371eb972012-11-30 11:11:54 -080033#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080034
35#include <private/media/AudioTrackShared.h>
36#include <hardware/audio.h>
37#include <audio_effects/effect_ns.h>
38#include <audio_effects/effect_aec.h>
Andy Hung2ddee192015-12-18 17:34:44 -080039#include <audio_utils/conversion.h>
Eric Laurent81784c32012-11-19 14:55:58 -080040#include <audio_utils/primitives.h>
Andy Hung98ef9782014-03-04 14:46:50 -080041#include <audio_utils/format.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070042#include <audio_utils/minifloat.h>
Eric Laurent81784c32012-11-19 14:55:58 -080043
44// NBAIO implementations
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070045#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080046#include <media/nbaio/AudioStreamOutSink.h>
47#include <media/nbaio/MonoPipe.h>
48#include <media/nbaio/MonoPipeReader.h>
49#include <media/nbaio/Pipe.h>
50#include <media/nbaio/PipeReader.h>
51#include <media/nbaio/SourceAudioBufferProvider.h>
Wei Jia3f273d12015-11-24 09:06:49 -080052#include <mediautils/BatteryNotifier.h>
Eric Laurent81784c32012-11-19 14:55:58 -080053
54#include <powermanager/PowerManager.h>
55
Eric Laurent81784c32012-11-19 14:55:58 -080056#include "AudioFlinger.h"
57#include "AudioMixer.h"
Andy Hungd330ee42015-04-20 13:23:41 -070058#include "BufferProviders.h"
Eric Laurent81784c32012-11-19 14:55:58 -080059#include "FastMixer.h"
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070060#include "FastCapture.h"
Eric Laurent81784c32012-11-19 14:55:58 -080061#include "ServiceUtilities.h"
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -070062#include "mediautils/SchedulingPolicyService.h"
Eric Laurent81784c32012-11-19 14:55:58 -080063
Eric Laurent81784c32012-11-19 14:55:58 -080064#ifdef ADD_BATTERY_DATA
65#include <media/IMediaPlayerService.h>
66#include <media/IMediaDeathNotifier.h>
67#endif
68
Eric Laurent81784c32012-11-19 14:55:58 -080069#ifdef DEBUG_CPU_USAGE
70#include <cpustats/CentralTendencyStatistics.h>
71#include <cpustats/ThreadCpuUsage.h>
72#endif
73
Glenn Kastenc05b8d72016-03-24 09:48:17 -070074#include "AutoPark.h"
75
Eric Laurent81784c32012-11-19 14:55:58 -080076// ----------------------------------------------------------------------------
77
78// Note: the following macro is used for extremely verbose logging message. In
79// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
80// 0; but one side effect of this is to turn all LOGV's as well. Some messages
81// are so verbose that we want to suppress them even when we have ALOG_ASSERT
82// turned on. Do not uncomment the #def below unless you really know what you
83// are doing and want to see all of the extremely verbose messages.
84//#define VERY_VERY_VERBOSE_LOGGING
85#ifdef VERY_VERY_VERBOSE_LOGGING
86#define ALOGVV ALOGV
87#else
88#define ALOGVV(a...) do { } while(0)
89#endif
90
Andy Hung6770c6f2015-04-07 13:43:36 -070091// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -070092#define max(a, b) ((a) > (b) ? (a) : (b))
Andy Hung6770c6f2015-04-07 13:43:36 -070093template <typename T>
94static inline T min(const T& a, const T& b)
95{
96 return a < b ? a : b;
97}
Glenn Kasten49d00ad2014-07-21 11:22:03 -070098
Andy Hungd330ee42015-04-20 13:23:41 -070099#ifndef ARRAY_SIZE
100#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
101#endif
102
Eric Laurent81784c32012-11-19 14:55:58 -0800103namespace android {
104
105// retry counts for buffer fill timeout
106// 50 * ~20msecs = 1 second
107static const int8_t kMaxTrackRetries = 50;
108static const int8_t kMaxTrackStartupRetries = 50;
109// allow less retry attempts on direct output thread.
110// direct outputs can be a scarce resource in audio hardware and should
111// be released as quickly as possible.
112static const int8_t kMaxTrackRetriesDirect = 2;
Eric Laurent51716182016-02-29 18:00:56 -0800113// retry count before removing active track in case of underrun on offloaded thread:
114// we need to make sure that AudioTrack client has enough time to send large buffers
115//FIXME may be more appropriate if expressed in time units. Need to revise how underrun is handled
116// for offloaded tracks
117static const int8_t kMaxTrackRetriesOffload = 10;
118static const int8_t kMaxTrackStartupRetriesOffload = 100;
119
Eric Laurent81784c32012-11-19 14:55:58 -0800120
121// don't warn about blocked writes or record buffer overflows more often than this
122static const nsecs_t kWarningThrottleNs = seconds(5);
123
124// RecordThread loop sleep time upon application overrun or audio HAL read error
125static const int kRecordThreadSleepUs = 5000;
126
Eric Laurent10351942014-05-08 18:49:52 -0700127// maximum time to wait in sendConfigEvent_l() for a status to be received
128static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800129
130// minimum sleep time for the mixer thread loop when tracks are active but in underrun
131static const uint32_t kMinThreadSleepTimeUs = 5000;
132// maximum divider applied to the active sleep time in the mixer thread loop
133static const uint32_t kMaxThreadSleepTimeShift = 2;
134
Andy Hung09a50072014-02-27 14:30:47 -0800135// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700136// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800137static const uint32_t kMinNormalSinkBufferSizeMs = 20;
138// maximum normal sink buffer size
139static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800140
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700141// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
142// FIXME This should be based on experimentally observed scheduling jitter
143static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
144
Eric Laurent972a1732013-09-04 09:42:59 -0700145// Offloaded output thread standby delay: allows track transition without going to standby
146static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
147
Eric Laurent51716182016-02-29 18:00:56 -0800148// Direct output thread minimum sleep time in idle or active(underrun) state
149static const nsecs_t kDirectMinSleepTimeUs = 10000;
150
151// Offloaded output bit rate in bits per second when unknown.
152// Used for sleep time calculation, so use a high default bitrate to be conservative on sleep time.
153static const uint32_t kOffloadDefaultBitRateBps = 1500000;
154
155
Eric Laurent81784c32012-11-19 14:55:58 -0800156// Whether to use fast mixer
157static const enum {
158 FastMixer_Never, // never initialize or use: for debugging only
159 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
160 // normal mixer multiplier is 1
161 FastMixer_Static, // initialize if needed, then use all the time if initialized,
162 // multiplier is calculated based on min & max normal mixer buffer size
163 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
164 // multiplier is calculated based on min & max normal mixer buffer size
165 // FIXME for FastMixer_Dynamic:
166 // Supporting this option will require fixing HALs that can't handle large writes.
167 // For example, one HAL implementation returns an error from a large write,
168 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
169 // We could either fix the HAL implementations, or provide a wrapper that breaks
170 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
171} kUseFastMixer = FastMixer_Static;
172
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700173// Whether to use fast capture
174static const enum {
175 FastCapture_Never, // never initialize or use: for debugging only
176 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
177 FastCapture_Static, // initialize if needed, then use all the time if initialized
178} kUseFastCapture = FastCapture_Static;
179
Eric Laurent81784c32012-11-19 14:55:58 -0800180// Priorities for requestPriority
181static const int kPriorityAudioApp = 2;
182static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700183static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800184
185// IAudioFlinger::createTrack() reports back to client the total size of shared memory area
186// for the track. The client then sub-divides this into smaller buffers for its use.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800187// Currently the client uses N-buffering by default, but doesn't tell us about the value of N.
188// So for now we just assume that client is double-buffered for fast tracks.
189// FIXME It would be better for client to tell AudioFlinger the value of N,
190// so AudioFlinger could allocate the right amount of memory.
Eric Laurent81784c32012-11-19 14:55:58 -0800191// See the client's minBufCount and mNotificationFramesAct calculations for details.
Glenn Kasten03490092014-05-27 12:30:54 -0700192
193// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800194static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800195
Glenn Kasten03490092014-05-27 12:30:54 -0700196// The minimum and maximum allowed values
197static const int kFastTrackMultiplierMin = 1;
198static const int kFastTrackMultiplierMax = 2;
199
200// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
201static int sFastTrackMultiplier = kFastTrackMultiplier;
202
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700203// See Thread::readOnlyHeap().
204// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
205// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
206// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Glenn Kasten9f81de32014-07-27 15:02:23 -0700207static const size_t kRecordThreadReadOnlyHeapSize = 0x2000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700208
Eric Laurent81784c32012-11-19 14:55:58 -0800209// ----------------------------------------------------------------------------
210
Glenn Kasten03490092014-05-27 12:30:54 -0700211static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
212
213static void sFastTrackMultiplierInit()
214{
215 char value[PROPERTY_VALUE_MAX];
216 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
217 char *endptr;
218 unsigned long ul = strtoul(value, &endptr, 0);
219 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
220 sFastTrackMultiplier = (int) ul;
221 }
222 }
223}
224
225// ----------------------------------------------------------------------------
226
Eric Laurent81784c32012-11-19 14:55:58 -0800227#ifdef ADD_BATTERY_DATA
228// To collect the amplifier usage
229static void addBatteryData(uint32_t params) {
230 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
231 if (service == NULL) {
232 // it already logged
233 return;
234 }
235
236 service->addBatteryData(params);
237}
238#endif
239
Andy Hung3f0c9022016-01-15 17:49:46 -0800240// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
241struct {
242 // call when you acquire a partial wakelock
243 void acquire(const sp<IBinder> &wakeLockToken) {
244 pthread_mutex_lock(&mLock);
245 if (wakeLockToken.get() == nullptr) {
246 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
247 } else {
248 if (mCount == 0) {
249 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
250 }
251 ++mCount;
252 }
253 pthread_mutex_unlock(&mLock);
254 }
255
256 // call when you release a partial wakelock.
257 void release(const sp<IBinder> &wakeLockToken) {
258 if (wakeLockToken.get() == nullptr) {
259 return;
260 }
261 pthread_mutex_lock(&mLock);
262 if (--mCount < 0) {
263 ALOGE("negative wakelock count");
264 mCount = 0;
265 }
266 pthread_mutex_unlock(&mLock);
267 }
268
269 // retrieves the boottime timebase offset from monotonic.
270 int64_t getBoottimeOffset() {
271 pthread_mutex_lock(&mLock);
272 int64_t boottimeOffset = mBoottimeOffset;
273 pthread_mutex_unlock(&mLock);
274 return boottimeOffset;
275 }
276
277 // Adjusts the timebase offset between TIMEBASE_MONOTONIC
278 // and the selected timebase.
279 // Currently only TIMEBASE_BOOTTIME is allowed.
280 //
281 // This only needs to be called upon acquiring the first partial wakelock
282 // after all other partial wakelocks are released.
283 //
284 // We do an empirical measurement of the offset rather than parsing
285 // /proc/timer_list since the latter is not a formal kernel ABI.
286 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
287 int clockbase;
288 switch (timebase) {
289 case ExtendedTimestamp::TIMEBASE_BOOTTIME:
290 clockbase = SYSTEM_TIME_BOOTTIME;
291 break;
292 default:
293 LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
294 break;
295 }
296 // try three times to get the clock offset, choose the one
297 // with the minimum gap in measurements.
298 const int tries = 3;
299 nsecs_t bestGap, measured;
300 for (int i = 0; i < tries; ++i) {
301 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
302 const nsecs_t tbase = systemTime(clockbase);
303 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
304 const nsecs_t gap = tmono2 - tmono;
305 if (i == 0 || gap < bestGap) {
306 bestGap = gap;
307 measured = tbase - ((tmono + tmono2) >> 1);
308 }
309 }
310
311 // to avoid micro-adjusting, we don't change the timebase
312 // unless it is significantly different.
313 //
314 // Assumption: It probably takes more than toleranceNs to
315 // suspend and resume the device.
316 static int64_t toleranceNs = 10000; // 10 us
317 if (llabs(*offset - measured) > toleranceNs) {
318 ALOGV("Adjusting timebase offset old: %lld new: %lld",
319 (long long)*offset, (long long)measured);
320 *offset = measured;
321 }
322 }
323
324 pthread_mutex_t mLock;
325 int32_t mCount;
326 int64_t mBoottimeOffset;
327} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
Eric Laurent81784c32012-11-19 14:55:58 -0800328
329// ----------------------------------------------------------------------------
330// CPU Stats
331// ----------------------------------------------------------------------------
332
333class CpuStats {
334public:
335 CpuStats();
336 void sample(const String8 &title);
337#ifdef DEBUG_CPU_USAGE
338private:
339 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
340 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
341
342 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
343
344 int mCpuNum; // thread's current CPU number
345 int mCpukHz; // frequency of thread's current CPU in kHz
346#endif
347};
348
349CpuStats::CpuStats()
350#ifdef DEBUG_CPU_USAGE
351 : mCpuNum(-1), mCpukHz(-1)
352#endif
353{
354}
355
Glenn Kasten0f11b512014-01-31 16:18:54 -0800356void CpuStats::sample(const String8 &title
357#ifndef DEBUG_CPU_USAGE
358 __unused
359#endif
360 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800361#ifdef DEBUG_CPU_USAGE
362 // get current thread's delta CPU time in wall clock ns
363 double wcNs;
364 bool valid = mCpuUsage.sampleAndEnable(wcNs);
365
366 // record sample for wall clock statistics
367 if (valid) {
368 mWcStats.sample(wcNs);
369 }
370
371 // get the current CPU number
372 int cpuNum = sched_getcpu();
373
374 // get the current CPU frequency in kHz
375 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
376
377 // check if either CPU number or frequency changed
378 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
379 mCpuNum = cpuNum;
380 mCpukHz = cpukHz;
381 // ignore sample for purposes of cycles
382 valid = false;
383 }
384
385 // if no change in CPU number or frequency, then record sample for cycle statistics
386 if (valid && mCpukHz > 0) {
387 double cycles = wcNs * cpukHz * 0.000001;
388 mHzStats.sample(cycles);
389 }
390
391 unsigned n = mWcStats.n();
392 // mCpuUsage.elapsed() is expensive, so don't call it every loop
393 if ((n & 127) == 1) {
394 long long elapsed = mCpuUsage.elapsed();
395 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
396 double perLoop = elapsed / (double) n;
397 double perLoop100 = perLoop * 0.01;
398 double perLoop1k = perLoop * 0.001;
399 double mean = mWcStats.mean();
400 double stddev = mWcStats.stddev();
401 double minimum = mWcStats.minimum();
402 double maximum = mWcStats.maximum();
403 double meanCycles = mHzStats.mean();
404 double stddevCycles = mHzStats.stddev();
405 double minCycles = mHzStats.minimum();
406 double maxCycles = mHzStats.maximum();
407 mCpuUsage.resetElapsed();
408 mWcStats.reset();
409 mHzStats.reset();
410 ALOGD("CPU usage for %s over past %.1f secs\n"
411 " (%u mixer loops at %.1f mean ms per loop):\n"
412 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
413 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
414 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
415 title.string(),
416 elapsed * .000000001, n, perLoop * .000001,
417 mean * .001,
418 stddev * .001,
419 minimum * .001,
420 maximum * .001,
421 mean / perLoop100,
422 stddev / perLoop100,
423 minimum / perLoop100,
424 maximum / perLoop100,
425 meanCycles / perLoop1k,
426 stddevCycles / perLoop1k,
427 minCycles / perLoop1k,
428 maxCycles / perLoop1k);
429
430 }
431 }
432#endif
433};
434
435// ----------------------------------------------------------------------------
436// ThreadBase
437// ----------------------------------------------------------------------------
438
Glenn Kasten97b7b752014-09-28 13:04:24 -0700439// static
440const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
441{
442 switch (type) {
443 case MIXER:
444 return "MIXER";
445 case DIRECT:
446 return "DIRECT";
447 case DUPLICATING:
448 return "DUPLICATING";
449 case RECORD:
450 return "RECORD";
451 case OFFLOAD:
452 return "OFFLOAD";
453 default:
454 return "unknown";
455 }
456}
457
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800458String8 devicesToString(audio_devices_t devices)
459{
460 static const struct mapping {
461 audio_devices_t mDevices;
462 const char * mString;
463 } mappingsOut[] = {
Glenn Kasten818da522015-12-02 13:53:26 -0800464 {AUDIO_DEVICE_OUT_EARPIECE, "EARPIECE"},
465 {AUDIO_DEVICE_OUT_SPEAKER, "SPEAKER"},
466 {AUDIO_DEVICE_OUT_WIRED_HEADSET, "WIRED_HEADSET"},
467 {AUDIO_DEVICE_OUT_WIRED_HEADPHONE, "WIRED_HEADPHONE"},
468 {AUDIO_DEVICE_OUT_BLUETOOTH_SCO, "BLUETOOTH_SCO"},
469 {AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET, "BLUETOOTH_SCO_HEADSET"},
470 {AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT, "BLUETOOTH_SCO_CARKIT"},
471 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, "BLUETOOTH_A2DP"},
472 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,"BLUETOOTH_A2DP_HEADPHONES"},
473 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER, "BLUETOOTH_A2DP_SPEAKER"},
474 {AUDIO_DEVICE_OUT_AUX_DIGITAL, "AUX_DIGITAL"},
475 {AUDIO_DEVICE_OUT_HDMI, "HDMI"},
476 {AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET,"ANLG_DOCK_HEADSET"},
477 {AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET,"DGTL_DOCK_HEADSET"},
478 {AUDIO_DEVICE_OUT_USB_ACCESSORY, "USB_ACCESSORY"},
479 {AUDIO_DEVICE_OUT_USB_DEVICE, "USB_DEVICE"},
480 {AUDIO_DEVICE_OUT_TELEPHONY_TX, "TELEPHONY_TX"},
481 {AUDIO_DEVICE_OUT_LINE, "LINE"},
482 {AUDIO_DEVICE_OUT_HDMI_ARC, "HDMI_ARC"},
483 {AUDIO_DEVICE_OUT_SPDIF, "SPDIF"},
484 {AUDIO_DEVICE_OUT_FM, "FM"},
485 {AUDIO_DEVICE_OUT_AUX_LINE, "AUX_LINE"},
486 {AUDIO_DEVICE_OUT_SPEAKER_SAFE, "SPEAKER_SAFE"},
487 {AUDIO_DEVICE_OUT_IP, "IP"},
Eric Laurent58545be2016-02-22 18:54:20 -0800488 {AUDIO_DEVICE_OUT_BUS, "BUS"},
Glenn Kasten818da522015-12-02 13:53:26 -0800489 {AUDIO_DEVICE_NONE, "NONE"}, // must be last
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800490 }, mappingsIn[] = {
Glenn Kasten818da522015-12-02 13:53:26 -0800491 {AUDIO_DEVICE_IN_COMMUNICATION, "COMMUNICATION"},
492 {AUDIO_DEVICE_IN_AMBIENT, "AMBIENT"},
493 {AUDIO_DEVICE_IN_BUILTIN_MIC, "BUILTIN_MIC"},
494 {AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET, "BLUETOOTH_SCO_HEADSET"},
495 {AUDIO_DEVICE_IN_WIRED_HEADSET, "WIRED_HEADSET"},
496 {AUDIO_DEVICE_IN_AUX_DIGITAL, "AUX_DIGITAL"},
497 {AUDIO_DEVICE_IN_VOICE_CALL, "VOICE_CALL"},
498 {AUDIO_DEVICE_IN_TELEPHONY_RX, "TELEPHONY_RX"},
499 {AUDIO_DEVICE_IN_BACK_MIC, "BACK_MIC"},
500 {AUDIO_DEVICE_IN_REMOTE_SUBMIX, "REMOTE_SUBMIX"},
501 {AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET, "ANLG_DOCK_HEADSET"},
502 {AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET, "DGTL_DOCK_HEADSET"},
503 {AUDIO_DEVICE_IN_USB_ACCESSORY, "USB_ACCESSORY"},
504 {AUDIO_DEVICE_IN_USB_DEVICE, "USB_DEVICE"},
505 {AUDIO_DEVICE_IN_FM_TUNER, "FM_TUNER"},
506 {AUDIO_DEVICE_IN_TV_TUNER, "TV_TUNER"},
507 {AUDIO_DEVICE_IN_LINE, "LINE"},
508 {AUDIO_DEVICE_IN_SPDIF, "SPDIF"},
509 {AUDIO_DEVICE_IN_BLUETOOTH_A2DP, "BLUETOOTH_A2DP"},
510 {AUDIO_DEVICE_IN_LOOPBACK, "LOOPBACK"},
511 {AUDIO_DEVICE_IN_IP, "IP"},
Eric Laurent58545be2016-02-22 18:54:20 -0800512 {AUDIO_DEVICE_IN_BUS, "BUS"},
Glenn Kasten818da522015-12-02 13:53:26 -0800513 {AUDIO_DEVICE_NONE, "NONE"}, // must be last
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800514 };
515 String8 result;
516 audio_devices_t allDevices = AUDIO_DEVICE_NONE;
517 const mapping *entry;
518 if (devices & AUDIO_DEVICE_BIT_IN) {
519 devices &= ~AUDIO_DEVICE_BIT_IN;
520 entry = mappingsIn;
521 } else {
522 entry = mappingsOut;
523 }
524 for ( ; entry->mDevices != AUDIO_DEVICE_NONE; entry++) {
525 allDevices = (audio_devices_t) (allDevices | entry->mDevices);
526 if (devices & entry->mDevices) {
527 if (!result.isEmpty()) {
528 result.append("|");
529 }
530 result.append(entry->mString);
531 }
532 }
533 if (devices & ~allDevices) {
534 if (!result.isEmpty()) {
535 result.append("|");
536 }
537 result.appendFormat("0x%X", devices & ~allDevices);
538 }
539 if (result.isEmpty()) {
540 result.append(entry->mString);
541 }
542 return result;
543}
544
545String8 inputFlagsToString(audio_input_flags_t flags)
546{
547 static const struct mapping {
548 audio_input_flags_t mFlag;
549 const char * mString;
550 } mappings[] = {
Glenn Kasten818da522015-12-02 13:53:26 -0800551 {AUDIO_INPUT_FLAG_FAST, "FAST"},
552 {AUDIO_INPUT_FLAG_HW_HOTWORD, "HW_HOTWORD"},
553 {AUDIO_INPUT_FLAG_RAW, "RAW"},
554 {AUDIO_INPUT_FLAG_SYNC, "SYNC"},
555 {AUDIO_INPUT_FLAG_NONE, "NONE"}, // must be last
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800556 };
557 String8 result;
558 audio_input_flags_t allFlags = AUDIO_INPUT_FLAG_NONE;
559 const mapping *entry;
560 for (entry = mappings; entry->mFlag != AUDIO_INPUT_FLAG_NONE; entry++) {
561 allFlags = (audio_input_flags_t) (allFlags | entry->mFlag);
562 if (flags & entry->mFlag) {
563 if (!result.isEmpty()) {
564 result.append("|");
565 }
566 result.append(entry->mString);
567 }
568 }
569 if (flags & ~allFlags) {
570 if (!result.isEmpty()) {
571 result.append("|");
572 }
573 result.appendFormat("0x%X", flags & ~allFlags);
574 }
575 if (result.isEmpty()) {
576 result.append(entry->mString);
577 }
578 return result;
579}
580
581String8 outputFlagsToString(audio_output_flags_t flags)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700582{
583 static const struct mapping {
584 audio_output_flags_t mFlag;
585 const char * mString;
586 } mappings[] = {
Glenn Kasten818da522015-12-02 13:53:26 -0800587 {AUDIO_OUTPUT_FLAG_DIRECT, "DIRECT"},
588 {AUDIO_OUTPUT_FLAG_PRIMARY, "PRIMARY"},
589 {AUDIO_OUTPUT_FLAG_FAST, "FAST"},
590 {AUDIO_OUTPUT_FLAG_DEEP_BUFFER, "DEEP_BUFFER"},
591 {AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,"COMPRESS_OFFLOAD"},
592 {AUDIO_OUTPUT_FLAG_NON_BLOCKING, "NON_BLOCKING"},
593 {AUDIO_OUTPUT_FLAG_HW_AV_SYNC, "HW_AV_SYNC"},
594 {AUDIO_OUTPUT_FLAG_RAW, "RAW"},
595 {AUDIO_OUTPUT_FLAG_SYNC, "SYNC"},
596 {AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO, "IEC958_NONAUDIO"},
597 {AUDIO_OUTPUT_FLAG_NONE, "NONE"}, // must be last
Glenn Kasten97b7b752014-09-28 13:04:24 -0700598 };
599 String8 result;
600 audio_output_flags_t allFlags = AUDIO_OUTPUT_FLAG_NONE;
601 const mapping *entry;
602 for (entry = mappings; entry->mFlag != AUDIO_OUTPUT_FLAG_NONE; entry++) {
603 allFlags = (audio_output_flags_t) (allFlags | entry->mFlag);
604 if (flags & entry->mFlag) {
605 if (!result.isEmpty()) {
606 result.append("|");
607 }
608 result.append(entry->mString);
609 }
610 }
611 if (flags & ~allFlags) {
612 if (!result.isEmpty()) {
613 result.append("|");
614 }
615 result.appendFormat("0x%X", flags & ~allFlags);
616 }
617 if (result.isEmpty()) {
618 result.append(entry->mString);
619 }
620 return result;
621}
622
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800623const char *sourceToString(audio_source_t source)
624{
625 switch (source) {
626 case AUDIO_SOURCE_DEFAULT: return "default";
627 case AUDIO_SOURCE_MIC: return "mic";
628 case AUDIO_SOURCE_VOICE_UPLINK: return "voice uplink";
629 case AUDIO_SOURCE_VOICE_DOWNLINK: return "voice downlink";
630 case AUDIO_SOURCE_VOICE_CALL: return "voice call";
631 case AUDIO_SOURCE_CAMCORDER: return "camcorder";
632 case AUDIO_SOURCE_VOICE_RECOGNITION: return "voice recognition";
633 case AUDIO_SOURCE_VOICE_COMMUNICATION: return "voice communication";
634 case AUDIO_SOURCE_REMOTE_SUBMIX: return "remote submix";
rago8a397d52015-12-02 11:27:57 -0800635 case AUDIO_SOURCE_UNPROCESSED: return "unprocessed";
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800636 case AUDIO_SOURCE_FM_TUNER: return "FM tuner";
637 case AUDIO_SOURCE_HOTWORD: return "hotword";
638 default: return "unknown";
639 }
640}
641
Eric Laurent81784c32012-11-19 14:55:58 -0800642AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -0700643 audio_devices_t outDevice, audio_devices_t inDevice, type_t type, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -0800644 : Thread(false /*canCallJava*/),
645 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700646 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700647 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800648 // are set by PlaybackThread::readOutputParameters_l() or
649 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700650 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800651 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700652 mPrevOutDevice(AUDIO_DEVICE_NONE), mPrevInDevice(AUDIO_DEVICE_NONE),
653 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800654 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700655 mDeathRecipient(new PMDeathRecipient(this)),
Wei Jia3f273d12015-11-24 09:06:49 -0800656 mSystemReady(systemReady),
657 mNotifiedBatteryStart(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800658{
Eric Laurent296fb132015-05-01 11:38:42 -0700659 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800660}
661
662AudioFlinger::ThreadBase::~ThreadBase()
663{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700664 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700665 mConfigEvents.clear();
666
Eric Laurent81784c32012-11-19 14:55:58 -0800667 // do not lock the mutex in destructor
668 releaseWakeLock_l();
669 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800670 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800671 binder->unlinkToDeath(mDeathRecipient);
672 }
673}
674
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700675status_t AudioFlinger::ThreadBase::readyToRun()
676{
677 status_t status = initCheck();
678 if (status == NO_ERROR) {
679 ALOGI("AudioFlinger's thread %p ready to run", this);
680 } else {
681 ALOGE("No working audio driver found.");
682 }
683 return status;
684}
685
Eric Laurent81784c32012-11-19 14:55:58 -0800686void AudioFlinger::ThreadBase::exit()
687{
688 ALOGV("ThreadBase::exit");
689 // do any cleanup required for exit to succeed
690 preExit();
691 {
692 // This lock prevents the following race in thread (uniprocessor for illustration):
693 // if (!exitPending()) {
694 // // context switch from here to exit()
695 // // exit() calls requestExit(), what exitPending() observes
696 // // exit() calls signal(), which is dropped since no waiters
697 // // context switch back from exit() to here
698 // mWaitWorkCV.wait(...);
699 // // now thread is hung
700 // }
701 AutoMutex lock(mLock);
702 requestExit();
703 mWaitWorkCV.broadcast();
704 }
705 // When Thread::requestExitAndWait is made virtual and this method is renamed to
706 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
707 requestExitAndWait();
708}
709
710status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
711{
Eric Laurent81784c32012-11-19 14:55:58 -0800712 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
713 Mutex::Autolock _l(mLock);
714
Eric Laurent10351942014-05-08 18:49:52 -0700715 return sendSetParameterConfigEvent_l(keyValuePairs);
716}
717
718// sendConfigEvent_l() must be called with ThreadBase::mLock held
719// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
720status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
721{
722 status_t status = NO_ERROR;
723
Eric Laurent72e3f392015-05-20 14:43:50 -0700724 if (event->mRequiresSystemReady && !mSystemReady) {
725 event->mWaitStatus = false;
726 mPendingConfigEvents.add(event);
727 return status;
728 }
Eric Laurent10351942014-05-08 18:49:52 -0700729 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700730 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800731 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700732 mLock.unlock();
733 {
734 Mutex::Autolock _l(event->mLock);
735 while (event->mWaitStatus) {
736 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
737 event->mStatus = TIMED_OUT;
738 event->mWaitStatus = false;
739 }
740 }
741 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800742 }
Eric Laurent10351942014-05-08 18:49:52 -0700743 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800744 return status;
745}
746
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700747void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800748{
749 Mutex::Autolock _l(mLock);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700750 sendIoConfigEvent_l(event, pid);
Eric Laurent81784c32012-11-19 14:55:58 -0800751}
752
753// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700754void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800755{
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700756 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid);
Eric Laurent10351942014-05-08 18:49:52 -0700757 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800758}
759
Eric Laurent72e3f392015-05-20 14:43:50 -0700760void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio)
761{
762 Mutex::Autolock _l(mLock);
763 sendPrioConfigEvent_l(pid, tid, prio);
764}
765
Eric Laurent81784c32012-11-19 14:55:58 -0800766// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
767void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
768{
Eric Laurent10351942014-05-08 18:49:52 -0700769 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio);
770 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800771}
772
Eric Laurent10351942014-05-08 18:49:52 -0700773// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
774status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800775{
Andy Hung2ddee192015-12-18 17:34:44 -0800776 sp<ConfigEvent> configEvent;
777 AudioParameter param(keyValuePair);
778 int value;
779 if (param.getInt(String8(AUDIO_PARAMETER_MONO_OUTPUT), value) == NO_ERROR) {
780 setMasterMono_l(value != 0);
781 if (param.size() == 1) {
782 return NO_ERROR; // should be a solo parameter - we don't pass down
783 }
784 param.remove(String8(AUDIO_PARAMETER_MONO_OUTPUT));
785 configEvent = new SetParameterConfigEvent(param.toString());
786 } else {
787 configEvent = new SetParameterConfigEvent(keyValuePair);
788 }
Eric Laurent10351942014-05-08 18:49:52 -0700789 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700790}
791
Eric Laurent1c333e22014-05-20 10:48:17 -0700792status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
793 const struct audio_patch *patch,
794 audio_patch_handle_t *handle)
795{
796 Mutex::Autolock _l(mLock);
797 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
798 status_t status = sendConfigEvent_l(configEvent);
799 if (status == NO_ERROR) {
800 CreateAudioPatchConfigEventData *data =
801 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
802 *handle = data->mHandle;
803 }
804 return status;
805}
806
807status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
808 const audio_patch_handle_t handle)
809{
810 Mutex::Autolock _l(mLock);
811 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
812 return sendConfigEvent_l(configEvent);
813}
814
815
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700816// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700817void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700818{
Eric Laurent10351942014-05-08 18:49:52 -0700819 bool configChanged = false;
820
Eric Laurent81784c32012-11-19 14:55:58 -0800821 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700822 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700823 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800824 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700825 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700826 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700827 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
828 // FIXME Need to understand why this has to be done asynchronously
829 int err = requestPriority(data->mPid, data->mTid, data->mPrio,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700830 true /*asynchronous*/);
831 if (err != 0) {
832 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700833 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700834 }
835 } break;
836 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700837 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700838 ioConfigChanged(data->mEvent, data->mPid);
Eric Laurent10351942014-05-08 18:49:52 -0700839 } break;
840 case CFG_EVENT_SET_PARAMETER: {
841 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
842 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
843 configChanged = true;
Glenn Kastend5418eb2013-08-14 13:11:06 -0700844 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700845 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700846 case CFG_EVENT_CREATE_AUDIO_PATCH: {
847 CreateAudioPatchConfigEventData *data =
848 (CreateAudioPatchConfigEventData *)event->mData.get();
849 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
850 } break;
851 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
852 ReleaseAudioPatchConfigEventData *data =
853 (ReleaseAudioPatchConfigEventData *)event->mData.get();
854 event->mStatus = releaseAudioPatch_l(data->mHandle);
855 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700856 default:
Eric Laurent10351942014-05-08 18:49:52 -0700857 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700858 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800859 }
Eric Laurent10351942014-05-08 18:49:52 -0700860 {
861 Mutex::Autolock _l(event->mLock);
862 if (event->mWaitStatus) {
863 event->mWaitStatus = false;
864 event->mCond.signal();
865 }
866 }
867 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
868 }
869
870 if (configChanged) {
871 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800872 }
Eric Laurent81784c32012-11-19 14:55:58 -0800873}
874
Marco Nelissenb2208842014-02-07 14:00:50 -0800875String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
876 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700877 const audio_channel_representation_t representation =
878 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700879
880 switch (representation) {
881 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
882 if (output) {
883 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
884 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
885 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
886 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
887 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
888 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
889 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
890 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
891 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
892 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
893 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
894 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
895 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
896 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
897 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
898 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
899 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
900 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
901 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
902 } else {
903 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
904 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
905 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
906 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
907 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
908 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
909 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
910 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
911 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
912 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
913 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
914 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
915 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
916 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
917 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
918 }
919 const int len = s.length();
920 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -0700921 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -0700922 s.unlockBuffer(len - 2); // remove trailing ", "
923 }
924 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800925 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700926 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
927 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
928 return s;
929 default:
930 s.appendFormat("unknown mask, representation:%d bits:%#x",
931 representation, audio_channel_mask_get_bits(mask));
932 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800933 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800934}
935
Glenn Kasten0f11b512014-01-31 16:18:54 -0800936void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800937{
938 const size_t SIZE = 256;
939 char buffer[SIZE];
940 String8 result;
941
942 bool locked = AudioFlinger::dumpTryLock(mLock);
943 if (!locked) {
Glenn Kasten97b7b752014-09-28 13:04:24 -0700944 dprintf(fd, "thread %p may be deadlocked\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -0800945 }
946
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800947 dprintf(fd, " Thread name: %s\n", mThreadName);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700948 dprintf(fd, " I/O handle: %d\n", mId);
949 dprintf(fd, " TID: %d\n", getTid());
950 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700951 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700952 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700953 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat));
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700954 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700955 dprintf(fd, " Channel count: %u\n", mChannelCount);
956 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800957 channelMaskToString(mChannelMask, mType != RECORD).string());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700958 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat));
959 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700960 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800961 size_t numConfig = mConfigEvents.size();
962 if (numConfig) {
963 for (size_t i = 0; i < numConfig; i++) {
964 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700965 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800966 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700967 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800968 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700969 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800970 }
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800971 dprintf(fd, " Output device: %#x (%s)\n", mOutDevice, devicesToString(mOutDevice).string());
972 dprintf(fd, " Input device: %#x (%s)\n", mInDevice, devicesToString(mInDevice).string());
973 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, sourceToString(mAudioSource));
Eric Laurent81784c32012-11-19 14:55:58 -0800974
975 if (locked) {
976 mLock.unlock();
977 }
978}
979
980void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
981{
982 const size_t SIZE = 256;
983 char buffer[SIZE];
984 String8 result;
985
Marco Nelissenb2208842014-02-07 14:00:50 -0800986 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000987 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800988 write(fd, buffer, strlen(buffer));
989
Marco Nelissenb2208842014-02-07 14:00:50 -0800990 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800991 sp<EffectChain> chain = mEffectChains[i];
992 if (chain != 0) {
993 chain->dump(fd, args);
994 }
995 }
996}
997
Marco Nelissene14a5d62013-10-03 08:51:24 -0700998void AudioFlinger::ThreadBase::acquireWakeLock(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800999{
1000 Mutex::Autolock _l(mLock);
Marco Nelissene14a5d62013-10-03 08:51:24 -07001001 acquireWakeLock_l(uid);
Eric Laurent81784c32012-11-19 14:55:58 -08001002}
1003
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001004String16 AudioFlinger::ThreadBase::getWakeLockTag()
1005{
1006 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -08001007 case MIXER:
1008 return String16("AudioMix");
1009 case DIRECT:
1010 return String16("AudioDirectOut");
1011 case DUPLICATING:
1012 return String16("AudioDup");
1013 case RECORD:
1014 return String16("AudioIn");
1015 case OFFLOAD:
1016 return String16("AudioOffload");
1017 default:
1018 ALOG_ASSERT(false);
1019 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001020 }
1021}
1022
Marco Nelissene14a5d62013-10-03 08:51:24 -07001023void AudioFlinger::ThreadBase::acquireWakeLock_l(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -08001024{
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001025 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001026 if (mPowerManager != 0) {
1027 sp<IBinder> binder = new BBinder();
Marco Nelissene14a5d62013-10-03 08:51:24 -07001028 status_t status;
1029 if (uid >= 0) {
Eric Laurent547789d2013-10-04 11:46:55 -07001030 status = mPowerManager->acquireWakeLockWithUid(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -07001031 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001032 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -07001033 String16("audioserver"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -07001034 uid,
1035 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -07001036 } else {
Eric Laurent547789d2013-10-04 11:46:55 -07001037 status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -07001038 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001039 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -07001040 String16("audioserver"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -07001041 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -07001042 }
Eric Laurent81784c32012-11-19 14:55:58 -08001043 if (status == NO_ERROR) {
1044 mWakeLockToken = binder;
1045 }
Glenn Kastend7dca052015-03-05 16:05:54 -08001046 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -08001047 }
Wei Jia3f273d12015-11-24 09:06:49 -08001048
1049 if (!mNotifiedBatteryStart) {
1050 BatteryNotifier::getInstance().noteStartAudio();
1051 mNotifiedBatteryStart = true;
1052 }
Andy Hung3f0c9022016-01-15 17:49:46 -08001053 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -08001054 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
1055 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -08001056}
1057
1058void AudioFlinger::ThreadBase::releaseWakeLock()
1059{
1060 Mutex::Autolock _l(mLock);
1061 releaseWakeLock_l();
1062}
1063
1064void AudioFlinger::ThreadBase::releaseWakeLock_l()
1065{
Andy Hung3f0c9022016-01-15 17:49:46 -08001066 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -08001067 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001068 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001069 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -07001070 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
1071 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -08001072 }
1073 mWakeLockToken.clear();
1074 }
Wei Jia3f273d12015-11-24 09:06:49 -08001075
1076 if (mNotifiedBatteryStart) {
1077 BatteryNotifier::getInstance().noteStopAudio();
1078 mNotifiedBatteryStart = false;
1079 }
Eric Laurent81784c32012-11-19 14:55:58 -08001080}
1081
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001082void AudioFlinger::ThreadBase::updateWakeLockUids(const SortedVector<int> &uids) {
1083 Mutex::Autolock _l(mLock);
1084 updateWakeLockUids_l(uids);
1085}
1086
1087void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -07001088 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001089 // use checkService() to avoid blocking if power service is not up yet
1090 sp<IBinder> binder =
1091 defaultServiceManager()->checkService(String16("power"));
1092 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001093 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001094 } else {
1095 mPowerManager = interface_cast<IPowerManager>(binder);
1096 binder->linkToDeath(mDeathRecipient);
1097 }
1098 }
1099}
1100
1101void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<int> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001102 getPowerManager_l();
Andy Hung438e7572015-12-14 15:51:17 -08001103 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
1104 if (mSystemReady) {
1105 ALOGE("no wake lock to update, but system ready!");
1106 } else {
1107 ALOGW("no wake lock to update, system not ready yet");
1108 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001109 return;
1110 }
1111 if (mPowerManager != 0) {
1112 sp<IBinder> binder = new BBinder();
1113 status_t status;
Glenn Kasten3abc2de2014-09-05 16:45:52 -07001114 status = mPowerManager->updateWakeLockUids(mWakeLockToken, uids.size(), uids.array(),
1115 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent4d231dc2016-03-11 18:38:23 -08001116 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001117 }
1118}
1119
Eric Laurent81784c32012-11-19 14:55:58 -08001120void AudioFlinger::ThreadBase::clearPowerManager()
1121{
1122 Mutex::Autolock _l(mLock);
1123 releaseWakeLock_l();
1124 mPowerManager.clear();
1125}
1126
Glenn Kasten0f11b512014-01-31 16:18:54 -08001127void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001128{
1129 sp<ThreadBase> thread = mThread.promote();
1130 if (thread != 0) {
1131 thread->clearPowerManager();
1132 }
1133 ALOGW("power manager service died !!!");
1134}
1135
1136void AudioFlinger::ThreadBase::setEffectSuspended(
Glenn Kastend848eb42016-03-08 13:42:11 -08001137 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001138{
1139 Mutex::Autolock _l(mLock);
1140 setEffectSuspended_l(type, suspend, sessionId);
1141}
1142
1143void AudioFlinger::ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001144 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001145{
1146 sp<EffectChain> chain = getEffectChain_l(sessionId);
1147 if (chain != 0) {
1148 if (type != NULL) {
1149 chain->setEffectSuspended_l(type, suspend);
1150 } else {
1151 chain->setEffectSuspendedAll_l(suspend);
1152 }
1153 }
1154
1155 updateSuspendedSessions_l(type, suspend, sessionId);
1156}
1157
1158void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1159{
1160 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1161 if (index < 0) {
1162 return;
1163 }
1164
1165 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1166 mSuspendedSessions.valueAt(index);
1167
1168 for (size_t i = 0; i < sessionEffects.size(); i++) {
1169 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1170 for (int j = 0; j < desc->mRefCount; j++) {
1171 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1172 chain->setEffectSuspendedAll_l(true);
1173 } else {
1174 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1175 desc->mType.timeLow);
1176 chain->setEffectSuspended_l(&desc->mType, true);
1177 }
1178 }
1179 }
1180}
1181
1182void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1183 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001184 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001185{
1186 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1187
1188 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1189
1190 if (suspend) {
1191 if (index >= 0) {
1192 sessionEffects = mSuspendedSessions.valueAt(index);
1193 } else {
1194 mSuspendedSessions.add(sessionId, sessionEffects);
1195 }
1196 } else {
1197 if (index < 0) {
1198 return;
1199 }
1200 sessionEffects = mSuspendedSessions.valueAt(index);
1201 }
1202
1203
1204 int key = EffectChain::kKeyForSuspendAll;
1205 if (type != NULL) {
1206 key = type->timeLow;
1207 }
1208 index = sessionEffects.indexOfKey(key);
1209
1210 sp<SuspendedSessionDesc> desc;
1211 if (suspend) {
1212 if (index >= 0) {
1213 desc = sessionEffects.valueAt(index);
1214 } else {
1215 desc = new SuspendedSessionDesc();
1216 if (type != NULL) {
1217 desc->mType = *type;
1218 }
1219 sessionEffects.add(key, desc);
1220 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1221 }
1222 desc->mRefCount++;
1223 } else {
1224 if (index < 0) {
1225 return;
1226 }
1227 desc = sessionEffects.valueAt(index);
1228 if (--desc->mRefCount == 0) {
1229 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1230 sessionEffects.removeItemsAt(index);
1231 if (sessionEffects.isEmpty()) {
1232 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1233 sessionId);
1234 mSuspendedSessions.removeItem(sessionId);
1235 }
1236 }
1237 }
1238 if (!sessionEffects.isEmpty()) {
1239 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1240 }
1241}
1242
1243void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1244 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001245 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001246{
1247 Mutex::Autolock _l(mLock);
1248 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1249}
1250
1251void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1252 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001253 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001254{
1255 if (mType != RECORD) {
1256 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1257 // another session. This gives the priority to well behaved effect control panels
1258 // and applications not using global effects.
1259 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1260 // global effects
1261 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1262 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1263 }
1264 }
1265
1266 sp<EffectChain> chain = getEffectChain_l(sessionId);
1267 if (chain != 0) {
1268 chain->checkSuspendOnEffectEnabled(effect, enabled);
1269 }
1270}
1271
1272// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1273sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1274 const sp<AudioFlinger::Client>& client,
1275 const sp<IEffectClient>& effectClient,
1276 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001277 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001278 effect_descriptor_t *desc,
1279 int *enabled,
Glenn Kasten9156ef32013-08-06 15:39:08 -07001280 status_t *status)
Eric Laurent81784c32012-11-19 14:55:58 -08001281{
1282 sp<EffectModule> effect;
1283 sp<EffectHandle> handle;
1284 status_t lStatus;
1285 sp<EffectChain> chain;
1286 bool chainCreated = false;
1287 bool effectCreated = false;
1288 bool effectRegistered = false;
1289
1290 lStatus = initCheck();
1291 if (lStatus != NO_ERROR) {
1292 ALOGW("createEffect_l() Audio driver not initialized.");
1293 goto Exit;
1294 }
1295
Andy Hung98ef9782014-03-04 14:46:50 -08001296 // Reject any effect on Direct output threads for now, since the format of
1297 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1298 if (mType == DIRECT) {
1299 ALOGW("createEffect_l() Cannot add effect %s on Direct output type thread %s",
Glenn Kastend7dca052015-03-05 16:05:54 -08001300 desc->name, mThreadName);
Andy Hung98ef9782014-03-04 14:46:50 -08001301 lStatus = BAD_VALUE;
1302 goto Exit;
1303 }
1304
Andy Hung389cfdb2014-08-07 17:49:53 -07001305 // Reject any effect on mixer or duplicating multichannel sinks.
Andy Hung9a592762014-07-21 21:56:01 -07001306 // TODO: fix both format and multichannel issues with effects.
Andy Hung389cfdb2014-08-07 17:49:53 -07001307 if ((mType == MIXER || mType == DUPLICATING) && mChannelCount != FCC_2) {
1308 ALOGW("createEffect_l() Cannot add effect %s for multichannel(%d) %s threads",
1309 desc->name, mChannelCount, mType == MIXER ? "MIXER" : "DUPLICATING");
Andy Hung9a592762014-07-21 21:56:01 -07001310 lStatus = BAD_VALUE;
1311 goto Exit;
1312 }
1313
Eric Laurent5baf2af2013-09-12 17:37:00 -07001314 // Allow global effects only on offloaded and mixer threads
1315 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1316 switch (mType) {
1317 case MIXER:
1318 case OFFLOAD:
1319 break;
1320 case DIRECT:
1321 case DUPLICATING:
1322 case RECORD:
1323 default:
Glenn Kastend7dca052015-03-05 16:05:54 -08001324 ALOGW("createEffect_l() Cannot add global effect %s on thread %s",
1325 desc->name, mThreadName);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001326 lStatus = BAD_VALUE;
1327 goto Exit;
1328 }
Eric Laurent81784c32012-11-19 14:55:58 -08001329 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001330
Eric Laurent81784c32012-11-19 14:55:58 -08001331 // Only Pre processor effects are allowed on input threads and only on input threads
1332 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
1333 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
1334 desc->name, desc->flags, mType);
1335 lStatus = BAD_VALUE;
1336 goto Exit;
1337 }
1338
1339 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1340
1341 { // scope for mLock
1342 Mutex::Autolock _l(mLock);
1343
1344 // check for existing effect chain with the requested audio session
1345 chain = getEffectChain_l(sessionId);
1346 if (chain == 0) {
1347 // create a new chain for this session
1348 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1349 chain = new EffectChain(this, sessionId);
1350 addEffectChain_l(chain);
1351 chain->setStrategy(getStrategyForSession_l(sessionId));
1352 chainCreated = true;
1353 } else {
1354 effect = chain->getEffectFromDesc_l(desc);
1355 }
1356
1357 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1358
1359 if (effect == 0) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08001360 audio_unique_id_t id = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001361 // Check CPU and memory usage
1362 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
1363 if (lStatus != NO_ERROR) {
1364 goto Exit;
1365 }
1366 effectRegistered = true;
1367 // create a new effect module if none present in the chain
1368 effect = new EffectModule(this, chain, desc, id, sessionId);
1369 lStatus = effect->status();
1370 if (lStatus != NO_ERROR) {
1371 goto Exit;
1372 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001373 effect->setOffloaded(mType == OFFLOAD, mId);
1374
Eric Laurent81784c32012-11-19 14:55:58 -08001375 lStatus = chain->addEffect_l(effect);
1376 if (lStatus != NO_ERROR) {
1377 goto Exit;
1378 }
1379 effectCreated = true;
1380
1381 effect->setDevice(mOutDevice);
1382 effect->setDevice(mInDevice);
1383 effect->setMode(mAudioFlinger->getMode());
1384 effect->setAudioSource(mAudioSource);
1385 }
1386 // create effect handle and connect it to effect module
1387 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001388 lStatus = handle->initCheck();
1389 if (lStatus == OK) {
1390 lStatus = effect->addHandle(handle.get());
1391 }
Eric Laurent81784c32012-11-19 14:55:58 -08001392 if (enabled != NULL) {
1393 *enabled = (int)effect->isEnabled();
1394 }
1395 }
1396
1397Exit:
1398 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1399 Mutex::Autolock _l(mLock);
1400 if (effectCreated) {
1401 chain->removeEffect_l(effect);
1402 }
1403 if (effectRegistered) {
1404 AudioSystem::unregisterEffect(effect->id());
1405 }
1406 if (chainCreated) {
1407 removeEffectChain_l(chain);
1408 }
1409 handle.clear();
1410 }
1411
Glenn Kasten9156ef32013-08-06 15:39:08 -07001412 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001413 return handle;
1414}
1415
Glenn Kastend848eb42016-03-08 13:42:11 -08001416sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1417 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001418{
1419 Mutex::Autolock _l(mLock);
1420 return getEffect_l(sessionId, effectId);
1421}
1422
Glenn Kastend848eb42016-03-08 13:42:11 -08001423sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1424 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001425{
1426 sp<EffectChain> chain = getEffectChain_l(sessionId);
1427 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1428}
1429
1430// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1431// PlaybackThread::mLock held
1432status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1433{
1434 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001435 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001436 sp<EffectChain> chain = getEffectChain_l(sessionId);
1437 bool chainCreated = false;
1438
Eric Laurent5baf2af2013-09-12 17:37:00 -07001439 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1440 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1441 this, effect->desc().name, effect->desc().flags);
1442
Eric Laurent81784c32012-11-19 14:55:58 -08001443 if (chain == 0) {
1444 // create a new chain for this session
1445 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1446 chain = new EffectChain(this, sessionId);
1447 addEffectChain_l(chain);
1448 chain->setStrategy(getStrategyForSession_l(sessionId));
1449 chainCreated = true;
1450 }
1451 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1452
1453 if (chain->getEffectFromId_l(effect->id()) != 0) {
1454 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1455 this, effect->desc().name, chain.get());
1456 return BAD_VALUE;
1457 }
1458
Eric Laurent5baf2af2013-09-12 17:37:00 -07001459 effect->setOffloaded(mType == OFFLOAD, mId);
1460
Eric Laurent81784c32012-11-19 14:55:58 -08001461 status_t status = chain->addEffect_l(effect);
1462 if (status != NO_ERROR) {
1463 if (chainCreated) {
1464 removeEffectChain_l(chain);
1465 }
1466 return status;
1467 }
1468
1469 effect->setDevice(mOutDevice);
1470 effect->setDevice(mInDevice);
1471 effect->setMode(mAudioFlinger->getMode());
1472 effect->setAudioSource(mAudioSource);
1473 return NO_ERROR;
1474}
1475
1476void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
1477
1478 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
1479 effect_descriptor_t desc = effect->desc();
1480 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1481 detachAuxEffect_l(effect->id());
1482 }
1483
1484 sp<EffectChain> chain = effect->chain().promote();
1485 if (chain != 0) {
1486 // remove effect chain if removing last effect
1487 if (chain->removeEffect_l(effect) == 0) {
1488 removeEffectChain_l(chain);
1489 }
1490 } else {
1491 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1492 }
1493}
1494
1495void AudioFlinger::ThreadBase::lockEffectChains_l(
1496 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1497{
1498 effectChains = mEffectChains;
1499 for (size_t i = 0; i < mEffectChains.size(); i++) {
1500 mEffectChains[i]->lock();
1501 }
1502}
1503
1504void AudioFlinger::ThreadBase::unlockEffectChains(
1505 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1506{
1507 for (size_t i = 0; i < effectChains.size(); i++) {
1508 effectChains[i]->unlock();
1509 }
1510}
1511
Glenn Kastend848eb42016-03-08 13:42:11 -08001512sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001513{
1514 Mutex::Autolock _l(mLock);
1515 return getEffectChain_l(sessionId);
1516}
1517
Glenn Kastend848eb42016-03-08 13:42:11 -08001518sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1519 const
Eric Laurent81784c32012-11-19 14:55:58 -08001520{
1521 size_t size = mEffectChains.size();
1522 for (size_t i = 0; i < size; i++) {
1523 if (mEffectChains[i]->sessionId() == sessionId) {
1524 return mEffectChains[i];
1525 }
1526 }
1527 return 0;
1528}
1529
1530void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1531{
1532 Mutex::Autolock _l(mLock);
1533 size_t size = mEffectChains.size();
1534 for (size_t i = 0; i < size; i++) {
1535 mEffectChains[i]->setMode_l(mode);
1536 }
1537}
1538
Eric Laurent83b88082014-06-20 18:31:16 -07001539void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1540{
1541 config->type = AUDIO_PORT_TYPE_MIX;
1542 config->ext.mix.handle = mId;
1543 config->sample_rate = mSampleRate;
1544 config->format = mFormat;
1545 config->channel_mask = mChannelMask;
1546 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1547 AUDIO_PORT_CONFIG_FORMAT;
1548}
1549
Eric Laurent72e3f392015-05-20 14:43:50 -07001550void AudioFlinger::ThreadBase::systemReady()
1551{
1552 Mutex::Autolock _l(mLock);
1553 if (mSystemReady) {
1554 return;
1555 }
1556 mSystemReady = true;
1557
1558 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1559 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1560 }
1561 mPendingConfigEvents.clear();
1562}
1563
Eric Laurent83b88082014-06-20 18:31:16 -07001564
Eric Laurent81784c32012-11-19 14:55:58 -08001565// ----------------------------------------------------------------------------
1566// Playback
1567// ----------------------------------------------------------------------------
1568
1569AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1570 AudioStreamOut* output,
1571 audio_io_handle_t id,
1572 audio_devices_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07001573 type_t type,
Eric Laurent51716182016-02-29 18:00:56 -08001574 bool systemReady,
1575 uint32_t bitRate)
Eric Laurent72e3f392015-05-20 14:43:50 -07001576 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001577 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001578 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001579 mMixerBuffer(NULL),
1580 mMixerBufferSize(0),
1581 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1582 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001583 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001584 mEffectBuffer(NULL),
1585 mEffectBufferSize(0),
1586 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1587 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001588 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001589 mFramesWritten(0),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001590 mActiveTracksGeneration(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001591 // mStreamTypes[] initialized in constructor body
1592 mOutput(output),
1593 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
1594 mMixerStatus(MIXER_IDLE),
1595 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001596 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001597 mBytesRemaining(0),
1598 mCurrentWriteLength(0),
1599 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001600 mWriteAckSequence(0),
1601 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001602 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001603 mScreenState(AudioFlinger::mScreenState),
1604 // index 0 is reserved for normal mixer's submix
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001605 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1),
Andy Hunge10393e2015-06-12 13:59:33 -07001606 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001607{
Glenn Kastend7dca052015-03-05 16:05:54 -08001608 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1609 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001610
1611 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1612 // it would be safer to explicitly pass initial masterVolume/masterMute as
1613 // parameter.
1614 //
1615 // If the HAL we are using has support for master volume or master mute,
1616 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1617 // and the mute set to false).
1618 mMasterVolume = audioFlinger->masterVolume_l();
1619 mMasterMute = audioFlinger->masterMute_l();
1620 if (mOutput && mOutput->audioHwDev) {
1621 if (mOutput->audioHwDev->canSetMasterVolume()) {
1622 mMasterVolume = 1.0;
1623 }
1624
1625 if (mOutput->audioHwDev->canSetMasterMute()) {
1626 mMasterMute = false;
1627 }
1628 }
1629
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001630 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001631
Eric Laurent223fd5c2014-11-11 13:43:36 -08001632 // ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001633 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001634 stream = (audio_stream_type_t) (stream + 1)) {
1635 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1636 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1637 }
Eric Laurent51716182016-02-29 18:00:56 -08001638
1639 if (audio_has_proportional_frames(mFormat)) {
1640 mBufferDurationUs = (uint32_t)((mNormalFrameCount * 1000000LL) / mSampleRate);
1641 } else {
1642 bitRate = bitRate != 0 ? bitRate : kOffloadDefaultBitRateBps;
1643 mBufferDurationUs = (uint32_t)((mBufferSize * 8 * 1000000LL) / bitRate);
1644 }
Eric Laurent81784c32012-11-19 14:55:58 -08001645}
1646
1647AudioFlinger::PlaybackThread::~PlaybackThread()
1648{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001649 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001650 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001651 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001652 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001653}
1654
1655void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1656{
1657 dumpInternals(fd, args);
1658 dumpTracks(fd, args);
1659 dumpEffectChains(fd, args);
1660}
1661
Glenn Kasten0f11b512014-01-31 16:18:54 -08001662void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001663{
1664 const size_t SIZE = 256;
1665 char buffer[SIZE];
1666 String8 result;
1667
Marco Nelissenb2208842014-02-07 14:00:50 -08001668 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001669 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1670 const stream_type_t *st = &mStreamTypes[i];
1671 if (i > 0) {
1672 result.appendFormat(", ");
1673 }
1674 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1675 if (st->mute) {
1676 result.append("M");
1677 }
1678 }
1679 result.append("\n");
1680 write(fd, result.string(), result.length());
1681 result.clear();
1682
Eric Laurent81784c32012-11-19 14:55:58 -08001683 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1684 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001685 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001686 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001687
1688 size_t numtracks = mTracks.size();
1689 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001690 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001691 size_t numactiveseen = 0;
1692 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001693 dprintf(fd, " of which %zu are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001694 Track::appendDumpHeader(result);
1695 for (size_t i = 0; i < numtracks; ++i) {
1696 sp<Track> track = mTracks[i];
1697 if (track != 0) {
1698 bool active = mActiveTracks.indexOf(track) >= 0;
1699 if (active) {
1700 numactiveseen++;
1701 }
1702 track->dump(buffer, SIZE, active);
1703 result.append(buffer);
1704 }
1705 }
1706 } else {
1707 result.append("\n");
1708 }
1709 if (numactiveseen != numactive) {
1710 // some tracks in the active list were not in the tracks list
1711 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1712 " not in the track list\n");
1713 result.append(buffer);
1714 Track::appendDumpHeader(result);
1715 for (size_t i = 0; i < numactive; ++i) {
1716 sp<Track> track = mActiveTracks[i].promote();
1717 if (track != 0 && mTracks.indexOf(track) < 0) {
1718 track->dump(buffer, SIZE, true);
1719 result.append(buffer);
1720 }
1721 }
1722 }
1723
1724 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001725}
1726
1727void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1728{
Glenn Kasten97b7b752014-09-28 13:04:24 -07001729 dprintf(fd, "\nOutput thread %p type %d (%s):\n", this, type(), threadTypeToString(type()));
Glenn Kasten44182c22015-03-05 17:12:23 -08001730
1731 dumpBase(fd, args);
1732
Elliott Hughes87cebad2014-05-22 10:14:43 -07001733 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001734 dprintf(fd, " Last write occurred (msecs): %llu\n",
1735 (unsigned long long) ns2ms(systemTime() - mLastWriteTime));
Elliott Hughes87cebad2014-05-22 10:14:43 -07001736 dprintf(fd, " Total writes: %d\n", mNumWrites);
1737 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1738 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1739 dprintf(fd, " Suspend count: %d\n", mSuspended);
1740 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1741 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1742 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1743 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08001744 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001745 AudioStreamOut *output = mOutput;
1746 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
1747 String8 flagsAsString = outputFlagsToString(flags);
1748 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n", output, flags, flagsAsString.string());
Eric Laurent81784c32012-11-19 14:55:58 -08001749}
1750
1751// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001752
1753void AudioFlinger::PlaybackThread::onFirstRef()
1754{
Glenn Kastend7dca052015-03-05 16:05:54 -08001755 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001756}
1757
1758// ThreadBase virtuals
1759void AudioFlinger::PlaybackThread::preExit()
1760{
1761 ALOGV(" preExit()");
1762 // FIXME this is using hard-coded strings but in the future, this functionality will be
1763 // converted to use audio HAL extensions required to support tunneling
1764 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1765}
1766
1767// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1768sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1769 const sp<AudioFlinger::Client>& client,
1770 audio_stream_type_t streamType,
1771 uint32_t sampleRate,
1772 audio_format_t format,
1773 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001774 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001775 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08001776 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001777 IAudioFlinger::track_flags_t *flags,
1778 pid_t tid,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001779 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -08001780 status_t *status)
1781{
Glenn Kasten74935e42013-12-19 08:56:45 -08001782 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001783 sp<Track> track;
1784 status_t lStatus;
1785
Eric Laurent81784c32012-11-19 14:55:58 -08001786 // client expresses a preference for FAST, but we get the final say
1787 if (*flags & IAudioFlinger::TRACK_FAST) {
1788 if (
Eric Laurent81784c32012-11-19 14:55:58 -08001789 // PCM data
1790 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001791 // TODO: extract as a data library function that checks that a computationally
1792 // expensive downmixer is not required: isFastOutputChannelConversion()
Andy Hung9a592762014-07-21 21:56:01 -07001793 (channelMask == mChannelMask ||
Andy Hung1f439e12015-05-19 12:57:41 -07001794 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1795 (channelMask == AUDIO_CHANNEL_OUT_MONO
1796 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001797 // hardware sample rate
1798 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001799 // normal mixer has an associated fast mixer
1800 hasFastMixer() &&
1801 // there are sufficient fast track slots available
1802 (mFastTrackAvailMask != 0)
1803 // FIXME test that MixerThread for this fast track has a capable output HAL
1804 // FIXME add a permission test also?
1805 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07001806 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
1807 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001808 // read the fast track multiplier property the first time it is needed
1809 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1810 if (ok != 0) {
1811 ALOGE("%s pthread_once failed: %d", __func__, ok);
1812 }
Andy Hunge0a269a2016-03-23 15:13:42 -07001813 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08001814 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001815 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08001816 frameCount, mFrameCount);
1817 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001818 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
1819 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07001820 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001821 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08001822 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001823 audio_is_linear_pcm(format),
1824 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1825 *flags &= ~IAudioFlinger::TRACK_FAST;
Andy Hung0e48d252015-01-26 11:43:15 -08001826 }
1827 }
1828 // For normal PCM streaming tracks, update minimum frame count.
1829 // For compatibility with AudioTrack calculation, buffer depth is forced
1830 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1831 // This is probably too conservative, but legacy application code may depend on it.
1832 // If you change this calculation, also review the start threshold which is related.
1833 if (!(*flags & IAudioFlinger::TRACK_FAST)
Phil Burkfdb3c072016-02-09 10:47:02 -08001834 && audio_has_proportional_frames(format) && sharedBuffer == 0) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001835 // this must match AudioTrack.cpp calculateMinFrameCount().
1836 // TODO: Move to a common library
Eric Laurent81784c32012-11-19 14:55:58 -08001837 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1838 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1839 if (minBufCount < 2) {
1840 minBufCount = 2;
1841 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07001842 // For normal mixing tracks, if speed is > 1.0f (normal), AudioTrack
1843 // or the client should compute and pass in a larger buffer request.
Andy Hung0e48d252015-01-26 11:43:15 -08001844 size_t minFrameCount =
Andy Hung8edb8dc2015-03-26 19:13:55 -07001845 minBufCount * sourceFramesNeededWithTimestretch(
1846 sampleRate, mNormalFrameCount,
1847 mSampleRate, AUDIO_TIMESTRETCH_SPEED_NORMAL /*speed*/);
Andy Hung0e48d252015-01-26 11:43:15 -08001848 if (frameCount < minFrameCount) { // including frameCount == 0
Eric Laurent81784c32012-11-19 14:55:58 -08001849 frameCount = minFrameCount;
1850 }
Eric Laurent81784c32012-11-19 14:55:58 -08001851 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001852 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001853
Glenn Kastenc3df8382014-03-13 15:05:25 -07001854 switch (mType) {
1855
1856 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08001857 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08001858 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001859 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1860 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001861 sampleRate, format, channelMask, mOutput, mFormat);
1862 lStatus = BAD_VALUE;
1863 goto Exit;
1864 }
1865 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001866 break;
1867
1868 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001869 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001870 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1871 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001872 sampleRate, format, channelMask, mOutput, mFormat);
1873 lStatus = BAD_VALUE;
1874 goto Exit;
1875 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001876 break;
1877
1878 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001879 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001880 ALOGE("createTrack_l() Bad parameter: format %#x \""
1881 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001882 format, mOutput, mFormat);
1883 lStatus = BAD_VALUE;
1884 goto Exit;
1885 }
Andy Hungcd044842014-08-07 11:04:34 -07001886 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08001887 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1888 lStatus = BAD_VALUE;
1889 goto Exit;
1890 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001891 break;
1892
Eric Laurent81784c32012-11-19 14:55:58 -08001893 }
1894
1895 lStatus = initCheck();
1896 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001897 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08001898 goto Exit;
1899 }
1900
1901 { // scope for mLock
1902 Mutex::Autolock _l(mLock);
1903
1904 // all tracks in same audio session must share the same routing strategy otherwise
1905 // conflicts will happen when tracks are moved from one output to another by audio policy
1906 // manager
1907 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1908 for (size_t i = 0; i < mTracks.size(); ++i) {
1909 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07001910 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001911 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1912 if (sessionId == t->sessionId() && strategy != actual) {
1913 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1914 strategy, actual);
1915 lStatus = BAD_VALUE;
1916 goto Exit;
1917 }
1918 }
1919 }
1920
Glenn Kastend79072e2016-01-06 08:41:20 -08001921 track = new Track(this, client, streamType, sampleRate, format,
1922 channelMask, frameCount, NULL, sharedBuffer,
1923 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT);
Glenn Kasten03003332013-08-06 15:40:54 -07001924
Glenn Kasten03003332013-08-06 15:40:54 -07001925 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1926 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08001927 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001928 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08001929 goto Exit;
1930 }
1931 mTracks.add(track);
1932
1933 sp<EffectChain> chain = getEffectChain_l(sessionId);
1934 if (chain != 0) {
1935 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1936 track->setMainBuffer(chain->inBuffer());
1937 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1938 chain->incTrackCnt();
1939 }
1940
1941 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1942 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1943 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1944 // so ask activity manager to do this on our behalf
1945 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1946 }
1947 }
1948
1949 lStatus = NO_ERROR;
1950
1951Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001952 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001953 return track;
1954}
1955
1956uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1957{
1958 return latency;
1959}
1960
1961uint32_t AudioFlinger::PlaybackThread::latency() const
1962{
1963 Mutex::Autolock _l(mLock);
1964 return latency_l();
1965}
1966uint32_t AudioFlinger::PlaybackThread::latency_l() const
1967{
1968 if (initCheck() == NO_ERROR) {
1969 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1970 } else {
1971 return 0;
1972 }
1973}
1974
1975void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1976{
1977 Mutex::Autolock _l(mLock);
1978 // Don't apply master volume in SW if our HAL can do it for us.
1979 if (mOutput && mOutput->audioHwDev &&
1980 mOutput->audioHwDev->canSetMasterVolume()) {
1981 mMasterVolume = 1.0;
1982 } else {
1983 mMasterVolume = value;
1984 }
1985}
1986
1987void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1988{
1989 Mutex::Autolock _l(mLock);
1990 // Don't apply master mute in SW if our HAL can do it for us.
1991 if (mOutput && mOutput->audioHwDev &&
1992 mOutput->audioHwDev->canSetMasterMute()) {
1993 mMasterMute = false;
1994 } else {
1995 mMasterMute = muted;
1996 }
1997}
1998
1999void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2000{
2001 Mutex::Autolock _l(mLock);
2002 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002003 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002004}
2005
2006void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2007{
2008 Mutex::Autolock _l(mLock);
2009 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002010 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002011}
2012
2013float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2014{
2015 Mutex::Autolock _l(mLock);
2016 return mStreamTypes[stream].volume;
2017}
2018
2019// addTrack_l() must be called with ThreadBase::mLock held
2020status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2021{
2022 status_t status = ALREADY_EXISTS;
2023
Eric Laurent81784c32012-11-19 14:55:58 -08002024 if (mActiveTracks.indexOf(track) < 0) {
2025 // the track is newly added, make sure it fills up all its
2026 // buffers before playing. This is to ensure the client will
2027 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002028 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002029 TrackBase::track_state state = track->mState;
2030 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002031 status = AudioSystem::startOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002032 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002033 mLock.lock();
2034 // abort track was stopped/paused while we released the lock
2035 if (state != track->mState) {
2036 if (status == NO_ERROR) {
2037 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002038 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002039 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002040 mLock.lock();
2041 }
2042 return INVALID_OPERATION;
2043 }
2044 // abort if start is rejected by audio policy manager
2045 if (status != NO_ERROR) {
2046 return PERMISSION_DENIED;
2047 }
2048#ifdef ADD_BATTERY_DATA
2049 // to track the speaker usage
2050 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2051#endif
2052 }
2053
Eric Laurent51716182016-02-29 18:00:56 -08002054 // set retry count for buffer fill
2055 if (track->isOffloaded()) {
2056 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2057 } else {
2058 track->mRetryCount = kMaxTrackStartupRetries;
2059 }
2060
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002061 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08002062 track->mResetDone = false;
2063 track->mPresentationCompleteFrames = 0;
2064 mActiveTracks.add(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002065 mWakeLockUids.add(track->uid());
2066 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07002067 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07002068 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2069 if (chain != 0) {
2070 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2071 track->sessionId());
2072 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002073 }
2074
2075 status = NO_ERROR;
2076 }
2077
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002078 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002079 return status;
2080}
2081
Eric Laurentbfb1b832013-01-07 09:53:42 -08002082bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002083{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002084 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002085 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002086 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2087 track->mState = TrackBase::STOPPED;
2088 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002089 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002090 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002091 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002092 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002093
2094 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002095}
2096
2097void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2098{
2099 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
2100 mTracks.remove(track);
2101 deleteTrackName_l(track->name());
2102 // redundant as track is about to be destroyed, for dumpsys only
2103 track->mName = -1;
2104 if (track->isFastTrack()) {
2105 int index = track->mFastIndex;
2106 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
2107 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2108 mFastTrackAvailMask |= 1 << index;
2109 // redundant as track is about to be destroyed, for dumpsys only
2110 track->mFastIndex = -1;
2111 }
2112 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2113 if (chain != 0) {
2114 chain->decTrackCnt();
2115 }
2116}
2117
Eric Laurentede6c3b2013-09-19 14:37:46 -07002118void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002119{
2120 // Thread could be blocked waiting for async
2121 // so signal it to handle state changes immediately
2122 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
2123 // be lost so we also flag to prevent it blocking on mWaitWorkCV
2124 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002125 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002126}
2127
Eric Laurent81784c32012-11-19 14:55:58 -08002128String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2129{
Eric Laurent81784c32012-11-19 14:55:58 -08002130 Mutex::Autolock _l(mLock);
2131 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07002132 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002133 }
2134
Glenn Kastend8ea6992013-07-16 14:17:15 -07002135 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
2136 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08002137 free(s);
2138 return out_s8;
2139}
2140
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002141void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002142 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2143 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002144
Eric Laurent73e26b62015-04-27 16:55:58 -07002145 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002146
2147 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002148 case AUDIO_OUTPUT_OPENED:
2149 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002150 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002151 desc->mChannelMask = mChannelMask;
2152 desc->mSamplingRate = mSampleRate;
2153 desc->mFormat = mFormat;
2154 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002155 // AudioFlinger::frameCount(audio_io_handle_t)
Eric Laurent73e26b62015-04-27 16:55:58 -07002156 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002157 break;
2158
Eric Laurent73e26b62015-04-27 16:55:58 -07002159 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002160 default:
2161 break;
2162 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002163 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002164}
2165
Eric Laurentbfb1b832013-01-07 09:53:42 -08002166void AudioFlinger::PlaybackThread::writeCallback()
2167{
2168 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002169 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002170}
2171
2172void AudioFlinger::PlaybackThread::drainCallback()
2173{
2174 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002175 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002176}
2177
Eric Laurent3b4529e2013-09-05 18:09:19 -07002178void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002179{
2180 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002181 // reject out of sequence requests
2182 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2183 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002184 mWaitWorkCV.signal();
2185 }
2186}
2187
Eric Laurent3b4529e2013-09-05 18:09:19 -07002188void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002189{
2190 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002191 // reject out of sequence requests
2192 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
2193 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002194 mWaitWorkCV.signal();
2195 }
2196}
2197
2198// static
2199int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
Glenn Kasten0f11b512014-01-31 16:18:54 -08002200 void *param __unused,
Eric Laurentbfb1b832013-01-07 09:53:42 -08002201 void *cookie)
2202{
2203 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
2204 ALOGV("asyncCallback() event %d", event);
2205 switch (event) {
2206 case STREAM_CBK_EVENT_WRITE_READY:
2207 me->writeCallback();
2208 break;
2209 case STREAM_CBK_EVENT_DRAIN_READY:
2210 me->drainCallback();
2211 break;
2212 default:
2213 ALOGW("asyncCallback() unknown event %d", event);
2214 break;
2215 }
2216 return 0;
2217}
2218
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002219void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002220{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002221 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002222 mSampleRate = mOutput->getSampleRate();
2223 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002224 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002225 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002226 }
Andy Hung9a592762014-07-21 21:56:01 -07002227 if ((mType == MIXER || mType == DUPLICATING)
2228 && !isValidPcmSinkChannelMask(mChannelMask)) {
2229 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2230 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002231 }
Andy Hunge5412692014-05-16 11:25:07 -07002232 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002233
2234 // Get actual HAL format.
Andy Hung463be252014-07-10 16:56:07 -07002235 mHALFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Phil Burkca5e6142015-07-14 09:42:29 -07002236 // Get format from the shim, which will be different than the HAL format
2237 // if playing compressed audio over HDMI passthrough.
2238 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002239 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002240 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002241 }
Andy Hung6146c082014-03-18 11:56:15 -07002242 if ((mType == MIXER || mType == DUPLICATING)
2243 && !isValidPcmSinkFormat(mFormat)) {
2244 LOG_FATAL("HAL format %#x not supported for mixed output",
2245 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002246 }
Phil Burk062e67a2015-02-11 13:40:50 -08002247 mFrameSize = mOutput->getFrameSize();
Glenn Kasten70949c42013-08-06 07:40:12 -07002248 mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
2249 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002250 if (mFrameCount & 15) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002251 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002252 mFrameCount);
2253 }
2254
Eric Laurentbfb1b832013-01-07 09:53:42 -08002255 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
2256 (mOutput->stream->set_callback != NULL)) {
2257 if (mOutput->stream->set_callback(mOutput->stream,
2258 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
2259 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002260 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002261 }
2262 }
2263
Eric Laurentd1f69b02014-12-15 14:33:13 -08002264 mHwSupportsPause = false;
2265 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
2266 if (mOutput->stream->pause != NULL) {
2267 if (mOutput->stream->resume != NULL) {
2268 mHwSupportsPause = true;
2269 } else {
2270 ALOGW("direct output implements pause but not resume");
2271 }
2272 } else if (mOutput->stream->resume != NULL) {
2273 ALOGW("direct output implements resume but not pause");
2274 }
2275 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002276 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2277 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2278 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002279
Andy Hungfbfc3952015-01-15 13:33:51 -08002280 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2281 // For best precision, we use float instead of the associated output
2282 // device format (typically PCM 16 bit).
2283
2284 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2285 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2286 mBufferSize = mFrameSize * mFrameCount;
2287
2288 // TODO: We currently use the associated output device channel mask and sample rate.
2289 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2290 // (if a valid mask) to avoid premature downmix.
2291 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2292 // instead of the output device sample rate to avoid loss of high frequency information.
2293 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2294 }
2295
Andy Hung09a50072014-02-27 14:30:47 -08002296 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002297 double multiplier = 1.0;
2298 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2299 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002300 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2301 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Eric Laurent81784c32012-11-19 14:55:58 -08002302 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2303 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2304 maxNormalFrameCount = maxNormalFrameCount & ~15;
2305 if (maxNormalFrameCount < minNormalFrameCount) {
2306 maxNormalFrameCount = minNormalFrameCount;
2307 }
2308 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2309 if (multiplier <= 1.0) {
2310 multiplier = 1.0;
2311 } else if (multiplier <= 2.0) {
2312 if (2 * mFrameCount <= maxNormalFrameCount) {
2313 multiplier = 2.0;
2314 } else {
2315 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2316 }
2317 } else {
2318 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
Andy Hung09a50072014-02-27 14:30:47 -08002319 // 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 -08002320 // track, but we sometimes have to do this to satisfy the maximum frame count
2321 // constraint)
2322 // FIXME this rounding up should not be done if no HAL SRC
2323 uint32_t truncMult = (uint32_t) multiplier;
2324 if ((truncMult & 1)) {
2325 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2326 ++truncMult;
2327 }
2328 }
2329 multiplier = (double) truncMult;
2330 }
2331 }
2332 mNormalFrameCount = multiplier * mFrameCount;
2333 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002334 if (mType == MIXER || mType == DUPLICATING) {
2335 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2336 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002337 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002338 mNormalFrameCount);
2339
Andy Hung08fb1742015-05-31 23:22:10 -07002340 // Check if we want to throttle the processing to no more than 2x normal rate
2341 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002342 mThreadThrottleTimeMs = 0;
2343 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002344 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2345
Andy Hung010a1a12014-03-13 13:57:33 -07002346 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2347 // Originally this was int16_t[] array, need to remove legacy implications.
2348 free(mSinkBuffer);
2349 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002350 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2351 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2352 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002353 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002354
Andy Hung69aed5f2014-02-25 17:24:40 -08002355 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2356 // drives the output.
2357 free(mMixerBuffer);
2358 mMixerBuffer = NULL;
2359 if (mMixerBufferEnabled) {
2360 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2361 mMixerBufferSize = mNormalFrameCount * mChannelCount
2362 * audio_bytes_per_sample(mMixerBufferFormat);
2363 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2364 }
Andy Hung98ef9782014-03-04 14:46:50 -08002365 free(mEffectBuffer);
2366 mEffectBuffer = NULL;
2367 if (mEffectBufferEnabled) {
2368 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2369 mEffectBufferSize = mNormalFrameCount * mChannelCount
2370 * audio_bytes_per_sample(mEffectBufferFormat);
2371 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2372 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002373
Eric Laurent81784c32012-11-19 14:55:58 -08002374 // force reconfiguration of effect chains and engines to take new buffer size and audio
2375 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002376 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002377 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2378 // matter.
2379 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2380 Vector< sp<EffectChain> > effectChains = mEffectChains;
2381 for (size_t i = 0; i < effectChains.size(); i ++) {
2382 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2383 }
2384}
2385
2386
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002387status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002388{
2389 if (halFrames == NULL || dspFrames == NULL) {
2390 return BAD_VALUE;
2391 }
2392 Mutex::Autolock _l(mLock);
2393 if (initCheck() != NO_ERROR) {
2394 return INVALID_OPERATION;
2395 }
Andy Hung818e7a32016-02-16 18:08:07 -08002396 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002397 *halFrames = framesWritten;
2398
2399 if (isSuspended()) {
2400 // return an estimation of rendered frames when the output is suspended
2401 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002402 *dspFrames = (uint32_t)
2403 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002404 return NO_ERROR;
2405 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002406 status_t status;
2407 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002408 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002409 *dspFrames = (size_t)frames;
2410 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002411 }
2412}
2413
Glenn Kastend848eb42016-03-08 13:42:11 -08002414uint32_t AudioFlinger::PlaybackThread::hasAudioSession(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08002415{
2416 Mutex::Autolock _l(mLock);
2417 uint32_t result = 0;
2418 if (getEffectChain_l(sessionId) != 0) {
2419 result = EFFECT_SESSION;
2420 }
2421
2422 for (size_t i = 0; i < mTracks.size(); ++i) {
2423 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002424 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002425 result |= TRACK_SESSION;
2426 break;
2427 }
2428 }
2429
2430 return result;
2431}
2432
Glenn Kastend848eb42016-03-08 13:42:11 -08002433uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08002434{
2435 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2436 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2437 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2438 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2439 }
2440 for (size_t i = 0; i < mTracks.size(); i++) {
2441 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002442 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002443 return AudioSystem::getStrategyForStream(track->streamType());
2444 }
2445 }
2446 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2447}
2448
2449
Phil Burk062e67a2015-02-11 13:40:50 -08002450AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002451{
2452 Mutex::Autolock _l(mLock);
2453 return mOutput;
2454}
2455
Phil Burk062e67a2015-02-11 13:40:50 -08002456AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002457{
2458 Mutex::Autolock _l(mLock);
2459 AudioStreamOut *output = mOutput;
2460 mOutput = NULL;
2461 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2462 // must push a NULL and wait for ack
2463 mOutputSink.clear();
2464 mPipeSink.clear();
2465 mNormalSink.clear();
2466 return output;
2467}
2468
2469// this method must always be called either with ThreadBase mLock held or inside the thread loop
2470audio_stream_t* AudioFlinger::PlaybackThread::stream() const
2471{
2472 if (mOutput == NULL) {
2473 return NULL;
2474 }
2475 return &mOutput->stream->common;
2476}
2477
2478uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2479{
2480 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2481}
2482
2483status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2484{
2485 if (!isValidSyncEvent(event)) {
2486 return BAD_VALUE;
2487 }
2488
2489 Mutex::Autolock _l(mLock);
2490
2491 for (size_t i = 0; i < mTracks.size(); ++i) {
2492 sp<Track> track = mTracks[i];
2493 if (event->triggerSession() == track->sessionId()) {
2494 (void) track->setSyncEvent(event);
2495 return NO_ERROR;
2496 }
2497 }
2498
2499 return NAME_NOT_FOUND;
2500}
2501
2502bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2503{
2504 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2505}
2506
2507void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2508 const Vector< sp<Track> >& tracksToRemove)
2509{
2510 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002511 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002512 for (size_t i = 0 ; i < count ; i++) {
2513 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002514 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002515 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002516 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002517#ifdef ADD_BATTERY_DATA
2518 // to track the speaker usage
2519 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2520#endif
2521 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002522 AudioSystem::releaseOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002523 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002524 }
Eric Laurent81784c32012-11-19 14:55:58 -08002525 }
2526 }
2527 }
Eric Laurent81784c32012-11-19 14:55:58 -08002528}
2529
2530void AudioFlinger::PlaybackThread::checkSilentMode_l()
2531{
2532 if (!mMasterMute) {
2533 char value[PROPERTY_VALUE_MAX];
2534 if (property_get("ro.audio.silent", value, "0") > 0) {
2535 char *endptr;
2536 unsigned long ul = strtoul(value, &endptr, 0);
2537 if (*endptr == '\0' && ul != 0) {
2538 ALOGD("Silence is golden");
2539 // The setprop command will not allow a property to be changed after
2540 // the first time it is set, so we don't have to worry about un-muting.
2541 setMasterMute_l(true);
2542 }
2543 }
2544 }
2545}
2546
2547// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002548ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002549{
2550 // FIXME rewrite to reduce number of system calls
2551 mLastWriteTime = systemTime();
2552 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002553 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002554 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002555
2556 // If an NBAIO sink is present, use it to write the normal mixer's submix
2557 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002558
Andy Hung010a1a12014-03-13 13:57:33 -07002559 const size_t count = mBytesRemaining / mFrameSize;
2560
Simon Wilson2d590962012-11-29 15:18:50 -08002561 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002562 // update the setpoint when AudioFlinger::mScreenState changes
2563 uint32_t screenState = AudioFlinger::mScreenState;
2564 if (screenState != mScreenState) {
2565 mScreenState = screenState;
2566 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2567 if (pipe != NULL) {
2568 pipe->setAvgFrames((mScreenState & 1) ?
2569 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2570 }
2571 }
Andy Hung010a1a12014-03-13 13:57:33 -07002572 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002573 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002574 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002575 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002576 } else {
2577 bytesWritten = framesWritten;
2578 }
2579 // otherwise use the HAL / AudioStreamOut directly
2580 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002581 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002582
Eric Laurentbfb1b832013-01-07 09:53:42 -08002583 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002584 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2585 mWriteAckSequence += 2;
2586 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002587 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002588 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002589 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002590 // FIXME We should have an implementation of timestamps for direct output threads.
2591 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002592 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurent51716182016-02-29 18:00:56 -08002593
Eric Laurentbfb1b832013-01-07 09:53:42 -08002594 if (mUseAsyncWrite &&
2595 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2596 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002597 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002598 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002599 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002600 }
Eric Laurent81784c32012-11-19 14:55:58 -08002601 }
2602
Eric Laurent81784c32012-11-19 14:55:58 -08002603 mNumWrites++;
2604 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002605 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002606 return bytesWritten;
2607}
2608
2609void AudioFlinger::PlaybackThread::threadLoop_drain()
2610{
2611 if (mOutput->stream->drain) {
2612 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2613 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002614 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2615 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002616 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002617 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002618 }
2619 mOutput->stream->drain(mOutput->stream,
2620 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2621 : AUDIO_DRAIN_ALL);
2622 }
2623}
2624
2625void AudioFlinger::PlaybackThread::threadLoop_exit()
2626{
Eric Laurent275e8e92014-11-30 15:14:47 -08002627 {
2628 Mutex::Autolock _l(mLock);
2629 for (size_t i = 0; i < mTracks.size(); i++) {
2630 sp<Track> track = mTracks[i];
2631 track->invalidate();
2632 }
2633 }
Eric Laurent81784c32012-11-19 14:55:58 -08002634}
2635
2636/*
2637The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002638 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002639 - mActiveSleepTimeUs from activeSleepTimeUs()
2640 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08002641 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
2642 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08002643 - maxPeriod from frame count and sample rate (MIXER only)
2644
2645The parameters that affect these derived values are:
2646 - frame count
2647 - frame size
2648 - sample rate
2649 - device type: A2DP or not
2650 - device latency
2651 - format: PCM or not
2652 - active sleep time
2653 - idle sleep time
2654*/
2655
2656void AudioFlinger::PlaybackThread::cacheParameters_l()
2657{
Andy Hung25c2dac2014-02-27 14:56:00 -08002658 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002659 mActiveSleepTimeUs = activeSleepTimeUs();
2660 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08002661
2662 // make sure standby delay is not too short when connected to an A2DP sink to avoid
2663 // truncating audio when going to standby.
2664 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
2665 if ((mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != 0) {
2666 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
2667 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
2668 }
2669 }
Eric Laurent81784c32012-11-19 14:55:58 -08002670}
2671
2672void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2673{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002674 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08002675 this, streamType, mTracks.size());
2676 Mutex::Autolock _l(mLock);
2677
2678 size_t size = mTracks.size();
2679 for (size_t i = 0; i < size; i++) {
2680 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07002681 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002682 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08002683 }
2684 }
2685}
2686
2687status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2688{
Glenn Kastend848eb42016-03-08 13:42:11 -08002689 audio_session_t session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002690 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2691 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002692 bool ownsBuffer = false;
2693
2694 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Glenn Kastend848eb42016-03-08 13:42:11 -08002695 if (session > AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002696 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002697 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002698 if (mType != DIRECT) {
2699 size_t numSamples = mNormalFrameCount * mChannelCount;
2700 buffer = new int16_t[numSamples];
2701 memset(buffer, 0, numSamples * sizeof(int16_t));
2702 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2703 ownsBuffer = true;
2704 }
2705
2706 // Attach all tracks with same session ID to this chain.
2707 for (size_t i = 0; i < mTracks.size(); ++i) {
2708 sp<Track> track = mTracks[i];
2709 if (session == track->sessionId()) {
2710 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2711 buffer);
2712 track->setMainBuffer(buffer);
2713 chain->incTrackCnt();
2714 }
2715 }
2716
2717 // indicate all active tracks in the chain
2718 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2719 sp<Track> track = mActiveTracks[i].promote();
2720 if (track == 0) {
2721 continue;
2722 }
2723 if (session == track->sessionId()) {
2724 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2725 chain->incActiveTrackCnt();
2726 }
2727 }
2728 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002729 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08002730 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002731 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2732 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002733 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Glenn Kastend848eb42016-03-08 13:42:11 -08002734 // chains list in order to be processed last as it contains output stage effects.
Eric Laurent81784c32012-11-19 14:55:58 -08002735 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2736 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08002737 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08002738 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08002739 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08002740 // Effect chain for other sessions are inserted at beginning of effect
2741 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08002742 // sessions is not important.
2743 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
2744 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX,
2745 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08002746 size_t size = mEffectChains.size();
2747 size_t i = 0;
2748 for (i = 0; i < size; i++) {
2749 if (mEffectChains[i]->sessionId() < session) {
2750 break;
2751 }
2752 }
2753 mEffectChains.insertAt(chain, i);
2754 checkSuspendOnAddEffectChain_l(chain);
2755
2756 return NO_ERROR;
2757}
2758
2759size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2760{
Glenn Kastend848eb42016-03-08 13:42:11 -08002761 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08002762
2763 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2764
2765 for (size_t i = 0; i < mEffectChains.size(); i++) {
2766 if (chain == mEffectChains[i]) {
2767 mEffectChains.removeAt(i);
2768 // detach all active tracks from the chain
2769 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2770 sp<Track> track = mActiveTracks[i].promote();
2771 if (track == 0) {
2772 continue;
2773 }
2774 if (session == track->sessionId()) {
2775 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2776 chain.get(), session);
2777 chain->decActiveTrackCnt();
2778 }
2779 }
2780
2781 // detach all tracks with same session ID from this chain
2782 for (size_t i = 0; i < mTracks.size(); ++i) {
2783 sp<Track> track = mTracks[i];
2784 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002785 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002786 chain->decTrackCnt();
2787 }
2788 }
2789 break;
2790 }
2791 }
2792 return mEffectChains.size();
2793}
2794
2795status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2796 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2797{
2798 Mutex::Autolock _l(mLock);
2799 return attachAuxEffect_l(track, EffectId);
2800}
2801
2802status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2803 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2804{
2805 status_t status = NO_ERROR;
2806
2807 if (EffectId == 0) {
2808 track->setAuxBuffer(0, NULL);
2809 } else {
2810 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2811 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2812 if (effect != 0) {
2813 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2814 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2815 } else {
2816 status = INVALID_OPERATION;
2817 }
2818 } else {
2819 status = BAD_VALUE;
2820 }
2821 }
2822 return status;
2823}
2824
2825void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2826{
2827 for (size_t i = 0; i < mTracks.size(); ++i) {
2828 sp<Track> track = mTracks[i];
2829 if (track->auxEffectId() == effectId) {
2830 attachAuxEffect_l(track, 0);
2831 }
2832 }
2833}
2834
2835bool AudioFlinger::PlaybackThread::threadLoop()
2836{
2837 Vector< sp<Track> > tracksToRemove;
2838
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002839 mStandbyTimeNs = systemTime();
Eric Laurent81784c32012-11-19 14:55:58 -08002840
2841 // MIXER
2842 nsecs_t lastWarning = 0;
2843
2844 // DUPLICATING
2845 // FIXME could this be made local to while loop?
2846 writeFrames = 0;
2847
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002848 int lastGeneration = 0;
2849
Eric Laurent81784c32012-11-19 14:55:58 -08002850 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002851 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002852
2853 if (mType == MIXER) {
2854 sleepTimeShift = 0;
2855 }
2856
2857 CpuStats cpuStats;
2858 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2859
2860 acquireWakeLock();
2861
Glenn Kasten9e58b552013-01-18 15:09:48 -08002862 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2863 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2864 // and then that string will be logged at the next convenient opportunity.
2865 const char *logString = NULL;
2866
Eric Laurent664539d2013-09-23 18:24:31 -07002867 checkSilentMode_l();
2868
Eric Laurent81784c32012-11-19 14:55:58 -08002869 while (!exitPending())
2870 {
2871 cpuStats.sample(myName);
2872
2873 Vector< sp<EffectChain> > effectChains;
2874
Eric Laurent81784c32012-11-19 14:55:58 -08002875 { // scope for mLock
2876
2877 Mutex::Autolock _l(mLock);
2878
Eric Laurent021cf962014-05-13 10:18:14 -07002879 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002880
Glenn Kasten9e58b552013-01-18 15:09:48 -08002881 if (logString != NULL) {
2882 mNBLogWriter->logTimestamp();
2883 mNBLogWriter->log(logString);
2884 logString = NULL;
2885 }
2886
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002887 // Gather the framesReleased counters for all active tracks,
Andy Hunge10393e2015-06-12 13:59:33 -07002888 // and associate with the sink frames written out. We need
2889 // this to convert the sink timestamp to the track timestamp.
2890 if (mNormalSink != 0) {
Andy Hungc54b1ff2016-02-23 14:07:07 -08002891 // Note: The DuplicatingThread may not have a mNormalSink.
Andy Hung818e7a32016-02-16 18:08:07 -08002892 // We always fetch the timestamp here because often the downstream
2893 // sink will block whie writing.
2894 ExtendedTimestamp timestamp; // use private copy to fetch
2895 (void) mNormalSink->getTimestamp(timestamp);
2896 // copy over kernel info
2897 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
2898 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
2899 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
2900 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hungc54b1ff2016-02-23 14:07:07 -08002901 }
2902 // mFramesWritten for non-offloaded tracks are contiguous
2903 // even after standby() is called. This is useful for the track frame
2904 // to sink frame mapping.
2905 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
2906 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
2907 const size_t size = mActiveTracks.size();
2908 for (size_t i = 0; i < size; ++i) {
2909 sp<Track> t = mActiveTracks[i].promote();
2910 if (t != 0 && !t->isFastTrack()) {
2911 t->updateTrackFrameInfo(
2912 t->mAudioTrackServerProxy->framesReleased(),
2913 mFramesWritten,
2914 mTimestamp);
Andy Hunge10393e2015-06-12 13:59:33 -07002915 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002916 }
2917
Eric Laurent81784c32012-11-19 14:55:58 -08002918 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002919 if (mSignalPending) {
2920 // A signal was raised while we were unlocked
2921 mSignalPending = false;
2922 } else if (waitingAsyncCallback_l()) {
2923 if (exitPending()) {
2924 break;
2925 }
Marco Nelissen078538c2015-05-12 09:17:57 -07002926 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07002927 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07002928 releaseWakeLock_l();
2929 released = true;
2930 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002931 mWakeLockUids.clear();
2932 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002933 ALOGV("wait async completion");
2934 mWaitWorkCV.wait(mLock);
2935 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07002936 if (released) {
2937 acquireWakeLock_l();
2938 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002939 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
2940 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002941
2942 continue;
2943 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002944 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002945 isSuspended()) {
2946 // put audio hardware into standby after short delay
2947 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002948
2949 threadLoop_standby();
2950
2951 mStandby = true;
2952 }
2953
2954 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2955 // we're about to wait, flush the binder command buffer
2956 IPCThreadState::self()->flushCommands();
2957
2958 clearOutputTracks();
2959
2960 if (exitPending()) {
2961 break;
2962 }
2963
2964 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002965 mWakeLockUids.clear();
2966 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002967 // wait until we have something to do...
2968 ALOGV("%s going to sleep", myName.string());
2969 mWaitWorkCV.wait(mLock);
2970 ALOGV("%s waking up", myName.string());
2971 acquireWakeLock_l();
2972
2973 mMixerStatus = MIXER_IDLE;
2974 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2975 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002976 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002977 checkSilentMode_l();
2978
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002979 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
2980 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002981 if (mType == MIXER) {
2982 sleepTimeShift = 0;
2983 }
2984
2985 continue;
2986 }
2987 }
Eric Laurent81784c32012-11-19 14:55:58 -08002988 // mMixerStatusIgnoringFastTracks is also updated internally
2989 mMixerStatus = prepareTracks_l(&tracksToRemove);
2990
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002991 // compare with previously applied list
2992 if (lastGeneration != mActiveTracksGeneration) {
2993 // update wakelock
2994 updateWakeLockUids_l(mWakeLockUids);
2995 lastGeneration = mActiveTracksGeneration;
2996 }
2997
Eric Laurent81784c32012-11-19 14:55:58 -08002998 // prevent any changes in effect chain list and in each effect chain
2999 // during mixing and effect process as the audio buffers could be deleted
3000 // or modified if an effect is created or deleted
3001 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003002 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003003
Eric Laurentbfb1b832013-01-07 09:53:42 -08003004 if (mBytesRemaining == 0) {
3005 mCurrentWriteLength = 0;
3006 if (mMixerStatus == MIXER_TRACKS_READY) {
3007 // threadLoop_mix() sets mCurrentWriteLength
3008 threadLoop_mix();
3009 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3010 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003011 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003012 // must be written to HAL
3013 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003014 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003015 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003016 }
3017 }
Andy Hung98ef9782014-03-04 14:46:50 -08003018 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003019 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003020 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3021 // or mSinkBuffer (if there are no effects).
3022 //
3023 // This is done pre-effects computation; if effects change to
3024 // support higher precision, this needs to move.
3025 //
3026 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003027 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003028 if (mMixerBufferValid) {
3029 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3030 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3031
Andy Hung2ddee192015-12-18 17:34:44 -08003032 // mono blend occurs for mixer threads only (not direct or offloaded)
3033 // and is handled here if we're going directly to the sink.
3034 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003035 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3036 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003037 }
3038
Andy Hung98ef9782014-03-04 14:46:50 -08003039 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
3040 mNormalFrameCount * mChannelCount);
3041 }
3042
Eric Laurentbfb1b832013-01-07 09:53:42 -08003043 mBytesRemaining = mCurrentWriteLength;
3044 if (isSuspended()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003045 mSleepTimeUs = suspendSleepTimeUs();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003046 // simulate write to HAL when suspended
Andy Hung25c2dac2014-02-27 14:56:00 -08003047 mBytesWritten += mSinkBufferSize;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003048 mFramesWritten += mSinkBufferSize / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003049 mBytesRemaining = 0;
3050 }
Eric Laurent81784c32012-11-19 14:55:58 -08003051
Eric Laurentbfb1b832013-01-07 09:53:42 -08003052 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003053 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003054 for (size_t i = 0; i < effectChains.size(); i ++) {
3055 effectChains[i]->process_l();
3056 }
Eric Laurent81784c32012-11-19 14:55:58 -08003057 }
3058 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003059 // Process effect chains for offloaded thread even if no audio
3060 // was read from audio track: process only updates effect state
3061 // and thus does have to be synchronized with audio writes but may have
3062 // to be called while waiting for async write callback
3063 if (mType == OFFLOAD) {
3064 for (size_t i = 0; i < effectChains.size(); i ++) {
3065 effectChains[i]->process_l();
3066 }
3067 }
Eric Laurent81784c32012-11-19 14:55:58 -08003068
Andy Hung98ef9782014-03-04 14:46:50 -08003069 // Only if the Effects buffer is enabled and there is data in the
3070 // Effects buffer (buffer valid), we need to
3071 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003072 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003073 if (mEffectBufferValid) {
3074 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003075
3076 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003077 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3078 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003079 }
3080
Andy Hung98ef9782014-03-04 14:46:50 -08003081 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
3082 mNormalFrameCount * mChannelCount);
3083 }
3084
Eric Laurent81784c32012-11-19 14:55:58 -08003085 // enable changes in effect chain
3086 unlockEffectChains(effectChains);
3087
Eric Laurentbfb1b832013-01-07 09:53:42 -08003088 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003089 // mSleepTimeUs == 0 means we must write to audio hardware
3090 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003091 ssize_t ret = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003092 if (mBytesRemaining) {
Andy Hung08fb1742015-05-31 23:22:10 -07003093 ret = threadLoop_write();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003094 if (ret < 0) {
3095 mBytesRemaining = 0;
3096 } else {
3097 mBytesWritten += ret;
3098 mBytesRemaining -= ret;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003099 mFramesWritten += ret / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003100 }
3101 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3102 (mMixerStatus == MIXER_DRAIN_ALL)) {
3103 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003104 }
Andy Hung08fb1742015-05-31 23:22:10 -07003105 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003106 // write blocked detection
3107 nsecs_t now = systemTime();
3108 nsecs_t delta = now - mLastWriteTime;
Andy Hung08fb1742015-05-31 23:22:10 -07003109 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003110 mNumDelayedWrites++;
3111 if ((now - lastWarning) > kWarningThrottleNs) {
3112 ATRACE_NAME("underrun");
3113 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003114 (unsigned long long) ns2ms(delta), mNumDelayedWrites, this);
Glenn Kasten4944acb2013-08-19 08:39:20 -07003115 lastWarning = now;
3116 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003117 }
Andy Hung08fb1742015-05-31 23:22:10 -07003118
3119 if (mThreadThrottle
3120 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
3121 && ret > 0) { // we wrote something
3122 // Limit MixerThread data processing to no more than twice the
3123 // expected processing rate.
3124 //
3125 // This helps prevent underruns with NuPlayer and other applications
3126 // which may set up buffers that are close to the minimum size, or use
3127 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3128 //
3129 // The throttle smooths out sudden large data drains from the device,
3130 // e.g. when it comes out of standby, which often causes problems with
3131 // (1) mixer threads without a fast mixer (which has its own warm-up)
3132 // (2) minimum buffer sized tracks (even if the track is full,
3133 // the app won't fill fast enough to handle the sudden draw).
3134
3135 const int32_t deltaMs = delta / 1000000;
3136 const int32_t throttleMs = mHalfBufferMs - deltaMs;
3137 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3138 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003139 // notify of throttle start on verbose log
3140 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3141 "mixer(%p) throttle begin:"
3142 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003143 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003144 mThreadThrottleTimeMs += throttleMs;
3145 } else {
3146 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3147 if (diff > 0) {
3148 // notify of throttle end on debug log
3149 ALOGD("mixer(%p) throttle end: throttle time(%u)", this, diff);
3150 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3151 }
Andy Hung08fb1742015-05-31 23:22:10 -07003152 }
3153 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003154 }
Eric Laurent81784c32012-11-19 14:55:58 -08003155
Eric Laurentbfb1b832013-01-07 09:53:42 -08003156 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003157 ATRACE_BEGIN("sleep");
Eric Laurent51716182016-02-29 18:00:56 -08003158 if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
3159 Mutex::Autolock _l(mLock);
3160 if (!mSignalPending && !exitPending()) {
3161 // Do not sleep more than one buffer duration since last write and not
3162 // less than kDirectMinSleepTimeUs
3163 // Wake up if a command is received
3164 nsecs_t now = systemTime();
3165 uint32_t deltaUs = (uint32_t)((now - mLastWriteTime) / 1000);
3166 uint32_t timeoutUs = mSleepTimeUs;
3167 if (timeoutUs + deltaUs > mBufferDurationUs) {
3168 if (mBufferDurationUs > deltaUs) {
3169 timeoutUs = mBufferDurationUs - deltaUs;
3170 if (timeoutUs < kDirectMinSleepTimeUs) {
3171 timeoutUs = kDirectMinSleepTimeUs;
3172 }
3173 } else {
3174 timeoutUs = kDirectMinSleepTimeUs;
3175 }
3176 }
3177 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)timeoutUs));
3178 }
3179 } else {
3180 usleep(mSleepTimeUs);
3181 }
Glenn Kastene7754022014-10-31 12:11:26 -07003182 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003183 }
Eric Laurent81784c32012-11-19 14:55:58 -08003184 }
3185
3186 // Finally let go of removed track(s), without the lock held
3187 // since we can't guarantee the destructors won't acquire that
3188 // same lock. This will also mutate and push a new fast mixer state.
3189 threadLoop_removeTracks(tracksToRemove);
3190 tracksToRemove.clear();
3191
3192 // FIXME I don't understand the need for this here;
3193 // it was in the original code but maybe the
3194 // assignment in saveOutputTracks() makes this unnecessary?
3195 clearOutputTracks();
3196
3197 // Effect chains will be actually deleted here if they were removed from
3198 // mEffectChains list during mixing or effects processing
3199 effectChains.clear();
3200
3201 // FIXME Note that the above .clear() is no longer necessary since effectChains
3202 // is now local to this block, but will keep it for now (at least until merge done).
3203 }
3204
Eric Laurentbfb1b832013-01-07 09:53:42 -08003205 threadLoop_exit();
3206
Eric Laurentcf817a22014-08-04 20:36:31 -07003207 if (!mStandby) {
3208 threadLoop_standby();
3209 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003210 }
3211
3212 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003213 mWakeLockUids.clear();
3214 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08003215
3216 ALOGV("Thread %p type %d exiting", this, mType);
3217 return false;
3218}
3219
Eric Laurentbfb1b832013-01-07 09:53:42 -08003220// removeTracks_l() must be called with ThreadBase::mLock held
3221void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3222{
3223 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003224 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003225 for (size_t i=0 ; i<count ; i++) {
3226 const sp<Track>& track = tracksToRemove.itemAt(i);
3227 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003228 mWakeLockUids.remove(track->uid());
3229 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003230 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3231 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3232 if (chain != 0) {
3233 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3234 track->sessionId());
3235 chain->decActiveTrackCnt();
3236 }
3237 if (track->isTerminated()) {
3238 removeTrack_l(track);
3239 }
3240 }
3241 }
3242
3243}
Eric Laurent81784c32012-11-19 14:55:58 -08003244
Eric Laurentaccc1472013-09-20 09:36:34 -07003245status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3246{
3247 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08003248 ExtendedTimestamp ets;
3249 status_t status = mNormalSink->getTimestamp(ets);
3250 if (status == NO_ERROR) {
3251 status = ets.getBestTimestamp(&timestamp);
3252 }
3253 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07003254 }
Andy Hung9a1c8892014-12-03 11:37:42 -08003255 if ((mType == OFFLOAD || mType == DIRECT)
3256 && mOutput != NULL && mOutput->stream->get_presentation_position) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003257 uint64_t position64;
Phil Burk062e67a2015-02-11 13:40:50 -08003258 int ret = mOutput->getPresentationPosition(&position64, &timestamp.mTime);
Eric Laurentaccc1472013-09-20 09:36:34 -07003259 if (ret == 0) {
3260 timestamp.mPosition = (uint32_t)position64;
3261 return NO_ERROR;
3262 }
3263 }
3264 return INVALID_OPERATION;
3265}
Eric Laurent1c333e22014-05-20 10:48:17 -07003266
Eric Laurent054d9d32015-04-24 08:48:48 -07003267status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3268 audio_patch_handle_t *handle)
3269{
Glenn Kastenc05b8d72016-03-24 09:48:17 -07003270 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent054d9d32015-04-24 08:48:48 -07003271
Glenn Kastenc05b8d72016-03-24 09:48:17 -07003272 status_t status = PlaybackThread::createAudioPatch_l(patch, handle);
Eric Laurent054d9d32015-04-24 08:48:48 -07003273
3274 return status;
3275}
3276
Eric Laurent1c333e22014-05-20 10:48:17 -07003277status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3278 audio_patch_handle_t *handle)
3279{
3280 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003281
3282 // store new device and send to effects
3283 audio_devices_t type = AUDIO_DEVICE_NONE;
3284 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3285 type |= patch->sinks[i].ext.device.type;
3286 }
3287
3288#ifdef ADD_BATTERY_DATA
3289 // when changing the audio output device, call addBatteryData to notify
3290 // the change
3291 if (mOutDevice != type) {
3292 uint32_t params = 0;
3293 // check whether speaker is on
3294 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3295 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003296 }
3297
Eric Laurent054d9d32015-04-24 08:48:48 -07003298 audio_devices_t deviceWithoutSpeaker
3299 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3300 // check if any other device (except speaker) is on
3301 if (type & deviceWithoutSpeaker) {
3302 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3303 }
3304
3305 if (params != 0) {
3306 addBatteryData(params);
3307 }
3308 }
3309#endif
3310
3311 for (size_t i = 0; i < mEffectChains.size(); i++) {
3312 mEffectChains[i]->setDevice_l(type);
3313 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003314
3315 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3316 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3317 bool configChanged = mPrevOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003318 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003319 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003320
3321 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003322 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3323 status = hwDevice->create_audio_patch(hwDevice,
3324 patch->num_sources,
3325 patch->sources,
3326 patch->num_sinks,
3327 patch->sinks,
3328 handle);
3329 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003330 char *address;
3331 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3332 //FIXME: we only support address on first sink with HAL version < 3.0
3333 address = audio_device_address_to_parameter(
3334 patch->sinks[0].ext.device.type,
3335 patch->sinks[0].ext.device.address);
3336 } else {
3337 address = (char *)calloc(1, 1);
3338 }
3339 AudioParameter param = AudioParameter(String8(address));
3340 free(address);
3341 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), (int)type);
3342 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3343 param.toString().string());
3344 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003345 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003346 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003347 mPrevOutDevice = type;
Eric Laurente8726fe2015-06-26 09:39:24 -07003348 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3349 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003350 return status;
3351}
3352
Eric Laurent054d9d32015-04-24 08:48:48 -07003353status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3354{
Glenn Kastenc05b8d72016-03-24 09:48:17 -07003355 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent054d9d32015-04-24 08:48:48 -07003356
3357 status_t status = PlaybackThread::releaseAudioPatch_l(handle);
3358
Eric Laurent054d9d32015-04-24 08:48:48 -07003359 return status;
3360}
3361
Eric Laurent1c333e22014-05-20 10:48:17 -07003362status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3363{
3364 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003365
3366 mOutDevice = AUDIO_DEVICE_NONE;
3367
Eric Laurent1c333e22014-05-20 10:48:17 -07003368 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
3369 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3370 status = hwDevice->release_audio_patch(hwDevice, handle);
3371 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003372 AudioParameter param;
3373 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
3374 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3375 param.toString().string());
Eric Laurent1c333e22014-05-20 10:48:17 -07003376 }
3377 return status;
3378}
3379
Eric Laurent83b88082014-06-20 18:31:16 -07003380void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3381{
3382 Mutex::Autolock _l(mLock);
3383 mTracks.add(track);
3384}
3385
3386void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3387{
3388 Mutex::Autolock _l(mLock);
3389 destroyTrack_l(track);
3390}
3391
3392void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3393{
3394 ThreadBase::getAudioPortConfig(config);
3395 config->role = AUDIO_PORT_ROLE_SOURCE;
3396 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3397 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3398}
3399
Eric Laurent81784c32012-11-19 14:55:58 -08003400// ----------------------------------------------------------------------------
3401
3402AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003403 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3404 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003405 // mAudioMixer below
3406 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08003407 mFastMixerFutex(0),
3408 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08003409 // mOutputSink below
3410 // mPipeSink below
3411 // mNormalSink below
3412{
3413 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003414 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%zu, "
3415 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003416 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3417 mNormalFrameCount);
3418 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3419
Andy Hungfbfc3952015-01-15 13:33:51 -08003420 if (type == DUPLICATING) {
3421 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3422 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3423 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3424 return;
3425 }
Eric Laurent81784c32012-11-19 14:55:58 -08003426 // create an NBAIO sink for the HAL output stream, and negotiate
3427 mOutputSink = new AudioStreamOutSink(output->stream);
3428 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003429 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003430#if !LOG_NDEBUG
3431 ssize_t index =
3432#else
3433 (void)
3434#endif
3435 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003436 ALOG_ASSERT(index == 0);
3437
3438 // initialize fast mixer depending on configuration
3439 bool initFastMixer;
3440 switch (kUseFastMixer) {
3441 case FastMixer_Never:
3442 initFastMixer = false;
3443 break;
3444 case FastMixer_Always:
3445 initFastMixer = true;
3446 break;
3447 case FastMixer_Static:
3448 case FastMixer_Dynamic:
3449 initFastMixer = mFrameCount < mNormalFrameCount;
3450 break;
3451 }
3452 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003453 audio_format_t fastMixerFormat;
3454 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3455 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3456 } else {
3457 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3458 }
3459 if (mFormat != fastMixerFormat) {
3460 // change our Sink format to accept our intermediate precision
3461 mFormat = fastMixerFormat;
3462 free(mSinkBuffer);
3463 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3464 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3465 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3466 }
Eric Laurent81784c32012-11-19 14:55:58 -08003467
3468 // create a MonoPipe to connect our submix to FastMixer
3469 NBAIO_Format format = mOutputSink->format();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003470#ifdef TEE_SINK
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003471 NBAIO_Format origformat = format;
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003472#endif
Andy Hung1258c1a2014-05-23 21:22:17 -07003473 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07003474 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003475 format.mFormat = fastMixerFormat;
3476 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3477
Eric Laurent81784c32012-11-19 14:55:58 -08003478 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3479 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3480 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3481 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3482 const NBAIO_Format offers[1] = {format};
3483 size_t numCounterOffers = 0;
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003484#if !LOG_NDEBUG
3485 ssize_t index =
3486#else
3487 (void)
3488#endif
3489 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003490 ALOG_ASSERT(index == 0);
3491 monoPipe->setAvgFrames((mScreenState & 1) ?
3492 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3493 mPipeSink = monoPipe;
3494
Glenn Kasten46909e72013-02-26 09:20:22 -08003495#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003496 if (mTeeSinkOutputEnabled) {
3497 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003498 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3499 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003500 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003501 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003502 ALOG_ASSERT(index == 0);
3503 mTeeSink = teeSink;
3504 PipeReader *teeSource = new PipeReader(*teeSink);
3505 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003506 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003507 ALOG_ASSERT(index == 0);
3508 mTeeSource = teeSource;
3509 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003510#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003511
3512 // create fast mixer and configure it initially with just one fast track for our submix
3513 mFastMixer = new FastMixer();
3514 FastMixerStateQueue *sq = mFastMixer->sq();
3515#ifdef STATE_QUEUE_DUMP
3516 sq->setObserverDump(&mStateQueueObserverDump);
3517 sq->setMutatorDump(&mStateQueueMutatorDump);
3518#endif
3519 FastMixerState *state = sq->begin();
3520 FastTrack *fastTrack = &state->mFastTracks[0];
3521 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3522 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3523 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003524 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3525 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003526 fastTrack->mGeneration++;
3527 state->mFastTracksGen++;
3528 state->mTrackMask = 1;
3529 // fast mixer will use the HAL output sink
3530 state->mOutputSink = mOutputSink.get();
3531 state->mOutputSinkGen++;
3532 state->mFrameCount = mFrameCount;
3533 state->mCommand = FastMixerState::COLD_IDLE;
3534 // already done in constructor initialization list
3535 //mFastMixerFutex = 0;
3536 state->mColdFutexAddr = &mFastMixerFutex;
3537 state->mColdGen++;
3538 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003539#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003540 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003541#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003542 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3543 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003544 sq->end();
3545 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3546
3547 // start the fast mixer
3548 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3549 pid_t tid = mFastMixer->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003550 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003551
3552#ifdef AUDIO_WATCHDOG
3553 // create and start the watchdog
3554 mAudioWatchdog = new AudioWatchdog();
3555 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3556 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3557 tid = mAudioWatchdog->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003558 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003559#endif
3560
Eric Laurent81784c32012-11-19 14:55:58 -08003561 }
3562
3563 switch (kUseFastMixer) {
3564 case FastMixer_Never:
3565 case FastMixer_Dynamic:
3566 mNormalSink = mOutputSink;
3567 break;
3568 case FastMixer_Always:
3569 mNormalSink = mPipeSink;
3570 break;
3571 case FastMixer_Static:
3572 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3573 break;
3574 }
3575}
3576
3577AudioFlinger::MixerThread::~MixerThread()
3578{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003579 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003580 FastMixerStateQueue *sq = mFastMixer->sq();
3581 FastMixerState *state = sq->begin();
3582 if (state->mCommand == FastMixerState::COLD_IDLE) {
3583 int32_t old = android_atomic_inc(&mFastMixerFutex);
3584 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003585 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003586 }
3587 }
3588 state->mCommand = FastMixerState::EXIT;
3589 sq->end();
3590 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3591 mFastMixer->join();
3592 // Though the fast mixer thread has exited, it's state queue is still valid.
3593 // We'll use that extract the final state which contains one remaining fast track
3594 // corresponding to our sub-mix.
3595 state = sq->begin();
3596 ALOG_ASSERT(state->mTrackMask == 1);
3597 FastTrack *fastTrack = &state->mFastTracks[0];
3598 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3599 delete fastTrack->mBufferProvider;
3600 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003601 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003602#ifdef AUDIO_WATCHDOG
3603 if (mAudioWatchdog != 0) {
3604 mAudioWatchdog->requestExit();
3605 mAudioWatchdog->requestExitAndWait();
3606 mAudioWatchdog.clear();
3607 }
3608#endif
3609 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003610 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003611 delete mAudioMixer;
3612}
3613
3614
3615uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3616{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003617 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003618 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3619 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3620 }
3621 return latency;
3622}
3623
3624
3625void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3626{
3627 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3628}
3629
Eric Laurentbfb1b832013-01-07 09:53:42 -08003630ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003631{
3632 // FIXME we should only do one push per cycle; confirm this is true
3633 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003634 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003635 FastMixerStateQueue *sq = mFastMixer->sq();
3636 FastMixerState *state = sq->begin();
3637 if (state->mCommand != FastMixerState::MIX_WRITE &&
3638 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3639 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07003640
3641 // FIXME workaround for first HAL write being CPU bound on some devices
3642 ATRACE_BEGIN("write");
3643 mOutput->write((char *)mSinkBuffer, 0);
3644 ATRACE_END();
3645
Eric Laurent81784c32012-11-19 14:55:58 -08003646 int32_t old = android_atomic_inc(&mFastMixerFutex);
3647 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003648 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003649 }
3650#ifdef AUDIO_WATCHDOG
3651 if (mAudioWatchdog != 0) {
3652 mAudioWatchdog->resume();
3653 }
3654#endif
3655 }
3656 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003657#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003658 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003659 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003660#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003661 sq->end();
3662 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3663 if (kUseFastMixer == FastMixer_Dynamic) {
3664 mNormalSink = mPipeSink;
3665 }
3666 } else {
3667 sq->end(false /*didModify*/);
3668 }
3669 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003670 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003671}
3672
3673void AudioFlinger::MixerThread::threadLoop_standby()
3674{
3675 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003676 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003677 FastMixerStateQueue *sq = mFastMixer->sq();
3678 FastMixerState *state = sq->begin();
3679 if (!(state->mCommand & FastMixerState::IDLE)) {
3680 state->mCommand = FastMixerState::COLD_IDLE;
3681 state->mColdFutexAddr = &mFastMixerFutex;
3682 state->mColdGen++;
3683 mFastMixerFutex = 0;
3684 sq->end();
3685 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3686 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3687 if (kUseFastMixer == FastMixer_Dynamic) {
3688 mNormalSink = mOutputSink;
3689 }
3690#ifdef AUDIO_WATCHDOG
3691 if (mAudioWatchdog != 0) {
3692 mAudioWatchdog->pause();
3693 }
3694#endif
3695 } else {
3696 sq->end(false /*didModify*/);
3697 }
3698 }
3699 PlaybackThread::threadLoop_standby();
3700}
3701
Eric Laurentbfb1b832013-01-07 09:53:42 -08003702bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3703{
3704 return false;
3705}
3706
3707bool AudioFlinger::PlaybackThread::shouldStandby_l()
3708{
3709 return !mStandby;
3710}
3711
3712bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3713{
3714 Mutex::Autolock _l(mLock);
3715 return waitingAsyncCallback_l();
3716}
3717
Eric Laurent81784c32012-11-19 14:55:58 -08003718// shared by MIXER and DIRECT, overridden by DUPLICATING
3719void AudioFlinger::PlaybackThread::threadLoop_standby()
3720{
3721 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08003722 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003723 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003724 // discard any pending drain or write ack by incrementing sequence
3725 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3726 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003727 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003728 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3729 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003730 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003731 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003732}
3733
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003734void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3735{
3736 ALOGV("signal playback thread");
3737 broadcast_l();
3738}
3739
Eric Laurent81784c32012-11-19 14:55:58 -08003740void AudioFlinger::MixerThread::threadLoop_mix()
3741{
Eric Laurent81784c32012-11-19 14:55:58 -08003742 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08003743 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08003744 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003745 // increase sleep time progressively when application underrun condition clears.
3746 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3747 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3748 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003749 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003750 sleepTimeShift--;
3751 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003752 mSleepTimeUs = 0;
3753 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08003754 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003755
Eric Laurent81784c32012-11-19 14:55:58 -08003756}
3757
3758void AudioFlinger::MixerThread::threadLoop_sleepTime()
3759{
3760 // If no tracks are ready, sleep once for the duration of an output
3761 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003762 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003763 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003764 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
3765 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
3766 mSleepTimeUs = kMinThreadSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003767 }
3768 // reduce sleep time in case of consecutive application underruns to avoid
3769 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3770 // duration we would end up writing less data than needed by the audio HAL if
3771 // the condition persists.
3772 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3773 sleepTimeShift++;
3774 }
3775 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003776 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003777 }
3778 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003779 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3780 // before effects processing or output.
3781 if (mMixerBufferValid) {
3782 memset(mMixerBuffer, 0, mMixerBufferSize);
3783 } else {
3784 memset(mSinkBuffer, 0, mSinkBufferSize);
3785 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003786 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003787 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3788 "anticipated start");
3789 }
3790 // TODO add standby time extension fct of effect tail
3791}
3792
3793// prepareTracks_l() must be called with ThreadBase::mLock held
3794AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3795 Vector< sp<Track> > *tracksToRemove)
3796{
3797
3798 mixer_state mixerStatus = MIXER_IDLE;
3799 // find out which tracks need to be processed
3800 size_t count = mActiveTracks.size();
3801 size_t mixedTracks = 0;
3802 size_t tracksWithEffect = 0;
3803 // counts only _active_ fast tracks
3804 size_t fastTracks = 0;
3805 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3806
3807 float masterVolume = mMasterVolume;
3808 bool masterMute = mMasterMute;
3809
3810 if (masterMute) {
3811 masterVolume = 0;
3812 }
3813 // Delegate master volume control to effect in output mix effect chain if needed
3814 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3815 if (chain != 0) {
3816 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3817 chain->setVolume_l(&v, &v);
3818 masterVolume = (float)((v + (1 << 23)) >> 24);
3819 chain.clear();
3820 }
3821
3822 // prepare a new state to push
3823 FastMixerStateQueue *sq = NULL;
3824 FastMixerState *state = NULL;
3825 bool didModify = false;
3826 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003827 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003828 sq = mFastMixer->sq();
3829 state = sq->begin();
3830 }
3831
Andy Hung69aed5f2014-02-25 17:24:40 -08003832 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003833 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003834
Eric Laurent81784c32012-11-19 14:55:58 -08003835 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003836 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003837 if (t == 0) {
3838 continue;
3839 }
3840
3841 // this const just means the local variable doesn't change
3842 Track* const track = t.get();
3843
3844 // process fast tracks
3845 if (track->isFastTrack()) {
3846
3847 // It's theoretically possible (though unlikely) for a fast track to be created
3848 // and then removed within the same normal mix cycle. This is not a problem, as
3849 // the track never becomes active so it's fast mixer slot is never touched.
3850 // The converse, of removing an (active) track and then creating a new track
3851 // at the identical fast mixer slot within the same normal mix cycle,
3852 // is impossible because the slot isn't marked available until the end of each cycle.
3853 int j = track->mFastIndex;
3854 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
3855 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3856 FastTrack *fastTrack = &state->mFastTracks[j];
3857
3858 // Determine whether the track is currently in underrun condition,
3859 // and whether it had a recent underrun.
3860 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3861 FastTrackUnderruns underruns = ftDump->mUnderruns;
3862 uint32_t recentFull = (underruns.mBitFields.mFull -
3863 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3864 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3865 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3866 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3867 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3868 uint32_t recentUnderruns = recentPartial + recentEmpty;
3869 track->mObservedUnderruns = underruns;
3870 // don't count underruns that occur while stopping or pausing
3871 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07003872 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3873 recentUnderruns > 0) {
3874 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3875 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Phil Burk2812d9e2016-01-04 10:34:30 -08003876 } else {
3877 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Eric Laurent81784c32012-11-19 14:55:58 -08003878 }
3879
3880 // This is similar to the state machine for normal tracks,
3881 // with a few modifications for fast tracks.
3882 bool isActive = true;
3883 switch (track->mState) {
3884 case TrackBase::STOPPING_1:
3885 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08003886 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003887 track->mState = TrackBase::STOPPING_2;
3888 }
3889 break;
3890 case TrackBase::PAUSING:
3891 // ramp down is not yet implemented
3892 track->setPaused();
3893 break;
3894 case TrackBase::RESUMING:
3895 // ramp up is not yet implemented
3896 track->mState = TrackBase::ACTIVE;
3897 break;
3898 case TrackBase::ACTIVE:
3899 if (recentFull > 0 || recentPartial > 0) {
3900 // track has provided at least some frames recently: reset retry count
3901 track->mRetryCount = kMaxTrackRetries;
3902 }
3903 if (recentUnderruns == 0) {
3904 // no recent underruns: stay active
3905 break;
3906 }
3907 // there has recently been an underrun of some kind
3908 if (track->sharedBuffer() == 0) {
3909 // were any of the recent underruns "empty" (no frames available)?
3910 if (recentEmpty == 0) {
3911 // no, then ignore the partial underruns as they are allowed indefinitely
3912 break;
3913 }
3914 // there has recently been an "empty" underrun: decrement the retry counter
3915 if (--(track->mRetryCount) > 0) {
3916 break;
3917 }
3918 // indicate to client process that the track was disabled because of underrun;
3919 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08003920 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08003921 // remove from active list, but state remains ACTIVE [confusing but true]
3922 isActive = false;
3923 break;
3924 }
3925 // fall through
3926 case TrackBase::STOPPING_2:
3927 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003928 case TrackBase::STOPPED:
3929 case TrackBase::FLUSHED: // flush() while active
3930 // Check for presentation complete if track is inactive
3931 // We have consumed all the buffers of this track.
3932 // This would be incomplete if we auto-paused on underrun
3933 {
3934 size_t audioHALFrames =
3935 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08003936 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003937 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
3938 // track stays in active list until presentation is complete
3939 break;
3940 }
3941 }
3942 if (track->isStopping_2()) {
3943 track->mState = TrackBase::STOPPED;
3944 }
3945 if (track->isStopped()) {
3946 // Can't reset directly, as fast mixer is still polling this track
3947 // track->reset();
3948 // So instead mark this track as needing to be reset after push with ack
3949 resetMask |= 1 << i;
3950 }
3951 isActive = false;
3952 break;
3953 case TrackBase::IDLE:
3954 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08003955 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08003956 }
3957
3958 if (isActive) {
3959 // was it previously inactive?
3960 if (!(state->mTrackMask & (1 << j))) {
3961 ExtendedAudioBufferProvider *eabp = track;
3962 VolumeProvider *vp = track;
3963 fastTrack->mBufferProvider = eabp;
3964 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08003965 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003966 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08003967 fastTrack->mGeneration++;
3968 state->mTrackMask |= 1 << j;
3969 didModify = true;
3970 // no acknowledgement required for newly active tracks
3971 }
3972 // cache the combined master volume and stream type volume for fast mixer; this
3973 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08003974 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08003975 ++fastTracks;
3976 } else {
3977 // was it previously active?
3978 if (state->mTrackMask & (1 << j)) {
3979 fastTrack->mBufferProvider = NULL;
3980 fastTrack->mGeneration++;
3981 state->mTrackMask &= ~(1 << j);
3982 didModify = true;
3983 // If any fast tracks were removed, we must wait for acknowledgement
3984 // because we're about to decrement the last sp<> on those tracks.
3985 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3986 } else {
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08003987 LOG_ALWAYS_FATAL("fast track %d should have been active; "
3988 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
3989 j, track->mState, state->mTrackMask, recentUnderruns,
3990 track->sharedBuffer() != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003991 }
3992 tracksToRemove->add(track);
3993 // Avoids a misleading display in dumpsys
3994 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
3995 }
3996 continue;
3997 }
3998
3999 { // local variable scope to avoid goto warning
4000
4001 audio_track_cblk_t* cblk = track->cblk();
4002
4003 // The first time a track is added we wait
4004 // for all its buffers to be filled before processing it
4005 int name = track->name();
4006 // make sure that we have enough frames to mix one full buffer.
4007 // enforce this condition only once to enable draining the buffer in case the client
4008 // app does not call stop() and relies on underrun to stop:
4009 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
4010 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004011 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07004012 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004013 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004014
4015 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004016 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004017 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
4018 // add frames already consumed but not yet released by the resampler
4019 // because mAudioTrackServerProxy->framesReady() will include these frames
4020 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
4021
Eric Laurent81784c32012-11-19 14:55:58 -08004022 uint32_t minFrames = 1;
4023 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
4024 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004025 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08004026 }
Eric Laurent13e4c962013-12-20 17:36:01 -08004027
4028 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07004029 if (ATRACE_ENABLED()) {
4030 // I wish we had formatted trace names
4031 char traceName[16];
4032 strcpy(traceName, "nRdy");
4033 int name = track->name();
4034 if (AudioMixer::TRACK0 <= name &&
4035 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
4036 name -= AudioMixer::TRACK0;
4037 traceName[4] = (name / 10) + '0';
4038 traceName[5] = (name % 10) + '0';
4039 } else {
4040 traceName[4] = '?';
4041 traceName[5] = '?';
4042 }
4043 traceName[6] = '\0';
4044 ATRACE_INT(traceName, framesReady);
4045 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004046 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08004047 !track->isPaused() && !track->isTerminated())
4048 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004049 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004050
4051 mixedTracks++;
4052
Andy Hung69aed5f2014-02-25 17:24:40 -08004053 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
4054 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08004055 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08004056 if (track->mainBuffer() != mSinkBuffer &&
4057 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004058 if (mEffectBufferEnabled) {
4059 mEffectBufferValid = true; // Later can set directly.
4060 }
Eric Laurent81784c32012-11-19 14:55:58 -08004061 chain = getEffectChain_l(track->sessionId());
4062 // Delegate volume control to effect in track effect chain if needed
4063 if (chain != 0) {
4064 tracksWithEffect++;
4065 } else {
4066 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
4067 "session %d",
4068 name, track->sessionId());
4069 }
4070 }
4071
4072
4073 int param = AudioMixer::VOLUME;
4074 if (track->mFillingUpStatus == Track::FS_FILLED) {
4075 // no ramp for the first volume setting
4076 track->mFillingUpStatus = Track::FS_ACTIVE;
4077 if (track->mState == TrackBase::RESUMING) {
4078 track->mState = TrackBase::ACTIVE;
4079 param = AudioMixer::RAMP_VOLUME;
4080 }
4081 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004082 // FIXME should not make a decision based on mServer
4083 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004084 // If the track is stopped before the first frame was mixed,
4085 // do not apply ramp
4086 param = AudioMixer::RAMP_VOLUME;
4087 }
4088
4089 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07004090 uint32_t vl, vr; // in U8.24 integer format
4091 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08004092 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07004093 vl = vr = 0;
4094 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08004095 if (track->isPausing()) {
4096 track->setPaused();
4097 }
4098 } else {
4099
4100 // read original volumes with volume control
4101 float typeVolume = mStreamTypes[track->streamType()].volume;
4102 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004103 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004104 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07004105 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
4106 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08004107 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07004108 if (vlf > GAIN_FLOAT_UNITY) {
4109 ALOGV("Track left volume out of range: %.3g", vlf);
4110 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004111 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07004112 if (vrf > GAIN_FLOAT_UNITY) {
4113 ALOGV("Track right volume out of range: %.3g", vrf);
4114 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004115 }
4116 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07004117 vlf *= v;
4118 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08004119 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07004120 // then derive vl and vr as U8.24 versions for the effect chain
4121 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
4122 vl = (uint32_t) (scaleto8_24 * vlf);
4123 vr = (uint32_t) (scaleto8_24 * vrf);
4124 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08004125 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08004126 // send level comes from shared memory and so may be corrupt
4127 if (sendLevel > MAX_GAIN_INT) {
4128 ALOGV("Track send level out of range: %04X", sendLevel);
4129 sendLevel = MAX_GAIN_INT;
4130 }
Andy Hung6be49402014-05-30 10:42:03 -07004131 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4132 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08004133 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004134
Eric Laurent81784c32012-11-19 14:55:58 -08004135 // Delegate volume control to effect in track effect chain if needed
4136 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4137 // Do not ramp volume if volume is controlled by effect
4138 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08004139 // Update remaining floating point volume levels
4140 vlf = (float)vl / (1 << 24);
4141 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004142 track->mHasVolumeController = true;
4143 } else {
4144 // force no volume ramp when volume controller was just disabled or removed
4145 // from effect chain to avoid volume spike
4146 if (track->mHasVolumeController) {
4147 param = AudioMixer::VOLUME;
4148 }
4149 track->mHasVolumeController = false;
4150 }
4151
Eric Laurent81784c32012-11-19 14:55:58 -08004152 // XXX: these things DON'T need to be done each time
4153 mAudioMixer->setBufferProvider(name, track);
4154 mAudioMixer->enable(name);
4155
Andy Hung6be49402014-05-30 10:42:03 -07004156 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
4157 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
4158 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004159 mAudioMixer->setParameter(
4160 name,
4161 AudioMixer::TRACK,
4162 AudioMixer::FORMAT, (void *)track->format());
4163 mAudioMixer->setParameter(
4164 name,
4165 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004166 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004167 mAudioMixer->setParameter(
4168 name,
4169 AudioMixer::TRACK,
4170 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004171 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004172 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004173 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004174 if (reqSampleRate == 0) {
4175 reqSampleRate = mSampleRate;
4176 } else if (reqSampleRate > maxSampleRate) {
4177 reqSampleRate = maxSampleRate;
4178 }
Eric Laurent81784c32012-11-19 14:55:58 -08004179 mAudioMixer->setParameter(
4180 name,
4181 AudioMixer::RESAMPLE,
4182 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004183 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004184
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004185 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004186 mAudioMixer->setParameter(
4187 name,
4188 AudioMixer::TIMESTRETCH,
4189 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004190 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004191
Andy Hung69aed5f2014-02-25 17:24:40 -08004192 /*
4193 * Select the appropriate output buffer for the track.
4194 *
Andy Hung98ef9782014-03-04 14:46:50 -08004195 * Tracks with effects go into their own effects chain buffer
4196 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004197 *
4198 * Other tracks can use mMixerBuffer for higher precision
4199 * channel accumulation. If this buffer is enabled
4200 * (mMixerBufferEnabled true), then selected tracks will accumulate
4201 * into it.
4202 *
4203 */
4204 if (mMixerBufferEnabled
4205 && (track->mainBuffer() == mSinkBuffer
4206 || track->mainBuffer() == mMixerBuffer)) {
4207 mAudioMixer->setParameter(
4208 name,
4209 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004210 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004211 mAudioMixer->setParameter(
4212 name,
4213 AudioMixer::TRACK,
4214 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4215 // TODO: override track->mainBuffer()?
4216 mMixerBufferValid = true;
4217 } else {
4218 mAudioMixer->setParameter(
4219 name,
4220 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004221 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004222 mAudioMixer->setParameter(
4223 name,
4224 AudioMixer::TRACK,
4225 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4226 }
Eric Laurent81784c32012-11-19 14:55:58 -08004227 mAudioMixer->setParameter(
4228 name,
4229 AudioMixer::TRACK,
4230 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4231
4232 // reset retry count
4233 track->mRetryCount = kMaxTrackRetries;
4234
4235 // If one track is ready, set the mixer ready if:
4236 // - the mixer was not ready during previous round OR
4237 // - no other track is not ready
4238 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4239 mixerStatus != MIXER_TRACKS_ENABLED) {
4240 mixerStatus = MIXER_TRACKS_READY;
4241 }
4242 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004243 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hung08fb1742015-05-31 23:22:10 -07004244 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)",
4245 track, framesReady, desiredFrames);
Glenn Kasten82aaf942013-07-17 16:05:07 -07004246 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08004247 } else {
4248 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004249 }
Phil Burk2812d9e2016-01-04 10:34:30 -08004250
Eric Laurent81784c32012-11-19 14:55:58 -08004251 // clear effect chain input buffer if an active track underruns to avoid sending
4252 // previous audio buffer again to effects
4253 chain = getEffectChain_l(track->sessionId());
4254 if (chain != 0) {
4255 chain->clearInputBuffer();
4256 }
4257
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004258 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004259 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4260 track->isStopped() || track->isPaused()) {
4261 // We have consumed all the buffers of this track.
4262 // Remove it from the list of active tracks.
4263 // TODO: use actual buffer filling status instead of latency when available from
4264 // audio HAL
4265 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004266 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004267 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4268 if (track->isStopped()) {
4269 track->reset();
4270 }
4271 tracksToRemove->add(track);
4272 }
4273 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004274 // No buffers for this track. Give it a few chances to
4275 // fill a buffer, then remove it from active list.
4276 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004277 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004278 tracksToRemove->add(track);
4279 // indicate to client process that the track was disabled because of underrun;
4280 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004281 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004282 // If one track is not ready, mark the mixer also not ready if:
4283 // - the mixer was ready during previous round OR
4284 // - no other track is ready
4285 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4286 mixerStatus != MIXER_TRACKS_READY) {
4287 mixerStatus = MIXER_TRACKS_ENABLED;
4288 }
4289 }
4290 mAudioMixer->disable(name);
4291 }
4292
4293 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08004294
4295 }
4296
4297 // Push the new FastMixer state if necessary
4298 bool pauseAudioWatchdog = false;
4299 if (didModify) {
4300 state->mFastTracksGen++;
4301 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4302 if (kUseFastMixer == FastMixer_Dynamic &&
4303 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4304 state->mCommand = FastMixerState::COLD_IDLE;
4305 state->mColdFutexAddr = &mFastMixerFutex;
4306 state->mColdGen++;
4307 mFastMixerFutex = 0;
4308 if (kUseFastMixer == FastMixer_Dynamic) {
4309 mNormalSink = mOutputSink;
4310 }
4311 // If we go into cold idle, need to wait for acknowledgement
4312 // so that fast mixer stops doing I/O.
4313 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4314 pauseAudioWatchdog = true;
4315 }
Eric Laurent81784c32012-11-19 14:55:58 -08004316 }
4317 if (sq != NULL) {
4318 sq->end(didModify);
4319 sq->push(block);
4320 }
4321#ifdef AUDIO_WATCHDOG
4322 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4323 mAudioWatchdog->pause();
4324 }
4325#endif
4326
4327 // Now perform the deferred reset on fast tracks that have stopped
4328 while (resetMask != 0) {
4329 size_t i = __builtin_ctz(resetMask);
4330 ALOG_ASSERT(i < count);
4331 resetMask &= ~(1 << i);
4332 sp<Track> t = mActiveTracks[i].promote();
4333 if (t == 0) {
4334 continue;
4335 }
4336 Track* track = t.get();
4337 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4338 track->reset();
4339 }
4340
4341 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004342 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004343
Eric Laurent97d547d2014-09-02 14:45:53 -07004344 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4345 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004346 }
4347
4348 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004349 // as long as there are effects we should clear the effects buffer, to avoid
4350 // passing a non-clean buffer to the effect chain
4351 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004352 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004353 // sink or mix buffer must be cleared if all tracks are connected to an
4354 // effect chain as in this case the mixer will not write to the sink or mix buffer
4355 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004356 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4357 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004358 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004359 if (mMixerBufferValid) {
4360 memset(mMixerBuffer, 0, mMixerBufferSize);
4361 // TODO: In testing, mSinkBuffer below need not be cleared because
4362 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4363 // after mixing.
4364 //
4365 // To enforce this guarantee:
4366 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4367 // (mixedTracks == 0 && fastTracks > 0))
4368 // must imply MIXER_TRACKS_READY.
4369 // Later, we may clear buffers regardless, and skip much of this logic.
4370 }
Andy Hung98ef9782014-03-04 14:46:50 -08004371 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004372 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004373 }
4374
4375 // if any fast tracks, then status is ready
4376 mMixerStatusIgnoringFastTracks = mixerStatus;
4377 if (fastTracks > 0) {
4378 mixerStatus = MIXER_TRACKS_READY;
4379 }
4380 return mixerStatus;
4381}
4382
4383// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07004384int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
Glenn Kastend848eb42016-03-08 13:42:11 -08004385 audio_format_t format, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08004386{
Andy Hunge8a1ced2014-05-09 15:02:21 -07004387 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08004388}
4389
4390// deleteTrackName_l() must be called with ThreadBase::mLock held
4391void AudioFlinger::MixerThread::deleteTrackName_l(int name)
4392{
4393 ALOGV("remove track (%d) and delete from mixer", name);
4394 mAudioMixer->deleteTrackName(name);
4395}
4396
Eric Laurent10351942014-05-08 18:49:52 -07004397// checkForNewParameter_l() must be called with ThreadBase::mLock held
4398bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4399 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004400{
Eric Laurent81784c32012-11-19 14:55:58 -08004401 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08004402 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004403
Eric Laurent10351942014-05-08 18:49:52 -07004404 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004405
Glenn Kastenc05b8d72016-03-24 09:48:17 -07004406 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004407
Eric Laurent10351942014-05-08 18:49:52 -07004408 AudioParameter param = AudioParameter(keyValuePair);
4409 int value;
4410 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4411 reconfig = true;
4412 }
4413 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004414 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004415 status = BAD_VALUE;
4416 } else {
4417 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004418 reconfig = true;
4419 }
Eric Laurent10351942014-05-08 18:49:52 -07004420 }
4421 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004422 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004423 status = BAD_VALUE;
4424 } else {
4425 // no need to save value, since it's constant
4426 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004427 }
Eric Laurent10351942014-05-08 18:49:52 -07004428 }
4429 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4430 // do not accept frame count changes if tracks are open as the track buffer
4431 // size depends on frame count and correct behavior would not be guaranteed
4432 // if frame count is changed after track creation
4433 if (!mTracks.isEmpty()) {
4434 status = INVALID_OPERATION;
4435 } else {
4436 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004437 }
Eric Laurent10351942014-05-08 18:49:52 -07004438 }
4439 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004440#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004441 // when changing the audio output device, call addBatteryData to notify
4442 // the change
4443 if (mOutDevice != value) {
4444 uint32_t params = 0;
4445 // check whether speaker is on
4446 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4447 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004448 }
Eric Laurent10351942014-05-08 18:49:52 -07004449
4450 audio_devices_t deviceWithoutSpeaker
4451 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4452 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07004453 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07004454 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4455 }
4456
4457 if (params != 0) {
4458 addBatteryData(params);
4459 }
4460 }
Eric Laurent81784c32012-11-19 14:55:58 -08004461#endif
4462
Eric Laurent10351942014-05-08 18:49:52 -07004463 // forward device change to effects that have requested to be
4464 // aware of attached audio device.
4465 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08004466 a2dpDeviceChanged =
4467 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07004468 mOutDevice = value;
4469 for (size_t i = 0; i < mEffectChains.size(); i++) {
4470 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004471 }
4472 }
Eric Laurent10351942014-05-08 18:49:52 -07004473 }
Eric Laurent81784c32012-11-19 14:55:58 -08004474
Eric Laurent10351942014-05-08 18:49:52 -07004475 if (status == NO_ERROR) {
4476 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4477 keyValuePair.string());
4478 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004479 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004480 mStandby = true;
4481 mBytesWritten = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004482 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Eric Laurent10351942014-05-08 18:49:52 -07004483 keyValuePair.string());
Eric Laurent81784c32012-11-19 14:55:58 -08004484 }
Eric Laurent10351942014-05-08 18:49:52 -07004485 if (status == NO_ERROR && reconfig) {
4486 readOutputParameters_l();
4487 delete mAudioMixer;
4488 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4489 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004490 int name = getTrackName_l(mTracks[i]->mChannelMask,
4491 mTracks[i]->mFormat, mTracks[i]->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07004492 if (name < 0) {
4493 break;
4494 }
4495 mTracks[i]->mName = name;
4496 }
Eric Laurent73e26b62015-04-27 16:55:58 -07004497 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004498 }
Eric Laurent81784c32012-11-19 14:55:58 -08004499 }
4500
Eric Laurent42537be2016-01-08 17:16:42 -08004501 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08004502}
4503
4504
4505void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4506{
Eric Laurent81784c32012-11-19 14:55:58 -08004507 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07004508 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Elliott Hughes87cebad2014-05-22 10:14:43 -07004509 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Andy Hung2ddee192015-12-18 17:34:44 -08004510 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent81784c32012-11-19 14:55:58 -08004511
4512 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten2f90c512015-12-02 11:40:09 -08004513 // while we are dumping it. It may be inconsistent, but it won't mutate!
4514 // This is a large object so we place it on the heap.
4515 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
4516 const FastMixerDumpState *copy = new FastMixerDumpState(mFastMixerDumpState);
4517 copy->dump(fd);
4518 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08004519
4520#ifdef STATE_QUEUE_DUMP
4521 // Similar for state queue
4522 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4523 observerCopy.dump(fd);
4524 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4525 mutatorCopy.dump(fd);
4526#endif
4527
Glenn Kasten46909e72013-02-26 09:20:22 -08004528#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004529 // Write the tee output to a .wav file
4530 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08004531#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004532
4533#ifdef AUDIO_WATCHDOG
4534 if (mAudioWatchdog != 0) {
4535 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4536 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4537 wdCopy.dump(fd);
4538 }
4539#endif
4540}
4541
4542uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4543{
4544 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4545}
4546
4547uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4548{
4549 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4550}
4551
4552void AudioFlinger::MixerThread::cacheParameters_l()
4553{
4554 PlaybackThread::cacheParameters_l();
4555
4556 // FIXME: Relaxed timing because of a certain device that can't meet latency
4557 // Should be reduced to 2x after the vendor fixes the driver issue
4558 // increase threshold again due to low power audio mode. The way this warning
4559 // threshold is calculated and its usefulness should be reconsidered anyway.
4560 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4561}
4562
4563// ----------------------------------------------------------------------------
4564
4565AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent51716182016-02-29 18:00:56 -08004566 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady,
4567 uint32_t bitRate)
4568 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady, bitRate)
Eric Laurent81784c32012-11-19 14:55:58 -08004569 // mLeftVolFloat, mRightVolFloat
4570{
4571}
4572
Eric Laurentbfb1b832013-01-07 09:53:42 -08004573AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4574 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurent51716182016-02-29 18:00:56 -08004575 ThreadBase::type_t type, bool systemReady, uint32_t bitRate)
4576 : PlaybackThread(audioFlinger, output, id, device, type, systemReady, bitRate)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004577 // mLeftVolFloat, mRightVolFloat
4578{
4579}
4580
Eric Laurent81784c32012-11-19 14:55:58 -08004581AudioFlinger::DirectOutputThread::~DirectOutputThread()
4582{
4583}
4584
Eric Laurentbfb1b832013-01-07 09:53:42 -08004585void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
4586{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004587 float left, right;
4588
4589 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4590 left = right = 0;
4591 } else {
4592 float typeVolume = mStreamTypes[track->streamType()].volume;
4593 float v = mMasterVolume * typeVolume;
4594 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004595 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4596 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4597 if (left > GAIN_FLOAT_UNITY) {
4598 left = GAIN_FLOAT_UNITY;
4599 }
4600 left *= v;
4601 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4602 if (right > GAIN_FLOAT_UNITY) {
4603 right = GAIN_FLOAT_UNITY;
4604 }
4605 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004606 }
4607
4608 if (lastTrack) {
4609 if (left != mLeftVolFloat || right != mRightVolFloat) {
4610 mLeftVolFloat = left;
4611 mRightVolFloat = right;
4612
4613 // Convert volumes from float to 8.24
4614 uint32_t vl = (uint32_t)(left * (1 << 24));
4615 uint32_t vr = (uint32_t)(right * (1 << 24));
4616
4617 // Delegate volume control to effect in track effect chain if needed
4618 // only one effect chain can be present on DirectOutputThread, so if
4619 // there is one, the track is connected to it
4620 if (!mEffectChains.isEmpty()) {
4621 mEffectChains[0]->setVolume_l(&vl, &vr);
4622 left = (float)vl / (1 << 24);
4623 right = (float)vr / (1 << 24);
4624 }
4625 if (mOutput->stream->set_volume) {
4626 mOutput->stream->set_volume(mOutput->stream, left, right);
4627 }
4628 }
4629 }
4630}
4631
Phil Burk43b4dcc2015-06-09 16:53:44 -07004632void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
4633{
4634 sp<Track> previousTrack = mPreviousTrack.promote();
4635 sp<Track> latestTrack = mLatestActiveTrack.promote();
4636
Eric Laurent0f0631e2015-07-06 18:01:25 -07004637 if (previousTrack != 0 && latestTrack != 0) {
4638 if (mType == DIRECT) {
4639 if (previousTrack.get() != latestTrack.get()) {
4640 mFlushPending = true;
4641 }
4642 } else /* mType == OFFLOAD */ {
4643 if (previousTrack->sessionId() != latestTrack->sessionId()) {
4644 mFlushPending = true;
4645 }
4646 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004647 }
4648 PlaybackThread::onAddNewTrack_l();
4649}
Eric Laurentbfb1b832013-01-07 09:53:42 -08004650
Eric Laurent81784c32012-11-19 14:55:58 -08004651AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4652 Vector< sp<Track> > *tracksToRemove
4653)
4654{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004655 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004656 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004657 bool doHwPause = false;
4658 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004659
4660 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07004661 for (size_t i = 0; i < count; i++) {
4662 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08004663 // The track died recently
4664 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004665 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08004666 }
4667
Phil Burk43b4dcc2015-06-09 16:53:44 -07004668 if (t->isInvalid()) {
4669 ALOGW("An invalidated track shouldn't be in active list");
4670 tracksToRemove->add(t);
4671 continue;
4672 }
4673
Eric Laurent81784c32012-11-19 14:55:58 -08004674 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004675#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08004676 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004677#endif
Eric Laurentfd477972013-10-25 18:10:40 -07004678 // Only consider last track started for volume and mixer state control.
4679 // In theory an older track could underrun and restart after the new one starts
4680 // but as we only care about the transition phase between two tracks on a
4681 // direct output, it is not a problem to ignore the underrun case.
4682 sp<Track> l = mLatestActiveTrack.promote();
4683 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004684
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004685 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004686 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004687 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004688 doHwPause = true;
4689 mHwPaused = true;
4690 }
4691 tracksToRemove->add(track);
4692 } else if (track->isFlushPending()) {
4693 track->flushAck();
4694 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004695 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004696 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004697 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004698 track->resumeAck();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004699 if (last && mHwPaused) {
4700 doHwResume = true;
4701 mHwPaused = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004702 }
4703 }
4704
Eric Laurent81784c32012-11-19 14:55:58 -08004705 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004706 // for all its buffers to be filled before processing it.
4707 // Allow draining the buffer in case the client
4708 // app does not call stop() and relies on underrun to stop:
4709 // hence the test on (track->mRetryCount > 1).
4710 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07004711 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08004712 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004713 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08004714 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004715 minFrames = mNormalFrameCount;
4716 } else {
4717 minFrames = 1;
4718 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004719
Eric Laurentab5cdba2014-06-09 17:22:27 -07004720 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4721 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004722 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004723 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004724
4725 if (track->mFillingUpStatus == Track::FS_FILLED) {
4726 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004727 // make sure processVolume_l() will apply new volume even if 0
4728 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004729 if (!mHwSupportsPause) {
4730 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004731 }
4732 }
4733
4734 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004735 processVolume_l(track, last);
4736 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004737 sp<Track> previousTrack = mPreviousTrack.promote();
4738 if (previousTrack != 0) {
4739 if (track != previousTrack.get()) {
4740 // Flush any data still being written from last track
4741 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07004742 // Invalidate previous track to force a seek when resuming.
4743 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004744 }
4745 }
4746 mPreviousTrack = track;
4747
Eric Laurentd595b7c2013-04-03 17:27:56 -07004748 // reset retry count
4749 track->mRetryCount = kMaxTrackRetriesDirect;
4750 mActiveTrack = t;
4751 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07004752 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004753 doHwResume = true;
4754 mHwPaused = false;
4755 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004756 }
Eric Laurent81784c32012-11-19 14:55:58 -08004757 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004758 // clear effect chain input buffer if the last active track started underruns
4759 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004760 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004761 mEffectChains[0]->clearInputBuffer();
4762 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004763 if (track->isStopping_1()) {
4764 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07004765 if (last && mHwPaused) {
4766 doHwResume = true;
4767 mHwPaused = false;
4768 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004769 }
4770 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4771 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004772 // We have consumed all the buffers of this track.
4773 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004774 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08004775 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004776 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4777 } else {
4778 audioHALFrames = 0;
4779 }
4780
Andy Hung818e7a32016-02-16 18:08:07 -08004781 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004782 if (mStandby || !last ||
4783 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004784 if (track->isStopping_2()) {
4785 track->mState = TrackBase::STOPPED;
4786 }
Eric Laurent81784c32012-11-19 14:55:58 -08004787 if (track->isStopped()) {
4788 track->reset();
4789 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004790 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004791 }
4792 } else {
4793 // No buffers for this track. Give it a few chances to
4794 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004795 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004796 if (--(track->mRetryCount) <= 0) {
4797 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004798 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004799 // indicate to client process that the track was disabled because of underrun;
4800 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004801 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004802 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07004803 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
4804 "minFrames = %u, mFormat = %#x",
4805 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08004806 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07004807 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004808 doHwPause = true;
4809 mHwPaused = true;
4810 }
Eric Laurent81784c32012-11-19 14:55:58 -08004811 }
4812 }
4813 }
4814 }
4815
Eric Laurentd1f69b02014-12-15 14:33:13 -08004816 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07004817 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004818 for (size_t i = 0; i < mTracks.size(); i++) {
4819 if (mTracks[i]->isFlushPending()) {
4820 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004821 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004822 }
4823 }
4824 }
4825
4826 // make sure the pause/flush/resume sequence is executed in the right order.
4827 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4828 // before flush and then resume HW. This can happen in case of pause/flush/resume
4829 // if resume is received before pause is executed.
4830 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07004831 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004832 mOutput->stream->pause(mOutput->stream);
4833 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004834 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004835 flushHw_l();
4836 }
4837 if (mHwSupportsPause && !mStandby && doHwResume) {
4838 mOutput->stream->resume(mOutput->stream);
4839 }
Eric Laurent81784c32012-11-19 14:55:58 -08004840 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004841 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004842
4843 return mixerStatus;
4844}
4845
4846void AudioFlinger::DirectOutputThread::threadLoop_mix()
4847{
Eric Laurent81784c32012-11-19 14:55:58 -08004848 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08004849 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004850 // output audio to hardware
4851 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07004852 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004853 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08004854 status_t status = mActiveTrack->getNextBuffer(&buffer);
4855 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08004856 // no need to pad with 0 for compressed audio
4857 if (audio_has_proportional_frames(mFormat)) {
4858 memset(curBuf, 0, frameCount * mFrameSize);
4859 }
Eric Laurent81784c32012-11-19 14:55:58 -08004860 break;
4861 }
4862 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
4863 frameCount -= buffer.frameCount;
4864 curBuf += buffer.frameCount * mFrameSize;
4865 mActiveTrack->releaseBuffer(&buffer);
4866 }
Andy Hung2098f272014-02-27 14:00:06 -08004867 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004868 mSleepTimeUs = 0;
4869 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004870 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004871}
4872
4873void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
4874{
Eric Laurentd1f69b02014-12-15 14:33:13 -08004875 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004876 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004877 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004878 return;
4879 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004880 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004881 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurent51716182016-02-29 18:00:56 -08004882 // For compressed offload, use faster sleep time when underruning until more than an
4883 // entire buffer was written to the audio HAL
4884 if (!audio_has_proportional_frames(mFormat) &&
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004885 (mType == OFFLOAD) && (mBytesWritten < (int64_t) mBufferSize)) {
Eric Laurent51716182016-02-29 18:00:56 -08004886 mSleepTimeUs = kDirectMinSleepTimeUs;
4887 } else {
4888 mSleepTimeUs = mActiveSleepTimeUs;
4889 }
Eric Laurent81784c32012-11-19 14:55:58 -08004890 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004891 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004892 }
Phil Burkfdb3c072016-02-09 10:47:02 -08004893 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08004894 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004895 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004896 }
4897}
4898
Eric Laurentd1f69b02014-12-15 14:33:13 -08004899void AudioFlinger::DirectOutputThread::threadLoop_exit()
4900{
4901 {
4902 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08004903 for (size_t i = 0; i < mTracks.size(); i++) {
4904 if (mTracks[i]->isFlushPending()) {
4905 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004906 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004907 }
4908 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004909 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004910 flushHw_l();
4911 }
4912 }
4913 PlaybackThread::threadLoop_exit();
4914}
4915
4916// must be called with thread mutex locked
4917bool AudioFlinger::DirectOutputThread::shouldStandby_l()
4918{
4919 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07004920 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004921
vivek mehta9cd7ad12016-03-17 00:18:29 -07004922 if ((mType == DIRECT) && audio_is_linear_pcm(mFormat) && !usesHwAvSync()) {
4923 return !mStandby;
4924 }
4925
Eric Laurentd1f69b02014-12-15 14:33:13 -08004926 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4927 // after a timeout and we will enter standby then.
4928 if (mTracks.size() > 0) {
4929 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07004930 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
4931 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004932 }
4933
Eric Laurent5cff4032015-05-26 13:49:58 -07004934 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08004935}
4936
Eric Laurent81784c32012-11-19 14:55:58 -08004937// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004938int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Glenn Kastend848eb42016-03-08 13:42:11 -08004939 audio_format_t format __unused, audio_session_t sessionId __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004940{
4941 return 0;
4942}
4943
4944// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004945void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004946{
4947}
4948
Eric Laurent10351942014-05-08 18:49:52 -07004949// checkForNewParameter_l() must be called with ThreadBase::mLock held
4950bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
4951 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004952{
4953 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08004954 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004955
Eric Laurent10351942014-05-08 18:49:52 -07004956 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004957
Eric Laurent10351942014-05-08 18:49:52 -07004958 AudioParameter param = AudioParameter(keyValuePair);
4959 int value;
4960 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4961 // forward device change to effects that have requested to be
4962 // aware of attached audio device.
4963 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08004964 a2dpDeviceChanged =
4965 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07004966 mOutDevice = value;
4967 for (size_t i = 0; i < mEffectChains.size(); i++) {
4968 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07004969 }
4970 }
Eric Laurent81784c32012-11-19 14:55:58 -08004971 }
Eric Laurent10351942014-05-08 18:49:52 -07004972 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4973 // do not accept frame count changes if tracks are open as the track buffer
4974 // size depends on frame count and correct behavior would not be garantied
4975 // if frame count is changed after track creation
4976 if (!mTracks.isEmpty()) {
4977 status = INVALID_OPERATION;
4978 } else {
4979 reconfig = true;
4980 }
4981 }
4982 if (status == NO_ERROR) {
4983 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4984 keyValuePair.string());
4985 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004986 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004987 mStandby = true;
4988 mBytesWritten = 0;
4989 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4990 keyValuePair.string());
4991 }
4992 if (status == NO_ERROR && reconfig) {
4993 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07004994 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004995 }
4996 }
4997
Eric Laurent42537be2016-01-08 17:16:42 -08004998 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08004999}
5000
5001uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
5002{
5003 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005004 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005005 time = PlaybackThread::activeSleepTimeUs();
5006 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005007 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005008 }
5009 return time;
5010}
5011
5012uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
5013{
5014 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005015 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005016 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
5017 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005018 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005019 }
5020 return time;
5021}
5022
5023uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
5024{
5025 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005026 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005027 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
5028 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005029 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005030 }
5031 return time;
5032}
5033
5034void AudioFlinger::DirectOutputThread::cacheParameters_l()
5035{
5036 PlaybackThread::cacheParameters_l();
5037
5038 // use shorter standby delay as on normal output to release
5039 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07005040 // no delay on outputs with HW A/V sync
5041 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005042 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08005043 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005044 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07005045 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005046 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07005047 }
Eric Laurent81784c32012-11-19 14:55:58 -08005048}
5049
Eric Laurente659ef42014-09-29 13:06:46 -07005050void AudioFlinger::DirectOutputThread::flushHw_l()
5051{
Phil Burk062e67a2015-02-11 13:40:50 -08005052 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08005053 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005054 mFlushPending = false;
Eric Laurente659ef42014-09-29 13:06:46 -07005055}
5056
Eric Laurent81784c32012-11-19 14:55:58 -08005057// ----------------------------------------------------------------------------
5058
Eric Laurentbfb1b832013-01-07 09:53:42 -08005059AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07005060 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005061 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07005062 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07005063 mWriteAckSequence(0),
5064 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005065{
5066}
5067
5068AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
5069{
5070}
5071
5072void AudioFlinger::AsyncCallbackThread::onFirstRef()
5073{
5074 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
5075}
5076
5077bool AudioFlinger::AsyncCallbackThread::threadLoop()
5078{
5079 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005080 uint32_t writeAckSequence;
5081 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005082
5083 {
5084 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005085 while (!((mWriteAckSequence & 1) ||
5086 (mDrainSequence & 1) ||
5087 exitPending())) {
5088 mWaitWorkCV.wait(mLock);
5089 }
5090
Eric Laurentbfb1b832013-01-07 09:53:42 -08005091 if (exitPending()) {
5092 break;
5093 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005094 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
5095 mWriteAckSequence, mDrainSequence);
5096 writeAckSequence = mWriteAckSequence;
5097 mWriteAckSequence &= ~1;
5098 drainSequence = mDrainSequence;
5099 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005100 }
5101 {
Eric Laurent4de95592013-09-26 15:28:21 -07005102 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
5103 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005104 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005105 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005106 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005107 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005108 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005109 }
5110 }
5111 }
5112 }
5113 return false;
5114}
5115
5116void AudioFlinger::AsyncCallbackThread::exit()
5117{
5118 ALOGV("AsyncCallbackThread::exit");
5119 Mutex::Autolock _l(mLock);
5120 requestExit();
5121 mWaitWorkCV.broadcast();
5122}
5123
Eric Laurent3b4529e2013-09-05 18:09:19 -07005124void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005125{
5126 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005127 // bit 0 is cleared
5128 mWriteAckSequence = sequence << 1;
5129}
5130
5131void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5132{
5133 Mutex::Autolock _l(mLock);
5134 // ignore unexpected callbacks
5135 if (mWriteAckSequence & 2) {
5136 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005137 mWaitWorkCV.signal();
5138 }
5139}
5140
Eric Laurent3b4529e2013-09-05 18:09:19 -07005141void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005142{
5143 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005144 // bit 0 is cleared
5145 mDrainSequence = sequence << 1;
5146}
5147
5148void AudioFlinger::AsyncCallbackThread::resetDraining()
5149{
5150 Mutex::Autolock _l(mLock);
5151 // ignore unexpected callbacks
5152 if (mDrainSequence & 2) {
5153 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005154 mWaitWorkCV.signal();
5155 }
5156}
5157
5158
5159// ----------------------------------------------------------------------------
5160AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent51716182016-02-29 18:00:56 -08005161 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady,
5162 uint32_t bitRate)
5163 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady, bitRate),
Eric Laurent64667972016-03-30 18:19:46 -07005164 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005165{
Eric Laurentfd477972013-10-25 18:10:40 -07005166 //FIXME: mStandby should be set to true by ThreadBase constructor
5167 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07005168 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005169}
5170
Eric Laurentbfb1b832013-01-07 09:53:42 -08005171void AudioFlinger::OffloadThread::threadLoop_exit()
5172{
5173 if (mFlushPending || mHwPaused) {
5174 // If a flush is pending or track was paused, just discard buffered data
5175 flushHw_l();
5176 } else {
5177 mMixerStatus = MIXER_DRAIN_ALL;
5178 threadLoop_drain();
5179 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005180 if (mUseAsyncWrite) {
5181 ALOG_ASSERT(mCallbackThread != 0);
5182 mCallbackThread->exit();
5183 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005184 PlaybackThread::threadLoop_exit();
5185}
5186
5187AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5188 Vector< sp<Track> > *tracksToRemove
5189)
5190{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005191 size_t count = mActiveTracks.size();
5192
5193 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005194 bool doHwPause = false;
5195 bool doHwResume = false;
5196
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005197 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07005198
Eric Laurentbfb1b832013-01-07 09:53:42 -08005199 // find out which tracks need to be processed
5200 for (size_t i = 0; i < count; i++) {
5201 sp<Track> t = mActiveTracks[i].promote();
5202 // The track died recently
5203 if (t == 0) {
5204 continue;
5205 }
5206 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005207#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08005208 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005209#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005210 // Only consider last track started for volume and mixer state control.
5211 // In theory an older track could underrun and restart after the new one starts
5212 // but as we only care about the transition phase between two tracks on a
5213 // direct output, it is not a problem to ignore the underrun case.
5214 sp<Track> l = mLatestActiveTrack.promote();
5215 bool last = l.get() == track;
5216
Haynes Mathew George7844f672014-01-15 12:32:55 -08005217 if (track->isInvalid()) {
5218 ALOGW("An invalidated track shouldn't be in active list");
5219 tracksToRemove->add(track);
5220 continue;
5221 }
5222
5223 if (track->mState == TrackBase::IDLE) {
5224 ALOGW("An idle track shouldn't be in active list");
5225 continue;
5226 }
5227
Eric Laurentbfb1b832013-01-07 09:53:42 -08005228 if (track->isPausing()) {
5229 track->setPaused();
5230 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005231 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005232 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005233 mHwPaused = true;
5234 }
5235 // If we were part way through writing the mixbuffer to
5236 // the HAL we must save this until we resume
5237 // BUG - this will be wrong if a different track is made active,
5238 // in that case we want to discard the pending data in the
5239 // mixbuffer and tell the client to present it again when the
5240 // track is resumed
5241 mPausedWriteLength = mCurrentWriteLength;
5242 mPausedBytesRemaining = mBytesRemaining;
5243 mBytesRemaining = 0; // stop writing
5244 }
5245 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005246 } else if (track->isFlushPending()) {
Eric Laurent51716182016-02-29 18:00:56 -08005247 track->mRetryCount = kMaxTrackRetriesOffload;
Haynes Mathew George7844f672014-01-15 12:32:55 -08005248 track->flushAck();
5249 if (last) {
5250 mFlushPending = true;
5251 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005252 } else if (track->isResumePending()){
5253 track->resumeAck();
5254 if (last) {
5255 if (mPausedBytesRemaining) {
5256 // Need to continue write that was interrupted
5257 mCurrentWriteLength = mPausedWriteLength;
5258 mBytesRemaining = mPausedBytesRemaining;
5259 mPausedBytesRemaining = 0;
5260 }
5261 if (mHwPaused) {
5262 doHwResume = true;
5263 mHwPaused = false;
5264 // threadLoop_mix() will handle the case that we need to
5265 // resume an interrupted write
5266 }
5267 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005268 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005269
5270 // Do not handle new data in this iteration even if track->framesReady()
5271 mixerStatus = MIXER_TRACKS_ENABLED;
5272 }
5273 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005274 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005275 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005276 if (track->mFillingUpStatus == Track::FS_FILLED) {
5277 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07005278 // make sure processVolume_l() will apply new volume even if 0
5279 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005280 }
5281
5282 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005283 sp<Track> previousTrack = mPreviousTrack.promote();
5284 if (previousTrack != 0) {
5285 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005286 // Flush any data still being written from last track
5287 mBytesRemaining = 0;
5288 if (mPausedBytesRemaining) {
5289 // Last track was paused so we also need to flush saved
5290 // mixbuffer state and invalidate track so that it will
5291 // re-submit that unwritten data when it is next resumed
5292 mPausedBytesRemaining = 0;
5293 // Invalidate is a bit drastic - would be more efficient
5294 // to have a flag to tell client that some of the
5295 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005296 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005297 }
5298 // flush data already sent to the DSP if changing audio session as audio
5299 // comes from a different source. Also invalidate previous track to force a
5300 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005301 if (previousTrack->sessionId() != track->sessionId()) {
5302 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005303 }
5304 }
5305 }
5306 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005307 // reset retry count
5308 track->mRetryCount = kMaxTrackRetriesOffload;
5309 mActiveTrack = t;
5310 mixerStatus = MIXER_TRACKS_READY;
5311 }
5312 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005313 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005314 if (track->isStopping_1()) {
5315 // Hardware buffer can hold a large amount of audio so we must
5316 // wait for all current track's data to drain before we say
5317 // that the track is stopped.
5318 if (mBytesRemaining == 0) {
5319 // Only start draining when all data in mixbuffer
5320 // has been written
5321 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5322 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005323 // do not drain if no data was ever sent to HAL (mStandby == true)
5324 if (last && !mStandby) {
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005325 // do not modify drain sequence if we are already draining. This happens
5326 // when resuming from pause after drain.
5327 if ((mDrainSequence & 1) == 0) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005328 mSleepTimeUs = 0;
5329 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005330 mixerStatus = MIXER_DRAIN_TRACK;
5331 mDrainSequence += 2;
5332 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005333 if (mHwPaused) {
5334 // It is possible to move from PAUSED to STOPPING_1 without
5335 // a resume so we must ensure hardware is running
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005336 doHwResume = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005337 mHwPaused = false;
5338 }
5339 }
5340 }
5341 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005342 // Drain has completed or we are in standby, signal presentation complete
5343 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005344 track->mState = TrackBase::STOPPED;
5345 size_t audioHALFrames =
5346 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005347 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005348 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005349 track->presentationComplete(framesWritten, audioHALFrames);
5350 track->reset();
5351 tracksToRemove->add(track);
5352 }
5353 } else {
5354 // No buffers for this track. Give it a few chances to
5355 // fill a buffer, then remove it from active list.
5356 if (--(track->mRetryCount) <= 0) {
5357 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5358 track->name());
5359 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005360 // indicate to client process that the track was disabled because of underrun;
5361 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005362 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005363 } else if (last){
5364 mixerStatus = MIXER_TRACKS_ENABLED;
5365 }
5366 }
5367 }
5368 // compute volume for this track
5369 processVolume_l(track, last);
5370 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005371
Eric Laurentea0fade2013-10-04 16:23:48 -07005372 // make sure the pause/flush/resume sequence is executed in the right order.
5373 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5374 // before flush and then resume HW. This can happen in case of pause/flush/resume
5375 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07005376 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07005377 mOutput->stream->pause(mOutput->stream);
5378 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005379 if (mFlushPending) {
5380 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005381 }
Eric Laurentfd477972013-10-25 18:10:40 -07005382 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07005383 mOutput->stream->resume(mOutput->stream);
5384 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005385
Eric Laurentbfb1b832013-01-07 09:53:42 -08005386 // remove all the tracks that need to be...
5387 removeTracks_l(*tracksToRemove);
5388
5389 return mixerStatus;
5390}
5391
Eric Laurentbfb1b832013-01-07 09:53:42 -08005392// must be called with thread mutex locked
5393bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5394{
Eric Laurent3b4529e2013-09-05 18:09:19 -07005395 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5396 mWriteAckSequence, mDrainSequence);
5397 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005398 return true;
5399 }
5400 return false;
5401}
5402
Eric Laurentbfb1b832013-01-07 09:53:42 -08005403bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5404{
5405 Mutex::Autolock _l(mLock);
5406 return waitingAsyncCallback_l();
5407}
5408
5409void AudioFlinger::OffloadThread::flushHw_l()
5410{
Eric Laurente659ef42014-09-29 13:06:46 -07005411 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005412 // Flush anything still waiting in the mixbuffer
5413 mCurrentWriteLength = 0;
5414 mBytesRemaining = 0;
5415 mPausedWriteLength = 0;
5416 mPausedBytesRemaining = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08005417
Eric Laurentbfb1b832013-01-07 09:53:42 -08005418 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005419 // discard any pending drain or write ack by incrementing sequence
5420 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5421 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005422 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005423 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5424 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005425 }
5426}
5427
Eric Laurent51716182016-02-29 18:00:56 -08005428uint32_t AudioFlinger::OffloadThread::activeSleepTimeUs() const
5429{
5430 uint32_t time;
5431 if (audio_has_proportional_frames(mFormat)) {
5432 time = PlaybackThread::activeSleepTimeUs();
5433 } else {
5434 // sleep time is half the duration of an audio HAL buffer.
5435 // Note: This can be problematic in case of underrun with variable bit rate and
5436 // current rate is much less than initial rate.
5437 time = (uint32_t)max(kDirectMinSleepTimeUs, mBufferDurationUs / 2);
5438 }
5439 return time;
5440}
5441
Eric Laurentbfb1b832013-01-07 09:53:42 -08005442// ----------------------------------------------------------------------------
5443
Eric Laurent81784c32012-11-19 14:55:58 -08005444AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005445 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005446 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07005447 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08005448 mWaitTimeMs(UINT_MAX)
5449{
5450 addOutputTrack(mainThread);
5451}
5452
5453AudioFlinger::DuplicatingThread::~DuplicatingThread()
5454{
5455 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5456 mOutputTracks[i]->destroy();
5457 }
5458}
5459
5460void AudioFlinger::DuplicatingThread::threadLoop_mix()
5461{
5462 // mix buffers...
5463 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08005464 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08005465 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005466 if (mMixerBufferValid) {
5467 memset(mMixerBuffer, 0, mMixerBufferSize);
5468 } else {
5469 memset(mSinkBuffer, 0, mSinkBufferSize);
5470 }
Eric Laurent81784c32012-11-19 14:55:58 -08005471 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005472 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005473 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005474 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005475 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005476}
5477
5478void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5479{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005480 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005481 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005482 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005483 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005484 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005485 }
5486 } else if (mBytesWritten != 0) {
5487 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5488 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005489 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005490 } else {
5491 // flush remaining overflow buffers in output tracks
5492 writeFrames = 0;
5493 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005494 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005495 }
5496}
5497
Eric Laurentbfb1b832013-01-07 09:53:42 -08005498ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005499{
5500 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005501 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005502 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005503 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005504 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005505}
5506
5507void AudioFlinger::DuplicatingThread::threadLoop_standby()
5508{
5509 // DuplicatingThread implements standby by stopping all tracks
5510 for (size_t i = 0; i < outputTracks.size(); i++) {
5511 outputTracks[i]->stop();
5512 }
5513}
5514
5515void AudioFlinger::DuplicatingThread::saveOutputTracks()
5516{
5517 outputTracks = mOutputTracks;
5518}
5519
5520void AudioFlinger::DuplicatingThread::clearOutputTracks()
5521{
5522 outputTracks.clear();
5523}
5524
5525void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5526{
5527 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005528 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5529 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5530 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5531 const size_t frameCount =
5532 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5533 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5534 // from different OutputTracks and their associated MixerThreads (e.g. one may
5535 // nearly empty and the other may be dropping data).
5536
5537 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005538 this,
5539 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005540 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005541 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005542 frameCount,
5543 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08005544 if (outputTrack->cblk() != NULL) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005545 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
Eric Laurent81784c32012-11-19 14:55:58 -08005546 mOutputTracks.add(outputTrack);
Andy Hungc25b84a2015-01-14 19:04:10 -08005547 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005548 updateWaitTime_l();
5549 }
5550}
5551
5552void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5553{
5554 Mutex::Autolock _l(mLock);
5555 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5556 if (mOutputTracks[i]->thread() == thread) {
5557 mOutputTracks[i]->destroy();
5558 mOutputTracks.removeAt(i);
5559 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07005560 if (thread->getOutput() == mOutput) {
5561 mOutput = NULL;
5562 }
Eric Laurent81784c32012-11-19 14:55:58 -08005563 return;
5564 }
5565 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07005566 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005567}
5568
5569// caller must hold mLock
5570void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5571{
5572 mWaitTimeMs = UINT_MAX;
5573 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5574 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5575 if (strong != 0) {
5576 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5577 if (waitTimeMs < mWaitTimeMs) {
5578 mWaitTimeMs = waitTimeMs;
5579 }
5580 }
5581 }
5582}
5583
5584
5585bool AudioFlinger::DuplicatingThread::outputsReady(
5586 const SortedVector< sp<OutputTrack> > &outputTracks)
5587{
5588 for (size_t i = 0; i < outputTracks.size(); i++) {
5589 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5590 if (thread == 0) {
5591 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5592 outputTracks[i].get());
5593 return false;
5594 }
5595 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5596 // see note at standby() declaration
5597 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5598 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5599 thread.get());
5600 return false;
5601 }
5602 }
5603 return true;
5604}
5605
5606uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5607{
5608 return (mWaitTimeMs * 1000) / 2;
5609}
5610
5611void AudioFlinger::DuplicatingThread::cacheParameters_l()
5612{
5613 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5614 updateWaitTime_l();
5615
5616 MixerThread::cacheParameters_l();
5617}
5618
5619// ----------------------------------------------------------------------------
5620// Record
5621// ----------------------------------------------------------------------------
5622
5623AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5624 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005625 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005626 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07005627 audio_devices_t inDevice,
5628 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08005629#ifdef TEE_SINK
5630 , const sp<NBAIO_Sink>& teeSink
5631#endif
5632 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07005633 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005634 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005635 // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005636 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005637#ifdef TEE_SINK
5638 , mTeeSink(teeSink)
5639#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005640 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5641 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005642 // mFastCapture below
5643 , mFastCaptureFutex(0)
5644 // mInputSource
5645 // mPipeSink
5646 // mPipeSource
5647 , mPipeFramesP2(0)
5648 // mPipeMemory
5649 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005650 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005651{
Glenn Kastend7dca052015-03-05 16:05:54 -08005652 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5653 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08005654
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005655 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005656
5657 // create an NBAIO source for the HAL input stream, and negotiate
5658 mInputSource = new AudioStreamInSource(input->stream);
5659 size_t numCounterOffers = 0;
5660 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005661#if !LOG_NDEBUG
5662 ssize_t index =
5663#else
5664 (void)
5665#endif
5666 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005667 ALOG_ASSERT(index == 0);
5668
5669 // initialize fast capture depending on configuration
5670 bool initFastCapture;
5671 switch (kUseFastCapture) {
5672 case FastCapture_Never:
5673 initFastCapture = false;
5674 break;
5675 case FastCapture_Always:
5676 initFastCapture = true;
5677 break;
5678 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07005679 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005680 break;
5681 // case FastCapture_Dynamic:
5682 }
5683
5684 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07005685 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005686 NBAIO_Format format = mInputSource->format();
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005687 size_t pipeFramesP2 = roundup(mSampleRate / 25); // double-buffering of 20 ms each
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005688 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5689 void *pipeBuffer;
5690 const sp<MemoryDealer> roHeap(readOnlyHeap());
5691 sp<IMemory> pipeMemory;
5692 if ((roHeap == 0) ||
5693 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5694 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5695 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5696 goto failed;
5697 }
5698 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5699 memset(pipeBuffer, 0, pipeSize);
5700 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5701 const NBAIO_Format offers[1] = {format};
5702 size_t numCounterOffers = 0;
5703 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5704 ALOG_ASSERT(index == 0);
5705 mPipeSink = pipe;
5706 PipeReader *pipeReader = new PipeReader(*pipe);
5707 numCounterOffers = 0;
5708 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5709 ALOG_ASSERT(index == 0);
5710 mPipeSource = pipeReader;
5711 mPipeFramesP2 = pipeFramesP2;
5712 mPipeMemory = pipeMemory;
5713
5714 // create fast capture
5715 mFastCapture = new FastCapture();
5716 FastCaptureStateQueue *sq = mFastCapture->sq();
5717#ifdef STATE_QUEUE_DUMP
5718 // FIXME
5719#endif
5720 FastCaptureState *state = sq->begin();
5721 state->mCblk = NULL;
5722 state->mInputSource = mInputSource.get();
5723 state->mInputSourceGen++;
5724 state->mPipeSink = pipe;
5725 state->mPipeSinkGen++;
5726 state->mFrameCount = mFrameCount;
5727 state->mCommand = FastCaptureState::COLD_IDLE;
5728 // already done in constructor initialization list
5729 //mFastCaptureFutex = 0;
5730 state->mColdFutexAddr = &mFastCaptureFutex;
5731 state->mColdGen++;
5732 state->mDumpState = &mFastCaptureDumpState;
5733#ifdef TEE_SINK
5734 // FIXME
5735#endif
5736 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
5737 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
5738 sq->end();
5739 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5740
5741 // start the fast capture
5742 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
5743 pid_t tid = mFastCapture->getTid();
Glenn Kasten8379b722016-03-18 14:54:17 -07005744 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005745#ifdef AUDIO_WATCHDOG
5746 // FIXME
5747#endif
5748
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005749 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005750 }
5751failed: ;
5752
5753 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08005754}
5755
Eric Laurent81784c32012-11-19 14:55:58 -08005756AudioFlinger::RecordThread::~RecordThread()
5757{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005758 if (mFastCapture != 0) {
5759 FastCaptureStateQueue *sq = mFastCapture->sq();
5760 FastCaptureState *state = sq->begin();
5761 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5762 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5763 if (old == -1) {
5764 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5765 }
5766 }
5767 state->mCommand = FastCaptureState::EXIT;
5768 sq->end();
5769 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5770 mFastCapture->join();
5771 mFastCapture.clear();
5772 }
5773 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07005774 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07005775 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08005776}
5777
5778void AudioFlinger::RecordThread::onFirstRef()
5779{
Glenn Kastend7dca052015-03-05 16:05:54 -08005780 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08005781}
5782
Eric Laurent81784c32012-11-19 14:55:58 -08005783bool AudioFlinger::RecordThread::threadLoop()
5784{
Eric Laurent81784c32012-11-19 14:55:58 -08005785 nsecs_t lastWarning = 0;
5786
5787 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08005788
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005789reacquire_wakelock:
5790 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08005791 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005792 {
5793 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005794 size_t size = mActiveTracks.size();
5795 activeTracksGen = mActiveTracksGen;
5796 if (size > 0) {
5797 // FIXME an arbitrary choice
5798 activeTrack = mActiveTracks[0];
5799 acquireWakeLock_l(activeTrack->uid());
5800 if (size > 1) {
5801 SortedVector<int> tmp;
5802 for (size_t i = 0; i < size; i++) {
5803 tmp.add(mActiveTracks[i]->uid());
5804 }
5805 updateWakeLockUids_l(tmp);
5806 }
5807 } else {
5808 acquireWakeLock_l(-1);
5809 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005810 }
5811
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005812 // used to request a deferred sleep, to be executed later while mutex is unlocked
5813 uint32_t sleepUs = 0;
5814
5815 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005816 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005817 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07005818
Glenn Kasten5edadd42013-08-14 16:30:49 -07005819 // sleep with mutex unlocked
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005820 if (sleepUs > 0) {
Glenn Kastene7754022014-10-31 12:11:26 -07005821 ATRACE_BEGIN("sleep");
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005822 usleep(sleepUs);
Glenn Kastene7754022014-10-31 12:11:26 -07005823 ATRACE_END();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005824 sleepUs = 0;
Glenn Kasten5edadd42013-08-14 16:30:49 -07005825 }
5826
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005827 // activeTracks accumulates a copy of a subset of mActiveTracks
5828 Vector< sp<RecordTrack> > activeTracks;
5829
Glenn Kasten735f45f2014-08-18 15:51:59 -07005830 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005831 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07005832
Glenn Kasten735f45f2014-08-18 15:51:59 -07005833 // reference to a fast track which is about to be removed
5834 sp<RecordTrack> fastTrackToRemove;
5835
Eric Laurent81784c32012-11-19 14:55:58 -08005836 { // scope for mLock
5837 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08005838
Eric Laurent021cf962014-05-13 10:18:14 -07005839 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005840
Eric Laurent000a4192014-01-29 15:17:32 -08005841 // check exitPending here because checkForNewParameters_l() and
5842 // checkForNewParameters_l() can temporarily release mLock
5843 if (exitPending()) {
5844 break;
5845 }
5846
Glenn Kasten2b806402013-11-20 16:37:38 -08005847 // if no active track(s), then standby and release wakelock
5848 size_t size = mActiveTracks.size();
5849 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07005850 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005851 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08005852 releaseWakeLock_l();
5853 ALOGV("RecordThread: loop stopping");
5854 // go to sleep
5855 mWaitWorkCV.wait(mLock);
5856 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005857 goto reacquire_wakelock;
5858 }
5859
Glenn Kasten2b806402013-11-20 16:37:38 -08005860 if (mActiveTracksGen != activeTracksGen) {
5861 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005862 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08005863 for (size_t i = 0; i < size; i++) {
5864 tmp.add(mActiveTracks[i]->uid());
5865 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005866 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08005867 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005868
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005869 bool doBroadcast = false;
5870 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07005871
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005872 activeTrack = mActiveTracks[i];
5873 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07005874 if (activeTrack->isFastTrack()) {
5875 ALOG_ASSERT(fastTrackToRemove == 0);
5876 fastTrackToRemove = activeTrack;
5877 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005878 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08005879 mActiveTracks.remove(activeTrack);
5880 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005881 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07005882 continue;
5883 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005884
5885 TrackBase::track_state activeTrackState = activeTrack->mState;
5886 switch (activeTrackState) {
5887
5888 case TrackBase::PAUSING:
5889 mActiveTracks.remove(activeTrack);
5890 mActiveTracksGen++;
5891 doBroadcast = true;
5892 size--;
5893 continue;
5894
5895 case TrackBase::STARTING_1:
5896 sleepUs = 10000;
5897 i++;
5898 continue;
5899
5900 case TrackBase::STARTING_2:
5901 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005902 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07005903 activeTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005904 break;
5905
5906 case TrackBase::ACTIVE:
5907 break;
5908
5909 case TrackBase::IDLE:
5910 i++;
5911 continue;
5912
5913 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08005914 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07005915 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005916
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005917 activeTracks.add(activeTrack);
5918 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07005919
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005920 if (activeTrack->isFastTrack()) {
5921 ALOG_ASSERT(!mFastTrackAvail);
5922 ALOG_ASSERT(fastTrack == 0);
5923 fastTrack = activeTrack;
5924 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005925 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005926 if (doBroadcast) {
5927 mStartStopCond.broadcast();
5928 }
5929
5930 // sleep if there are no active tracks to process
5931 if (activeTracks.size() == 0) {
5932 if (sleepUs == 0) {
5933 sleepUs = kRecordThreadSleepUs;
5934 }
5935 continue;
5936 }
5937 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07005938
Eric Laurent81784c32012-11-19 14:55:58 -08005939 lockEffectChains_l(effectChains);
5940 }
5941
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005942 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07005943
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005944 size_t size = effectChains.size();
5945 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005946 // thread mutex is not locked, but effect chain is locked
5947 effectChains[i]->process_l();
5948 }
5949
Glenn Kasten735f45f2014-08-18 15:51:59 -07005950 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005951 if (mFastCapture != 0) {
5952 FastCaptureStateQueue *sq = mFastCapture->sq();
5953 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07005954 bool didModify = false;
5955 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005956 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
5957 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
5958 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5959 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5960 if (old == -1) {
5961 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5962 }
5963 }
5964 state->mCommand = FastCaptureState::READ_WRITE;
5965#if 0 // FIXME
5966 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08005967 FastThreadDumpState::kSamplingNforLowRamDevice :
5968 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005969#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07005970 didModify = true;
5971 }
5972 audio_track_cblk_t *cblkOld = state->mCblk;
5973 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
5974 if (cblkNew != cblkOld) {
5975 state->mCblk = cblkNew;
5976 // block until acked if removing a fast track
5977 if (cblkOld != NULL) {
5978 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
5979 }
5980 didModify = true;
5981 }
5982 sq->end(didModify);
5983 if (didModify) {
5984 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005985#if 0
5986 if (kUseFastCapture == FastCapture_Dynamic) {
5987 mNormalSource = mPipeSource;
5988 }
5989#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005990 }
5991 }
5992
Glenn Kasten735f45f2014-08-18 15:51:59 -07005993 // now run the fast track destructor with thread mutex unlocked
5994 fastTrackToRemove.clear();
5995
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005996 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
5997 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
5998 // slow, then this RecordThread will overrun by not calling HAL read often enough.
5999 // If destination is non-contiguous, first read past the nominal end of buffer, then
6000 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006001
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006002 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006003 ssize_t framesRead;
6004
6005 // If an NBAIO source is present, use it to read the normal capture's data
6006 if (mPipeSource != 0) {
6007 size_t framesToRead = mBufferSize / mFrameSize;
Andy Hung57446612015-04-19 23:56:46 -07006008 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
Glenn Kastend79072e2016-01-06 08:41:20 -08006009 framesToRead);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006010 if (framesRead == 0) {
6011 // since pipe is non-blocking, simulate blocking input
6012 sleepUs = (framesToRead * 1000000LL) / mSampleRate;
6013 }
6014 // otherwise use the HAL / AudioStreamIn directly
6015 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07006016 ATRACE_BEGIN("read");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006017 ssize_t bytesRead = mInput->stream->read(mInput->stream,
Andy Hung57446612015-04-19 23:56:46 -07006018 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize);
Glenn Kastenec6a7032016-03-14 07:40:23 -07006019 ATRACE_END();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006020 if (bytesRead < 0) {
6021 framesRead = bytesRead;
6022 } else {
6023 framesRead = bytesRead / mFrameSize;
6024 }
6025 }
6026
Andy Hung3f0c9022016-01-15 17:49:46 -08006027 // Update server timestamp with server stats
6028 // systemTime() is optional if the hardware supports timestamps.
6029 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
6030 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6031
6032 // Update server timestamp with kernel stats
6033 if (mInput->stream->get_capture_position != nullptr) {
6034 int64_t position, time;
6035 int ret = mInput->stream->get_capture_position(mInput->stream, &position, &time);
6036 if (ret == NO_ERROR) {
6037 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
6038 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
6039 // Note: In general record buffers should tend to be empty in
6040 // a properly running pipeline.
6041 //
6042 // Also, it is not advantageous to call get_presentation_position during the read
6043 // as the read obtains a lock, preventing the timestamp call from executing.
6044 }
6045 }
6046 // Use this to track timestamp information
6047 // ALOGD("%s", mTimestamp.toString().c_str());
6048
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006049 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006050 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006051 // Force input into standby so that it tries to recover at next read attempt
6052 inputStandBy();
6053 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006054 }
6055 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006056 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006057 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006058 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006059
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006060 if (mTeeSink != 0) {
Andy Hung57446612015-04-19 23:56:46 -07006061 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006062 }
6063 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006064 {
6065 size_t part1 = mRsmpInFramesP2 - rear;
6066 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07006067 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006068 (framesRead - part1) * mFrameSize);
6069 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006070 }
6071 rear = mRsmpInRear += framesRead;
6072
6073 size = activeTracks.size();
6074 // loop over each active track
6075 for (size_t i = 0; i < size; i++) {
6076 activeTrack = activeTracks[i];
6077
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006078 // skip fast tracks, as those are handled directly by FastCapture
6079 if (activeTrack->isFastTrack()) {
6080 continue;
6081 }
6082
Andy Hung73c02e42015-03-29 01:13:58 -07006083 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07006084 // TODO: Update the activeTrack buffer converter in case of reconfigure.
6085
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006086 enum {
6087 OVERRUN_UNKNOWN,
6088 OVERRUN_TRUE,
6089 OVERRUN_FALSE
6090 } overrun = OVERRUN_UNKNOWN;
6091
6092 // loop over getNextBuffer to handle circular sink
6093 for (;;) {
6094
6095 activeTrack->mSink.frameCount = ~0;
6096 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
6097 size_t framesOut = activeTrack->mSink.frameCount;
6098 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
6099
Andy Hung73c02e42015-03-29 01:13:58 -07006100 // check available frames and handle overrun conditions
6101 // if the record track isn't draining fast enough.
6102 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006103 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07006104 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
6105 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006106 overrun = OVERRUN_TRUE;
6107 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006108 if (framesOut == 0 || framesIn == 0) {
6109 break;
6110 }
6111
Andy Hung6770c6f2015-04-07 13:43:36 -07006112 // Don't allow framesOut to be larger than what is possible with resampling
6113 // from framesIn.
6114 // This isn't strictly necessary but helps limit buffer resizing in
6115 // RecordBufferConverter. TODO: remove when no longer needed.
6116 framesOut = min(framesOut,
6117 destinationFramesPossible(
6118 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07006119 // process frames from the RecordThread buffer provider to the RecordTrack buffer
6120 framesOut = activeTrack->mRecordBufferConverter->convert(
6121 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006122
6123 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
6124 overrun = OVERRUN_FALSE;
6125 }
6126
6127 if (activeTrack->mFramesToDrop == 0) {
6128 if (framesOut > 0) {
6129 activeTrack->mSink.frameCount = framesOut;
6130 activeTrack->releaseBuffer(&activeTrack->mSink);
6131 }
6132 } else {
6133 // FIXME could do a partial drop of framesOut
6134 if (activeTrack->mFramesToDrop > 0) {
6135 activeTrack->mFramesToDrop -= framesOut;
6136 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006137 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006138 }
6139 } else {
6140 activeTrack->mFramesToDrop += framesOut;
6141 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
6142 activeTrack->mSyncStartEvent->isCancelled()) {
6143 ALOGW("Synced record %s, session %d, trigger session %d",
6144 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
6145 activeTrack->sessionId(),
6146 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08006147 activeTrack->mSyncStartEvent->triggerSession() :
6148 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006149 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006150 }
6151 }
6152 }
6153
6154 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006155 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006156 }
6157 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006158
6159 switch (overrun) {
6160 case OVERRUN_TRUE:
6161 // client isn't retrieving buffers fast enough
6162 if (!activeTrack->setOverflow()) {
6163 nsecs_t now = systemTime();
6164 // FIXME should lastWarning per track?
6165 if ((now - lastWarning) > kWarningThrottleNs) {
6166 ALOGW("RecordThread: buffer overflow");
6167 lastWarning = now;
6168 }
6169 }
6170 break;
6171 case OVERRUN_FALSE:
6172 activeTrack->clearOverflow();
6173 break;
6174 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006175 break;
6176 }
6177
Andy Hung3f0c9022016-01-15 17:49:46 -08006178 // update frame information and push timestamp out
6179 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08006180 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08006181 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
6182 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006183 }
6184
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006185unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08006186 // enable changes in effect chain
6187 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006188 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08006189 }
6190
Glenn Kasten93e471f2013-08-19 08:40:07 -07006191 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08006192
6193 {
6194 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07006195 for (size_t i = 0; i < mTracks.size(); i++) {
6196 sp<RecordTrack> track = mTracks[i];
6197 track->invalidate();
6198 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006199 mActiveTracks.clear();
6200 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08006201 mStartStopCond.broadcast();
6202 }
6203
6204 releaseWakeLock();
6205
6206 ALOGV("RecordThread %p exiting", this);
6207 return false;
6208}
6209
Glenn Kasten93e471f2013-08-19 08:40:07 -07006210void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08006211{
6212 if (!mStandby) {
6213 inputStandBy();
6214 mStandby = true;
6215 }
6216}
6217
6218void AudioFlinger::RecordThread::inputStandBy()
6219{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006220 // Idle the fast capture if it's currently running
6221 if (mFastCapture != 0) {
6222 FastCaptureStateQueue *sq = mFastCapture->sq();
6223 FastCaptureState *state = sq->begin();
6224 if (!(state->mCommand & FastCaptureState::IDLE)) {
6225 state->mCommand = FastCaptureState::COLD_IDLE;
6226 state->mColdFutexAddr = &mFastCaptureFutex;
6227 state->mColdGen++;
6228 mFastCaptureFutex = 0;
6229 sq->end();
6230 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
6231 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
6232#if 0
6233 if (kUseFastCapture == FastCapture_Dynamic) {
6234 // FIXME
6235 }
6236#endif
6237#ifdef AUDIO_WATCHDOG
6238 // FIXME
6239#endif
6240 } else {
6241 sq->end(false /*didModify*/);
6242 }
6243 }
Eric Laurent81784c32012-11-19 14:55:58 -08006244 mInput->stream->common.standby(&mInput->stream->common);
6245}
6246
Glenn Kasten05997e22014-03-13 15:08:33 -07006247// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07006248sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08006249 const sp<AudioFlinger::Client>& client,
6250 uint32_t sampleRate,
6251 audio_format_t format,
6252 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08006253 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08006254 audio_session_t sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07006255 size_t *notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006256 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07006257 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08006258 pid_t tid,
6259 status_t *status)
6260{
Glenn Kasten74935e42013-12-19 08:56:45 -08006261 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08006262 sp<RecordTrack> track;
6263 status_t lStatus;
6264
Glenn Kasten90e58b12013-07-31 16:16:02 -07006265 // client expresses a preference for FAST, but we get the final say
6266 if (*flags & IAudioFlinger::TRACK_FAST) {
6267 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07006268 // we formerly checked for a callback handler (non-0 tid),
6269 // but that is no longer required for TRANSFER_OBTAIN mode
6270 //
Glenn Kasten74105912014-07-03 12:28:53 -07006271 // frame count is not specified, or is exactly the pipe depth
6272 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006273 // PCM data
6274 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006275 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006276 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006277 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006278 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006279 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07006280 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006281 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006282 hasFastCapture() &&
6283 // there are sufficient fast track slots available
6284 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07006285 ) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006286 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
Glenn Kasten90e58b12013-07-31 16:16:02 -07006287 frameCount, mFrameCount);
6288 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006289 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
Glenn Kasten74105912014-07-03 12:28:53 -07006290 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006291 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07006292 frameCount, mFrameCount, mPipeFramesP2,
6293 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
6294 hasFastCapture(), tid, mFastTrackAvail);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006295 *flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kasten74105912014-07-03 12:28:53 -07006296 }
6297 }
6298
6299 // compute track buffer size in frames, and suggest the notification frame count
6300 if (*flags & IAudioFlinger::TRACK_FAST) {
6301 // fast track: frame count is exactly the pipe depth
6302 frameCount = mPipeFramesP2;
6303 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
6304 *notificationFrames = mFrameCount;
6305 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006306 // not fast track: max notification period is resampled equivalent of one HAL buffer time
6307 // or 20 ms if there is a fast capture
6308 // TODO This could be a roundupRatio inline, and const
6309 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
6310 * sampleRate + mSampleRate - 1) / mSampleRate;
6311 // minimum number of notification periods is at least kMinNotifications,
6312 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
6313 static const size_t kMinNotifications = 3;
6314 static const uint32_t kMinMs = 30;
6315 // TODO This could be a roundupRatio inline
6316 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
6317 // TODO This could be a roundupRatio inline
6318 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
6319 maxNotificationFrames;
6320 const size_t minFrameCount = maxNotificationFrames *
6321 max(kMinNotifications, minNotificationsByMs);
6322 frameCount = max(frameCount, minFrameCount);
6323 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
6324 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07006325 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07006326 }
Glenn Kasten74935e42013-12-19 08:56:45 -08006327 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07006328
Glenn Kasten15e57982013-09-24 11:52:37 -07006329 lStatus = initCheck();
6330 if (lStatus != NO_ERROR) {
6331 ALOGE("createRecordTrack_l() audio driver not initialized");
6332 goto Exit;
6333 }
Eric Laurent81784c32012-11-19 14:55:58 -08006334
6335 { // scope for mLock
6336 Mutex::Autolock _l(mLock);
6337
6338 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07006339 format, channelMask, frameCount, NULL, sessionId, uid,
6340 *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08006341
Glenn Kasten03003332013-08-06 15:40:54 -07006342 lStatus = track->initCheck();
6343 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07006344 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08006345 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08006346 goto Exit;
6347 }
6348 mTracks.add(track);
6349
6350 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6351 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6352 mAudioFlinger->btNrecIsOff();
6353 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6354 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006355
6356 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
6357 pid_t callingPid = IPCThreadState::self()->getCallingPid();
6358 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
6359 // so ask activity manager to do this on our behalf
6360 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
6361 }
Eric Laurent81784c32012-11-19 14:55:58 -08006362 }
Glenn Kasten05997e22014-03-13 15:08:33 -07006363
Eric Laurent81784c32012-11-19 14:55:58 -08006364 lStatus = NO_ERROR;
6365
6366Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07006367 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08006368 return track;
6369}
6370
6371status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6372 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08006373 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08006374{
6375 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6376 sp<ThreadBase> strongMe = this;
6377 status_t status = NO_ERROR;
6378
6379 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006380 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006381 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006382 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08006383 triggerSession,
6384 recordTrack->sessionId(),
6385 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006386 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08006387 // Sync event can be cancelled by the trigger session if the track is not in a
6388 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006389 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006390 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006391 } else {
6392 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006393 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006394 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08006395 }
6396 }
6397
6398 {
Glenn Kasten47c20702013-08-13 15:37:35 -07006399 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08006400 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006401 if (mActiveTracks.indexOf(recordTrack) >= 0) {
6402 if (recordTrack->mState == TrackBase::PAUSING) {
6403 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006404 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006405 } else {
6406 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08006407 }
6408 return status;
6409 }
6410
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006411 // TODO consider other ways of handling this, such as changing the state to :STARTING and
6412 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6413 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006414 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08006415 mActiveTracks.add(recordTrack);
6416 mActiveTracksGen++;
Eric Laurent83b88082014-06-20 18:31:16 -07006417 status_t status = NO_ERROR;
6418 if (recordTrack->isExternalTrack()) {
6419 mLock.unlock();
Glenn Kastend848eb42016-03-08 13:42:11 -08006420 status = AudioSystem::startInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006421 mLock.lock();
6422 // FIXME should verify that recordTrack is still in mActiveTracks
6423 if (status != NO_ERROR) {
6424 mActiveTracks.remove(recordTrack);
6425 mActiveTracksGen++;
6426 recordTrack->clearSyncStartEvent();
6427 ALOGV("RecordThread::start error %d", status);
6428 return status;
6429 }
Eric Laurent81784c32012-11-19 14:55:58 -08006430 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006431 // Catch up with current buffer indices if thread is already running.
6432 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
6433 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6434 // see previously buffered data before it called start(), but with greater risk of overrun.
6435
Andy Hung73c02e42015-03-29 01:13:58 -07006436 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07006437 // clear any converter state as new data will be discontinuous
6438 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006439 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08006440 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08006441 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08006442 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006443 ALOGV("Record failed to start");
6444 status = BAD_VALUE;
6445 goto startError;
6446 }
Eric Laurent81784c32012-11-19 14:55:58 -08006447 return status;
6448 }
Glenn Kasten7c027242012-12-26 14:43:16 -08006449
Eric Laurent81784c32012-11-19 14:55:58 -08006450startError:
Eric Laurent83b88082014-06-20 18:31:16 -07006451 if (recordTrack->isExternalTrack()) {
Glenn Kastend848eb42016-03-08 13:42:11 -08006452 AudioSystem::stopInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006453 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006454 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006455 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08006456 return status;
6457}
6458
Eric Laurent81784c32012-11-19 14:55:58 -08006459void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6460{
6461 sp<SyncEvent> strongEvent = event.promote();
6462
6463 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08006464 sp<RefBase> ptr = strongEvent->cookie().promote();
6465 if (ptr != 0) {
6466 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6467 recordTrack->handleSyncStartEvent(strongEvent);
6468 }
Eric Laurent81784c32012-11-19 14:55:58 -08006469 }
6470}
6471
Glenn Kastena8356f62013-07-25 14:37:52 -07006472bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08006473 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07006474 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006475 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08006476 return false;
6477 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006478 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006479 recordTrack->mState = TrackBase::PAUSING;
6480 // do not wait for mStartStopCond if exiting
6481 if (exitPending()) {
6482 return true;
6483 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006484 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08006485 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006486 // if we have been restarted, recordTrack is in mActiveTracks here
6487 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006488 ALOGV("Record stopped OK");
6489 return true;
6490 }
6491 return false;
6492}
6493
Glenn Kasten0f11b512014-01-31 16:18:54 -08006494bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08006495{
6496 return false;
6497}
6498
Glenn Kasten0f11b512014-01-31 16:18:54 -08006499status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006500{
6501#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6502 if (!isValidSyncEvent(event)) {
6503 return BAD_VALUE;
6504 }
6505
Glenn Kastend848eb42016-03-08 13:42:11 -08006506 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08006507 status_t ret = NAME_NOT_FOUND;
6508
6509 Mutex::Autolock _l(mLock);
6510
6511 for (size_t i = 0; i < mTracks.size(); i++) {
6512 sp<RecordTrack> track = mTracks[i];
6513 if (eventSession == track->sessionId()) {
6514 (void) track->setSyncEvent(event);
6515 ret = NO_ERROR;
6516 }
6517 }
6518 return ret;
6519#else
6520 return BAD_VALUE;
6521#endif
6522}
6523
6524// destroyTrack_l() must be called with ThreadBase::mLock held
6525void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6526{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006527 track->terminate();
6528 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006529 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006530 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006531 removeTrack_l(track);
6532 }
6533}
6534
6535void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6536{
6537 mTracks.remove(track);
6538 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006539 if (track->isFastTrack()) {
6540 ALOG_ASSERT(!mFastTrackAvail);
6541 mFastTrackAvail = true;
6542 }
Eric Laurent81784c32012-11-19 14:55:58 -08006543}
6544
6545void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6546{
6547 dumpInternals(fd, args);
6548 dumpTracks(fd, args);
6549 dumpEffectChains(fd, args);
6550}
6551
6552void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6553{
Elliott Hughes87cebad2014-05-22 10:14:43 -07006554 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08006555
Glenn Kasten44182c22015-03-05 17:12:23 -08006556 dumpBase(fd, args);
6557
6558 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006559 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006560 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006561 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006562 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08006563
Glenn Kasten2f90c512015-12-02 11:40:09 -08006564 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
6565 // while we are dumping it. It may be inconsistent, but it won't mutate!
6566 // This is a large object so we place it on the heap.
6567 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
6568 const FastCaptureDumpState *copy = new FastCaptureDumpState(mFastCaptureDumpState);
6569 copy->dump(fd);
6570 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08006571}
6572
Glenn Kasten0f11b512014-01-31 16:18:54 -08006573void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006574{
6575 const size_t SIZE = 256;
6576 char buffer[SIZE];
6577 String8 result;
6578
Marco Nelissenb2208842014-02-07 14:00:50 -08006579 size_t numtracks = mTracks.size();
6580 size_t numactive = mActiveTracks.size();
6581 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006582 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006583 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006584 dprintf(fd, " of which %zu are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006585 RecordTrack::appendDumpHeader(result);
6586 for (size_t i = 0; i < numtracks ; ++i) {
6587 sp<RecordTrack> track = mTracks[i];
6588 if (track != 0) {
6589 bool active = mActiveTracks.indexOf(track) >= 0;
6590 if (active) {
6591 numactiveseen++;
6592 }
6593 track->dump(buffer, SIZE, active);
6594 result.append(buffer);
6595 }
Eric Laurent81784c32012-11-19 14:55:58 -08006596 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006597 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006598 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006599 }
6600
Marco Nelissenb2208842014-02-07 14:00:50 -08006601 if (numactiveseen != numactive) {
6602 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6603 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006604 result.append(buffer);
6605 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006606 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006607 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006608 if (mTracks.indexOf(track) < 0) {
6609 track->dump(buffer, SIZE, true);
6610 result.append(buffer);
6611 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006612 }
Eric Laurent81784c32012-11-19 14:55:58 -08006613
6614 }
6615 write(fd, result.string(), result.size());
6616}
6617
Andy Hung73c02e42015-03-29 01:13:58 -07006618
6619void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
6620{
6621 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6622 RecordThread *recordThread = (RecordThread *) threadBase.get();
6623 mRsmpInFront = recordThread->mRsmpInRear;
6624 mRsmpInUnrel = 0;
6625}
6626
6627void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
6628 size_t *framesAvailable, bool *hasOverrun)
6629{
6630 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6631 RecordThread *recordThread = (RecordThread *) threadBase.get();
6632 const int32_t rear = recordThread->mRsmpInRear;
6633 const int32_t front = mRsmpInFront;
6634 const ssize_t filled = rear - front;
6635
6636 size_t framesIn;
6637 bool overrun = false;
6638 if (filled < 0) {
6639 // should not happen, but treat like a massive overrun and re-sync
6640 framesIn = 0;
6641 mRsmpInFront = rear;
6642 overrun = true;
6643 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
6644 framesIn = (size_t) filled;
6645 } else {
6646 // client is not keeping up with server, but give it latest data
6647 framesIn = recordThread->mRsmpInFrames;
6648 mRsmpInFront = /* front = */ rear - framesIn;
6649 overrun = true;
6650 }
6651 if (framesAvailable != NULL) {
6652 *framesAvailable = framesIn;
6653 }
6654 if (hasOverrun != NULL) {
6655 *hasOverrun = overrun;
6656 }
6657}
6658
Eric Laurent81784c32012-11-19 14:55:58 -08006659// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006660status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08006661 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006662{
Andy Hung73c02e42015-03-29 01:13:58 -07006663 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006664 if (threadBase == 0) {
6665 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006666 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006667 return NOT_ENOUGH_DATA;
6668 }
6669 RecordThread *recordThread = (RecordThread *) threadBase.get();
6670 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07006671 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07006672 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006673 // FIXME should not be P2 (don't want to increase latency)
6674 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006675 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07006676 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006677 front &= recordThread->mRsmpInFramesP2 - 1;
6678 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07006679 if (part1 > (size_t) filled) {
6680 part1 = filled;
6681 }
6682 size_t ask = buffer->frameCount;
6683 ALOG_ASSERT(ask > 0);
6684 if (part1 > ask) {
6685 part1 = ask;
6686 }
6687 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07006688 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07006689 buffer->raw = NULL;
6690 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07006691 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07006692 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08006693 }
6694
Andy Hung57446612015-04-19 23:56:46 -07006695 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07006696 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07006697 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08006698 return NO_ERROR;
6699}
6700
6701// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006702void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
6703 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006704{
Glenn Kasten85948432013-08-19 12:09:05 -07006705 size_t stepCount = buffer->frameCount;
6706 if (stepCount == 0) {
6707 return;
6708 }
Andy Hung73c02e42015-03-29 01:13:58 -07006709 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
6710 mRsmpInUnrel -= stepCount;
6711 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006712 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006713 buffer->frameCount = 0;
6714}
6715
Andy Hung97a893e2015-03-29 01:03:07 -07006716AudioFlinger::RecordThread::RecordBufferConverter::RecordBufferConverter(
6717 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6718 uint32_t srcSampleRate,
6719 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6720 uint32_t dstSampleRate) :
6721 mSrcChannelMask(AUDIO_CHANNEL_INVALID), // updateParameters will set following vars
6722 // mSrcFormat
6723 // mSrcSampleRate
6724 // mDstChannelMask
6725 // mDstFormat
6726 // mDstSampleRate
6727 // mSrcChannelCount
6728 // mDstChannelCount
6729 // mDstFrameSize
6730 mBuf(NULL), mBufFrames(0), mBufFrameSize(0),
Andy Hungd330ee42015-04-20 13:23:41 -07006731 mResampler(NULL),
6732 mIsLegacyDownmix(false),
6733 mIsLegacyUpmix(false),
6734 mRequiresFloat(false),
6735 mInputConverterProvider(NULL)
Andy Hung97a893e2015-03-29 01:03:07 -07006736{
6737 (void)updateParameters(srcChannelMask, srcFormat, srcSampleRate,
6738 dstChannelMask, dstFormat, dstSampleRate);
6739}
6740
6741AudioFlinger::RecordThread::RecordBufferConverter::~RecordBufferConverter() {
6742 free(mBuf);
6743 delete mResampler;
Andy Hungd330ee42015-04-20 13:23:41 -07006744 delete mInputConverterProvider;
Andy Hung97a893e2015-03-29 01:03:07 -07006745}
6746
6747size_t AudioFlinger::RecordThread::RecordBufferConverter::convert(void *dst,
6748 AudioBufferProvider *provider, size_t frames)
6749{
Andy Hungd330ee42015-04-20 13:23:41 -07006750 if (mInputConverterProvider != NULL) {
6751 mInputConverterProvider->setBufferProvider(provider);
6752 provider = mInputConverterProvider;
6753 }
6754
6755 if (mResampler == NULL) {
Andy Hung97a893e2015-03-29 01:03:07 -07006756 ALOGVV("NO RESAMPLING sampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6757 mSrcSampleRate, mSrcFormat, mDstFormat);
6758
6759 AudioBufferProvider::Buffer buffer;
6760 for (size_t i = frames; i > 0; ) {
6761 buffer.frameCount = i;
Glenn Kastend79072e2016-01-06 08:41:20 -08006762 status_t status = provider->getNextBuffer(&buffer);
Andy Hung97a893e2015-03-29 01:03:07 -07006763 if (status != OK || buffer.frameCount == 0) {
6764 frames -= i; // cannot fill request.
6765 break;
6766 }
Andy Hungd330ee42015-04-20 13:23:41 -07006767 // format convert to destination buffer
6768 convertNoResampler(dst, buffer.raw, buffer.frameCount);
Andy Hung97a893e2015-03-29 01:03:07 -07006769
6770 dst = (int8_t*)dst + buffer.frameCount * mDstFrameSize;
6771 i -= buffer.frameCount;
6772 provider->releaseBuffer(&buffer);
6773 }
6774 } else {
6775 ALOGVV("RESAMPLING mSrcSampleRate:%u mDstSampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6776 mSrcSampleRate, mDstSampleRate, mSrcFormat, mDstFormat);
6777
Andy Hungd330ee42015-04-20 13:23:41 -07006778 // reallocate buffer if needed
6779 if (mBufFrameSize != 0 && mBufFrames < frames) {
6780 free(mBuf);
6781 mBufFrames = frames;
6782 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6783 }
Andy Hung97a893e2015-03-29 01:03:07 -07006784 // resampler accumulates, but we only have one source track
Andy Hungd330ee42015-04-20 13:23:41 -07006785 memset(mBuf, 0, frames * mBufFrameSize);
6786 frames = mResampler->resample((int32_t*)mBuf, frames, provider);
6787 // format convert to destination buffer
6788 convertResampler(dst, mBuf, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006789 }
6790 return frames;
6791}
6792
6793status_t AudioFlinger::RecordThread::RecordBufferConverter::updateParameters(
6794 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6795 uint32_t srcSampleRate,
6796 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6797 uint32_t dstSampleRate)
6798{
6799 // quick evaluation if there is any change.
6800 if (mSrcFormat == srcFormat
6801 && mSrcChannelMask == srcChannelMask
6802 && mSrcSampleRate == srcSampleRate
6803 && mDstFormat == dstFormat
6804 && mDstChannelMask == dstChannelMask
6805 && mDstSampleRate == dstSampleRate) {
6806 return NO_ERROR;
6807 }
6808
Andy Hungdb4c0312015-05-06 08:46:52 -07006809 ALOGV("RecordBufferConverter updateParameters srcMask:%#x dstMask:%#x"
6810 " srcFormat:%#x dstFormat:%#x srcRate:%u dstRate:%u",
6811 srcChannelMask, dstChannelMask, srcFormat, dstFormat, srcSampleRate, dstSampleRate);
Andy Hung97a893e2015-03-29 01:03:07 -07006812 const bool valid =
6813 audio_is_input_channel(srcChannelMask)
6814 && audio_is_input_channel(dstChannelMask)
6815 && audio_is_valid_format(srcFormat) && audio_is_linear_pcm(srcFormat)
6816 && audio_is_valid_format(dstFormat) && audio_is_linear_pcm(dstFormat)
6817 && (srcSampleRate <= dstSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX)
6818 ; // no upsampling checks for now
6819 if (!valid) {
6820 return BAD_VALUE;
6821 }
6822
6823 mSrcFormat = srcFormat;
6824 mSrcChannelMask = srcChannelMask;
6825 mSrcSampleRate = srcSampleRate;
6826 mDstFormat = dstFormat;
6827 mDstChannelMask = dstChannelMask;
6828 mDstSampleRate = dstSampleRate;
6829
6830 // compute derived parameters
6831 mSrcChannelCount = audio_channel_count_from_in_mask(srcChannelMask);
6832 mDstChannelCount = audio_channel_count_from_in_mask(dstChannelMask);
6833 mDstFrameSize = mDstChannelCount * audio_bytes_per_sample(mDstFormat);
6834
Andy Hungd330ee42015-04-20 13:23:41 -07006835 // do we need to resample?
6836 delete mResampler;
6837 mResampler = NULL;
6838 if (mSrcSampleRate != mDstSampleRate) {
6839 mResampler = AudioResampler::create(AUDIO_FORMAT_PCM_FLOAT,
6840 mSrcChannelCount, mDstSampleRate);
6841 mResampler->setSampleRate(mSrcSampleRate);
6842 mResampler->setVolume(AudioMixer::UNITY_GAIN_FLOAT, AudioMixer::UNITY_GAIN_FLOAT);
6843 }
6844
6845 // are we running legacy channel conversion modes?
6846 mIsLegacyDownmix = (mSrcChannelMask == AUDIO_CHANNEL_IN_STEREO
6847 || mSrcChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK)
6848 && mDstChannelMask == AUDIO_CHANNEL_IN_MONO;
6849 mIsLegacyUpmix = mSrcChannelMask == AUDIO_CHANNEL_IN_MONO
6850 && (mDstChannelMask == AUDIO_CHANNEL_IN_STEREO
6851 || mDstChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK);
6852
6853 // do we need to process in float?
6854 mRequiresFloat = mResampler != NULL || mIsLegacyDownmix || mIsLegacyUpmix;
6855
6856 // do we need a staging buffer to convert for destination (we can still optimize this)?
6857 // we use mBufFrameSize > 0 to indicate both frame size as well as buffer necessity
6858 if (mResampler != NULL) {
6859 mBufFrameSize = max(mSrcChannelCount, FCC_2)
6860 * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
Andy Hunga97630b2015-07-22 23:27:24 -07006861 } else if (mIsLegacyUpmix || mIsLegacyDownmix) { // legacy modes always float
Andy Hungd330ee42015-04-20 13:23:41 -07006862 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
6863 } else if (mSrcChannelMask != mDstChannelMask && mDstFormat != mSrcFormat) {
Andy Hung97a893e2015-03-29 01:03:07 -07006864 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(mSrcFormat);
6865 } else {
6866 mBufFrameSize = 0;
6867 }
6868 mBufFrames = 0; // force the buffer to be resized.
6869
Andy Hungd330ee42015-04-20 13:23:41 -07006870 // do we need an input converter buffer provider to give us float?
6871 delete mInputConverterProvider;
6872 mInputConverterProvider = NULL;
6873 if (mRequiresFloat && mSrcFormat != AUDIO_FORMAT_PCM_FLOAT) {
6874 mInputConverterProvider = new ReformatBufferProvider(
6875 audio_channel_count_from_in_mask(mSrcChannelMask),
6876 mSrcFormat,
6877 AUDIO_FORMAT_PCM_FLOAT,
6878 256 /* provider buffer frame count */);
6879 }
6880
6881 // do we need a remixer to do channel mask conversion
6882 if (!mIsLegacyDownmix && !mIsLegacyUpmix && mSrcChannelMask != mDstChannelMask) {
6883 (void) memcpy_by_index_array_initialization_from_channel_mask(
6884 mIdxAry, ARRAY_SIZE(mIdxAry), mDstChannelMask, mSrcChannelMask);
Andy Hung97a893e2015-03-29 01:03:07 -07006885 }
6886 return NO_ERROR;
6887}
6888
Andy Hungd330ee42015-04-20 13:23:41 -07006889void AudioFlinger::RecordThread::RecordBufferConverter::convertNoResampler(
6890 void *dst, const void *src, size_t frames)
Andy Hung97a893e2015-03-29 01:03:07 -07006891{
Andy Hungd330ee42015-04-20 13:23:41 -07006892 // src is native type unless there is legacy upmix or downmix, whereupon it is float.
Andy Hung97a893e2015-03-29 01:03:07 -07006893 if (mBufFrameSize != 0 && mBufFrames < frames) {
6894 free(mBuf);
6895 mBufFrames = frames;
6896 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6897 }
Andy Hungd330ee42015-04-20 13:23:41 -07006898 // do we need to do legacy upmix and downmix?
6899 if (mIsLegacyUpmix || mIsLegacyDownmix) {
Andy Hung97a893e2015-03-29 01:03:07 -07006900 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07006901 if (mIsLegacyUpmix) {
6902 upmix_to_stereo_float_from_mono_float((float *)dstBuf,
6903 (const float *)src, frames);
6904 } else /*mIsLegacyDownmix */ {
6905 downmix_to_mono_float_from_stereo_float((float *)dstBuf,
6906 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006907 }
Andy Hungd330ee42015-04-20 13:23:41 -07006908 if (mBuf != NULL) {
6909 memcpy_by_audio_format(dst, mDstFormat, mBuf, AUDIO_FORMAT_PCM_FLOAT,
6910 frames * mDstChannelCount);
6911 }
6912 return;
6913 }
6914 // do we need to do channel mask conversion?
6915 if (mSrcChannelMask != mDstChannelMask) {
Andy Hung97a893e2015-03-29 01:03:07 -07006916 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07006917 memcpy_by_index_array(dstBuf, mDstChannelCount,
6918 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mSrcFormat), frames);
6919 if (dstBuf == dst) {
6920 return; // format is the same
6921 }
6922 }
6923 // convert to destination buffer
6924 const void *convertBuf = mBuf != NULL ? mBuf : src;
6925 memcpy_by_audio_format(dst, mDstFormat, convertBuf, mSrcFormat,
6926 frames * mDstChannelCount);
6927}
6928
6929void AudioFlinger::RecordThread::RecordBufferConverter::convertResampler(
6930 void *dst, /*not-a-const*/ void *src, size_t frames)
6931{
6932 // src buffer format is ALWAYS float when entering this routine
6933 if (mIsLegacyUpmix) {
6934 ; // mono to stereo already handled by resampler
6935 } else if (mIsLegacyDownmix
6936 || (mSrcChannelMask == mDstChannelMask && mSrcChannelCount == 1)) {
6937 // the resampler outputs stereo for mono input channel (a feature?)
6938 // must convert to mono
6939 downmix_to_mono_float_from_stereo_float((float *)src,
6940 (const float *)src, frames);
6941 } else if (mSrcChannelMask != mDstChannelMask) {
6942 // convert to mono channel again for channel mask conversion (could be skipped
6943 // with further optimization).
Andy Hung97a893e2015-03-29 01:03:07 -07006944 if (mSrcChannelCount == 1) {
Andy Hungd330ee42015-04-20 13:23:41 -07006945 downmix_to_mono_float_from_stereo_float((float *)src,
6946 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006947 }
Andy Hungd330ee42015-04-20 13:23:41 -07006948 // convert to destination format (in place, OK as float is larger than other types)
6949 if (mDstFormat != AUDIO_FORMAT_PCM_FLOAT) {
6950 memcpy_by_audio_format(src, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
6951 frames * mSrcChannelCount);
6952 }
6953 // channel convert and save to dst
6954 memcpy_by_index_array(dst, mDstChannelCount,
6955 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mDstFormat), frames);
6956 return;
Andy Hung97a893e2015-03-29 01:03:07 -07006957 }
Andy Hungd330ee42015-04-20 13:23:41 -07006958 // convert to destination format and save to dst
6959 memcpy_by_audio_format(dst, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
6960 frames * mDstChannelCount);
Andy Hung97a893e2015-03-29 01:03:07 -07006961}
6962
Eric Laurent10351942014-05-08 18:49:52 -07006963bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
6964 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006965{
6966 bool reconfig = false;
6967
Eric Laurent10351942014-05-08 18:49:52 -07006968 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006969
Eric Laurent10351942014-05-08 18:49:52 -07006970 audio_format_t reqFormat = mFormat;
6971 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07006972 // 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 -07006973 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
6974
6975 AudioParameter param = AudioParameter(keyValuePair);
6976 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07006977
6978 // scope for AutoPark extends to end of method
6979 AutoPark<FastCapture> park(mFastCapture);
6980
Eric Laurent10351942014-05-08 18:49:52 -07006981 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
6982 // channel count change can be requested. Do we mandate the first client defines the
6983 // HAL sampling rate and channel count or do we allow changes on the fly?
6984 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6985 samplingRate = value;
6986 reconfig = true;
6987 }
6988 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07006989 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07006990 status = BAD_VALUE;
6991 } else {
6992 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08006993 reconfig = true;
6994 }
Eric Laurent10351942014-05-08 18:49:52 -07006995 }
6996 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
6997 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07006998 if (!audio_is_input_channel(mask) ||
6999 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007000 status = BAD_VALUE;
7001 } else {
7002 channelMask = mask;
7003 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007004 }
Eric Laurent10351942014-05-08 18:49:52 -07007005 }
7006 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7007 // do not accept frame count changes if tracks are open as the track buffer
7008 // size depends on frame count and correct behavior would not be guaranteed
7009 // if frame count is changed after track creation
7010 if (mActiveTracks.size() > 0) {
7011 status = INVALID_OPERATION;
7012 } else {
7013 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007014 }
Eric Laurent10351942014-05-08 18:49:52 -07007015 }
7016 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7017 // forward device change to effects that have requested to be
7018 // aware of attached audio device.
7019 for (size_t i = 0; i < mEffectChains.size(); i++) {
7020 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08007021 }
Eric Laurent81784c32012-11-19 14:55:58 -08007022
Eric Laurent10351942014-05-08 18:49:52 -07007023 // store input device and output device but do not forward output device to audio HAL.
7024 // Note that status is ignored by the caller for output device
7025 // (see AudioFlinger::setParameters()
7026 if (audio_is_output_devices(value)) {
7027 mOutDevice = value;
7028 status = BAD_VALUE;
7029 } else {
7030 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07007031 if (value != AUDIO_DEVICE_NONE) {
7032 mPrevInDevice = value;
7033 }
Eric Laurent10351942014-05-08 18:49:52 -07007034 // disable AEC and NS if the device is a BT SCO headset supporting those
7035 // pre processings
7036 if (mTracks.size() > 0) {
7037 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7038 mAudioFlinger->btNrecIsOff();
7039 for (size_t i = 0; i < mTracks.size(); i++) {
7040 sp<RecordTrack> track = mTracks[i];
7041 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7042 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08007043 }
7044 }
7045 }
Eric Laurent10351942014-05-08 18:49:52 -07007046 }
7047 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
7048 mAudioSource != (audio_source_t)value) {
7049 // forward device change to effects that have requested to be
7050 // aware of attached audio device.
7051 for (size_t i = 0; i < mEffectChains.size(); i++) {
7052 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08007053 }
Eric Laurent10351942014-05-08 18:49:52 -07007054 mAudioSource = (audio_source_t)value;
7055 }
Glenn Kastene198c362013-08-13 09:13:36 -07007056
Eric Laurent10351942014-05-08 18:49:52 -07007057 if (status == NO_ERROR) {
7058 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7059 keyValuePair.string());
7060 if (status == INVALID_OPERATION) {
7061 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08007062 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7063 keyValuePair.string());
Eric Laurent10351942014-05-08 18:49:52 -07007064 }
7065 if (reconfig) {
7066 if (status == BAD_VALUE &&
Andy Hung97a893e2015-03-29 01:03:07 -07007067 audio_is_linear_pcm(mInput->stream->common.get_format(&mInput->stream->common)) &&
7068 audio_is_linear_pcm(reqFormat) &&
Eric Laurent10351942014-05-08 18:49:52 -07007069 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
Andy Hung97a893e2015-03-29 01:03:07 -07007070 <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate)) &&
Andy Hunge5412692014-05-16 11:25:07 -07007071 audio_channel_count_from_in_mask(
Andy Hungd1abb8f2015-05-05 23:42:34 -07007072 mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007073 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007074 }
Eric Laurent10351942014-05-08 18:49:52 -07007075 if (status == NO_ERROR) {
7076 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007077 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08007078 }
7079 }
Eric Laurent81784c32012-11-19 14:55:58 -08007080 }
Eric Laurent10351942014-05-08 18:49:52 -07007081
Eric Laurent81784c32012-11-19 14:55:58 -08007082 return reconfig;
7083}
7084
7085String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
7086{
Eric Laurent81784c32012-11-19 14:55:58 -08007087 Mutex::Autolock _l(mLock);
7088 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07007089 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08007090 }
7091
Glenn Kastend8ea6992013-07-16 14:17:15 -07007092 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
7093 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08007094 free(s);
7095 return out_s8;
7096}
7097
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007098void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007099 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7100
7101 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08007102
7103 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007104 case AUDIO_INPUT_OPENED:
7105 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07007106 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07007107 desc->mChannelMask = mChannelMask;
7108 desc->mSamplingRate = mSampleRate;
7109 desc->mFormat = mFormat;
7110 desc->mFrameCount = mFrameCount;
7111 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007112 break;
7113
Eric Laurent73e26b62015-04-27 16:55:58 -07007114 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08007115 default:
7116 break;
7117 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007118 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08007119}
7120
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007121void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007122{
Eric Laurent81784c32012-11-19 14:55:58 -08007123 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
7124 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Andy Hunge5412692014-05-16 11:25:07 -07007125 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Andy Hungd330ee42015-04-20 13:23:41 -07007126 if (mChannelCount > FCC_8) {
7127 ALOGE("HAL channel count %d > %d", mChannelCount, FCC_8);
7128 }
Andy Hung463be252014-07-10 16:56:07 -07007129 mHALFormat = mInput->stream->common.get_format(&mInput->stream->common);
7130 mFormat = mHALFormat;
Andy Hungd330ee42015-04-20 13:23:41 -07007131 if (!audio_is_linear_pcm(mFormat)) {
7132 ALOGE("HAL format %#x is not linear pcm", mFormat);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07007133 }
Eric Laurent665470b2014-07-03 16:37:08 -07007134 mFrameSize = audio_stream_in_frame_size(mInput->stream);
Glenn Kasten548efc92012-11-29 08:48:51 -08007135 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
7136 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007137 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08007138 // 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 -07007139 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08007140 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007141 // A larger value should allow more old data to be read after a track calls start(),
7142 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07007143 //
7144 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08007145 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07007146 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07007147 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07007148 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007149
7150 // TODO optimize audio capture buffer sizes ...
7151 // Here we calculate the size of the sliding buffer used as a source
7152 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
7153 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
7154 // be better to have it derived from the pipe depth in the long term.
7155 // The current value is higher than necessary. However it should not add to latency.
7156
Glenn Kasten85948432013-08-19 12:09:05 -07007157 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Andy Hung0a01c2f2015-09-21 12:44:54 -07007158 size_t bufferSize = (mRsmpInFramesP2 + mFrameCount - 1) * mFrameSize;
7159 (void)posix_memalign(&mRsmpInBuffer, 32, bufferSize);
7160 memset(mRsmpInBuffer, 0, bufferSize); // if posix_memalign fails, will segv here.
Eric Laurent81784c32012-11-19 14:55:58 -08007161
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007162 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
7163 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08007164}
7165
Glenn Kasten5f972c02014-01-13 09:59:31 -08007166uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08007167{
7168 Mutex::Autolock _l(mLock);
7169 if (initCheck() != NO_ERROR) {
7170 return 0;
7171 }
7172
7173 return mInput->stream->get_input_frames_lost(mInput->stream);
7174}
7175
Glenn Kastend848eb42016-03-08 13:42:11 -08007176uint32_t AudioFlinger::RecordThread::hasAudioSession(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08007177{
7178 Mutex::Autolock _l(mLock);
7179 uint32_t result = 0;
7180 if (getEffectChain_l(sessionId) != 0) {
7181 result = EFFECT_SESSION;
7182 }
7183
7184 for (size_t i = 0; i < mTracks.size(); ++i) {
7185 if (sessionId == mTracks[i]->sessionId()) {
7186 result |= TRACK_SESSION;
7187 break;
7188 }
7189 }
7190
7191 return result;
7192}
7193
Glenn Kastend848eb42016-03-08 13:42:11 -08007194KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08007195{
Glenn Kastend848eb42016-03-08 13:42:11 -08007196 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08007197 Mutex::Autolock _l(mLock);
7198 for (size_t j = 0; j < mTracks.size(); ++j) {
7199 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08007200 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08007201 if (ids.indexOfKey(sessionId) < 0) {
7202 ids.add(sessionId, true);
7203 }
7204 }
7205 return ids;
7206}
7207
7208AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7209{
7210 Mutex::Autolock _l(mLock);
7211 AudioStreamIn *input = mInput;
7212 mInput = NULL;
7213 return input;
7214}
7215
7216// this method must always be called either with ThreadBase mLock held or inside the thread loop
7217audio_stream_t* AudioFlinger::RecordThread::stream() const
7218{
7219 if (mInput == NULL) {
7220 return NULL;
7221 }
7222 return &mInput->stream->common;
7223}
7224
7225status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7226{
7227 // only one chain per input thread
7228 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07007229 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08007230 return INVALID_OPERATION;
7231 }
7232 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07007233 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08007234 chain->setInBuffer(NULL);
7235 chain->setOutBuffer(NULL);
7236
7237 checkSuspendOnAddEffectChain_l(chain);
7238
Eric Laurent1b928682014-10-02 19:41:47 -07007239 // make sure enabled pre processing effects state is communicated to the HAL as we
7240 // just moved them to a new input stream.
7241 chain->syncHalEffectsState();
7242
Eric Laurent81784c32012-11-19 14:55:58 -08007243 mEffectChains.add(chain);
7244
7245 return NO_ERROR;
7246}
7247
7248size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7249{
7250 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7251 ALOGW_IF(mEffectChains.size() != 1,
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007252 "removeEffectChain_l() %p invalid chain size %zu on thread %p",
Eric Laurent81784c32012-11-19 14:55:58 -08007253 chain.get(), mEffectChains.size(), this);
7254 if (mEffectChains.size() == 1) {
7255 mEffectChains.removeAt(0);
7256 }
7257 return 0;
7258}
7259
Eric Laurent1c333e22014-05-20 10:48:17 -07007260status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7261 audio_patch_handle_t *handle)
7262{
7263 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007264
7265 // store new device and send to effects
7266 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07007267 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07007268 for (size_t i = 0; i < mEffectChains.size(); i++) {
7269 mEffectChains[i]->setDevice_l(mInDevice);
7270 }
7271
7272 // disable AEC and NS if the device is a BT SCO headset supporting those
7273 // pre processings
7274 if (mTracks.size() > 0) {
7275 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7276 mAudioFlinger->btNrecIsOff();
7277 for (size_t i = 0; i < mTracks.size(); i++) {
7278 sp<RecordTrack> track = mTracks[i];
7279 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7280 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
7281 }
7282 }
7283
7284 // store new source and send to effects
7285 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7286 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07007287 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07007288 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07007289 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007290 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007291
Eric Laurent054d9d32015-04-24 08:48:48 -07007292 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007293 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
7294 status = hwDevice->create_audio_patch(hwDevice,
7295 patch->num_sources,
7296 patch->sources,
7297 patch->num_sinks,
7298 patch->sinks,
7299 handle);
7300 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007301 char *address;
7302 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7303 address = audio_device_address_to_parameter(
7304 patch->sources[0].ext.device.type,
7305 patch->sources[0].ext.device.address);
7306 } else {
7307 address = (char *)calloc(1, 1);
7308 }
7309 AudioParameter param = AudioParameter(String8(address));
7310 free(address);
7311 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING),
7312 (int)patch->sources[0].ext.device.type);
7313 param.addInt(String8(AUDIO_PARAMETER_STREAM_INPUT_SOURCE),
7314 (int)patch->sinks[0].ext.mix.usecase.source);
7315 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7316 param.toString().string());
7317 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07007318 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007319
Eric Laurente8726fe2015-06-26 09:39:24 -07007320 if (mInDevice != mPrevInDevice) {
7321 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7322 mPrevInDevice = mInDevice;
7323 }
Eric Laurent296fb132015-05-01 11:38:42 -07007324
Eric Laurent1c333e22014-05-20 10:48:17 -07007325 return status;
7326}
7327
7328status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7329{
7330 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007331
7332 mInDevice = AUDIO_DEVICE_NONE;
7333
Eric Laurent1c333e22014-05-20 10:48:17 -07007334 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
7335 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
7336 status = hwDevice->release_audio_patch(hwDevice, handle);
7337 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007338 AudioParameter param;
7339 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
7340 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7341 param.toString().string());
Eric Laurent1c333e22014-05-20 10:48:17 -07007342 }
7343 return status;
7344}
7345
Eric Laurent83b88082014-06-20 18:31:16 -07007346void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
7347{
7348 Mutex::Autolock _l(mLock);
7349 mTracks.add(record);
7350}
7351
7352void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
7353{
7354 Mutex::Autolock _l(mLock);
7355 destroyTrack_l(record);
7356}
7357
7358void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
7359{
7360 ThreadBase::getAudioPortConfig(config);
7361 config->role = AUDIO_PORT_ROLE_SINK;
7362 config->ext.mix.hw_module = mInput->audioHwDev->handle();
7363 config->ext.mix.usecase.source = mAudioSource;
7364}
Eric Laurent1c333e22014-05-20 10:48:17 -07007365
Glenn Kasten63238ef2015-03-02 15:50:29 -08007366} // namespace android