blob: bc173398db5b585a61f090e444597c0ee3b8ebd4 [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 // either of these use cases:
1790 (
1791 // use case 1: shared buffer with any frame count
1792 (
1793 (sharedBuffer != 0)
1794 ) ||
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001795 // use case 2: frame count is default or at least as large as HAL
Eric Laurent81784c32012-11-19 14:55:58 -08001796 (
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001797 // we formerly checked for a callback handler (non-0 tid),
1798 // but that is no longer required for TRANSFER_OBTAIN mode
Eric Laurent81784c32012-11-19 14:55:58 -08001799 ((frameCount == 0) ||
Glenn Kastenb5fed682013-12-03 09:06:43 -08001800 (frameCount >= mFrameCount))
Eric Laurent81784c32012-11-19 14:55:58 -08001801 )
1802 ) &&
1803 // PCM data
1804 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001805 // TODO: extract as a data library function that checks that a computationally
1806 // expensive downmixer is not required: isFastOutputChannelConversion()
Andy Hung9a592762014-07-21 21:56:01 -07001807 (channelMask == mChannelMask ||
Andy Hung1f439e12015-05-19 12:57:41 -07001808 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1809 (channelMask == AUDIO_CHANNEL_OUT_MONO
1810 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001811 // hardware sample rate
1812 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001813 // normal mixer has an associated fast mixer
1814 hasFastMixer() &&
1815 // there are sufficient fast track slots available
1816 (mFastTrackAvailMask != 0)
1817 // FIXME test that MixerThread for this fast track has a capable output HAL
1818 // FIXME add a permission test also?
1819 ) {
1820 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1821 if (frameCount == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001822 // read the fast track multiplier property the first time it is needed
1823 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1824 if (ok != 0) {
1825 ALOGE("%s pthread_once failed: %d", __func__, ok);
1826 }
1827 frameCount = mFrameCount * sFastTrackMultiplier;
Eric Laurent81784c32012-11-19 14:55:58 -08001828 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001829 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08001830 frameCount, mFrameCount);
1831 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001832 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
1833 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07001834 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001835 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08001836 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001837 audio_is_linear_pcm(format),
1838 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1839 *flags &= ~IAudioFlinger::TRACK_FAST;
Andy Hung0e48d252015-01-26 11:43:15 -08001840 }
1841 }
1842 // For normal PCM streaming tracks, update minimum frame count.
1843 // For compatibility with AudioTrack calculation, buffer depth is forced
1844 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1845 // This is probably too conservative, but legacy application code may depend on it.
1846 // If you change this calculation, also review the start threshold which is related.
1847 if (!(*flags & IAudioFlinger::TRACK_FAST)
Phil Burkfdb3c072016-02-09 10:47:02 -08001848 && audio_has_proportional_frames(format) && sharedBuffer == 0) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001849 // this must match AudioTrack.cpp calculateMinFrameCount().
1850 // TODO: Move to a common library
Eric Laurent81784c32012-11-19 14:55:58 -08001851 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1852 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1853 if (minBufCount < 2) {
1854 minBufCount = 2;
1855 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07001856 // For normal mixing tracks, if speed is > 1.0f (normal), AudioTrack
1857 // or the client should compute and pass in a larger buffer request.
Andy Hung0e48d252015-01-26 11:43:15 -08001858 size_t minFrameCount =
Andy Hung8edb8dc2015-03-26 19:13:55 -07001859 minBufCount * sourceFramesNeededWithTimestretch(
1860 sampleRate, mNormalFrameCount,
1861 mSampleRate, AUDIO_TIMESTRETCH_SPEED_NORMAL /*speed*/);
Andy Hung0e48d252015-01-26 11:43:15 -08001862 if (frameCount < minFrameCount) { // including frameCount == 0
Eric Laurent81784c32012-11-19 14:55:58 -08001863 frameCount = minFrameCount;
1864 }
Eric Laurent81784c32012-11-19 14:55:58 -08001865 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001866 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001867
Glenn Kastenc3df8382014-03-13 15:05:25 -07001868 switch (mType) {
1869
1870 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08001871 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08001872 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001873 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1874 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001875 sampleRate, format, channelMask, mOutput, mFormat);
1876 lStatus = BAD_VALUE;
1877 goto Exit;
1878 }
1879 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001880 break;
1881
1882 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001883 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001884 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1885 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001886 sampleRate, format, channelMask, mOutput, mFormat);
1887 lStatus = BAD_VALUE;
1888 goto Exit;
1889 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001890 break;
1891
1892 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001893 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001894 ALOGE("createTrack_l() Bad parameter: format %#x \""
1895 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001896 format, mOutput, mFormat);
1897 lStatus = BAD_VALUE;
1898 goto Exit;
1899 }
Andy Hungcd044842014-08-07 11:04:34 -07001900 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08001901 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1902 lStatus = BAD_VALUE;
1903 goto Exit;
1904 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001905 break;
1906
Eric Laurent81784c32012-11-19 14:55:58 -08001907 }
1908
1909 lStatus = initCheck();
1910 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001911 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08001912 goto Exit;
1913 }
1914
1915 { // scope for mLock
1916 Mutex::Autolock _l(mLock);
1917
1918 // all tracks in same audio session must share the same routing strategy otherwise
1919 // conflicts will happen when tracks are moved from one output to another by audio policy
1920 // manager
1921 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1922 for (size_t i = 0; i < mTracks.size(); ++i) {
1923 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07001924 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001925 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1926 if (sessionId == t->sessionId() && strategy != actual) {
1927 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1928 strategy, actual);
1929 lStatus = BAD_VALUE;
1930 goto Exit;
1931 }
1932 }
1933 }
1934
Glenn Kastend79072e2016-01-06 08:41:20 -08001935 track = new Track(this, client, streamType, sampleRate, format,
1936 channelMask, frameCount, NULL, sharedBuffer,
1937 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT);
Glenn Kasten03003332013-08-06 15:40:54 -07001938
Glenn Kasten03003332013-08-06 15:40:54 -07001939 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1940 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08001941 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001942 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08001943 goto Exit;
1944 }
1945 mTracks.add(track);
1946
1947 sp<EffectChain> chain = getEffectChain_l(sessionId);
1948 if (chain != 0) {
1949 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1950 track->setMainBuffer(chain->inBuffer());
1951 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1952 chain->incTrackCnt();
1953 }
1954
1955 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1956 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1957 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1958 // so ask activity manager to do this on our behalf
1959 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1960 }
1961 }
1962
1963 lStatus = NO_ERROR;
1964
1965Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001966 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001967 return track;
1968}
1969
1970uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1971{
1972 return latency;
1973}
1974
1975uint32_t AudioFlinger::PlaybackThread::latency() const
1976{
1977 Mutex::Autolock _l(mLock);
1978 return latency_l();
1979}
1980uint32_t AudioFlinger::PlaybackThread::latency_l() const
1981{
1982 if (initCheck() == NO_ERROR) {
1983 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1984 } else {
1985 return 0;
1986 }
1987}
1988
1989void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1990{
1991 Mutex::Autolock _l(mLock);
1992 // Don't apply master volume in SW if our HAL can do it for us.
1993 if (mOutput && mOutput->audioHwDev &&
1994 mOutput->audioHwDev->canSetMasterVolume()) {
1995 mMasterVolume = 1.0;
1996 } else {
1997 mMasterVolume = value;
1998 }
1999}
2000
2001void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2002{
2003 Mutex::Autolock _l(mLock);
2004 // Don't apply master mute in SW if our HAL can do it for us.
2005 if (mOutput && mOutput->audioHwDev &&
2006 mOutput->audioHwDev->canSetMasterMute()) {
2007 mMasterMute = false;
2008 } else {
2009 mMasterMute = muted;
2010 }
2011}
2012
2013void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2014{
2015 Mutex::Autolock _l(mLock);
2016 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002017 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002018}
2019
2020void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2021{
2022 Mutex::Autolock _l(mLock);
2023 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002024 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002025}
2026
2027float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2028{
2029 Mutex::Autolock _l(mLock);
2030 return mStreamTypes[stream].volume;
2031}
2032
2033// addTrack_l() must be called with ThreadBase::mLock held
2034status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2035{
2036 status_t status = ALREADY_EXISTS;
2037
Eric Laurent81784c32012-11-19 14:55:58 -08002038 if (mActiveTracks.indexOf(track) < 0) {
2039 // the track is newly added, make sure it fills up all its
2040 // buffers before playing. This is to ensure the client will
2041 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002042 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002043 TrackBase::track_state state = track->mState;
2044 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002045 status = AudioSystem::startOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002046 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002047 mLock.lock();
2048 // abort track was stopped/paused while we released the lock
2049 if (state != track->mState) {
2050 if (status == NO_ERROR) {
2051 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002052 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002053 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002054 mLock.lock();
2055 }
2056 return INVALID_OPERATION;
2057 }
2058 // abort if start is rejected by audio policy manager
2059 if (status != NO_ERROR) {
2060 return PERMISSION_DENIED;
2061 }
2062#ifdef ADD_BATTERY_DATA
2063 // to track the speaker usage
2064 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2065#endif
2066 }
2067
Eric Laurent51716182016-02-29 18:00:56 -08002068 // set retry count for buffer fill
2069 if (track->isOffloaded()) {
2070 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2071 } else {
2072 track->mRetryCount = kMaxTrackStartupRetries;
2073 }
2074
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002075 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08002076 track->mResetDone = false;
2077 track->mPresentationCompleteFrames = 0;
2078 mActiveTracks.add(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002079 mWakeLockUids.add(track->uid());
2080 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07002081 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07002082 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2083 if (chain != 0) {
2084 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2085 track->sessionId());
2086 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002087 }
2088
2089 status = NO_ERROR;
2090 }
2091
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002092 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002093 return status;
2094}
2095
Eric Laurentbfb1b832013-01-07 09:53:42 -08002096bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002097{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002098 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002099 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002100 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2101 track->mState = TrackBase::STOPPED;
2102 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002103 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002104 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002105 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002106 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002107
2108 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002109}
2110
2111void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2112{
2113 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
2114 mTracks.remove(track);
2115 deleteTrackName_l(track->name());
2116 // redundant as track is about to be destroyed, for dumpsys only
2117 track->mName = -1;
2118 if (track->isFastTrack()) {
2119 int index = track->mFastIndex;
2120 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
2121 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2122 mFastTrackAvailMask |= 1 << index;
2123 // redundant as track is about to be destroyed, for dumpsys only
2124 track->mFastIndex = -1;
2125 }
2126 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2127 if (chain != 0) {
2128 chain->decTrackCnt();
2129 }
2130}
2131
Eric Laurentede6c3b2013-09-19 14:37:46 -07002132void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002133{
2134 // Thread could be blocked waiting for async
2135 // so signal it to handle state changes immediately
2136 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
2137 // be lost so we also flag to prevent it blocking on mWaitWorkCV
2138 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002139 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002140}
2141
Eric Laurent81784c32012-11-19 14:55:58 -08002142String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2143{
Eric Laurent81784c32012-11-19 14:55:58 -08002144 Mutex::Autolock _l(mLock);
2145 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07002146 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002147 }
2148
Glenn Kastend8ea6992013-07-16 14:17:15 -07002149 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
2150 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08002151 free(s);
2152 return out_s8;
2153}
2154
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002155void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002156 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2157 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002158
Eric Laurent73e26b62015-04-27 16:55:58 -07002159 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002160
2161 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002162 case AUDIO_OUTPUT_OPENED:
2163 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002164 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002165 desc->mChannelMask = mChannelMask;
2166 desc->mSamplingRate = mSampleRate;
2167 desc->mFormat = mFormat;
2168 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002169 // AudioFlinger::frameCount(audio_io_handle_t)
Eric Laurent73e26b62015-04-27 16:55:58 -07002170 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002171 break;
2172
Eric Laurent73e26b62015-04-27 16:55:58 -07002173 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002174 default:
2175 break;
2176 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002177 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002178}
2179
Eric Laurentbfb1b832013-01-07 09:53:42 -08002180void AudioFlinger::PlaybackThread::writeCallback()
2181{
2182 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002183 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002184}
2185
2186void AudioFlinger::PlaybackThread::drainCallback()
2187{
2188 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002189 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002190}
2191
Eric Laurent3b4529e2013-09-05 18:09:19 -07002192void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002193{
2194 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002195 // reject out of sequence requests
2196 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2197 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002198 mWaitWorkCV.signal();
2199 }
2200}
2201
Eric Laurent3b4529e2013-09-05 18:09:19 -07002202void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002203{
2204 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002205 // reject out of sequence requests
2206 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
2207 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002208 mWaitWorkCV.signal();
2209 }
2210}
2211
2212// static
2213int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
Glenn Kasten0f11b512014-01-31 16:18:54 -08002214 void *param __unused,
Eric Laurentbfb1b832013-01-07 09:53:42 -08002215 void *cookie)
2216{
2217 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
2218 ALOGV("asyncCallback() event %d", event);
2219 switch (event) {
2220 case STREAM_CBK_EVENT_WRITE_READY:
2221 me->writeCallback();
2222 break;
2223 case STREAM_CBK_EVENT_DRAIN_READY:
2224 me->drainCallback();
2225 break;
2226 default:
2227 ALOGW("asyncCallback() unknown event %d", event);
2228 break;
2229 }
2230 return 0;
2231}
2232
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002233void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002234{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002235 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002236 mSampleRate = mOutput->getSampleRate();
2237 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002238 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002239 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002240 }
Andy Hung9a592762014-07-21 21:56:01 -07002241 if ((mType == MIXER || mType == DUPLICATING)
2242 && !isValidPcmSinkChannelMask(mChannelMask)) {
2243 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2244 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002245 }
Andy Hunge5412692014-05-16 11:25:07 -07002246 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002247
2248 // Get actual HAL format.
Andy Hung463be252014-07-10 16:56:07 -07002249 mHALFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Phil Burkca5e6142015-07-14 09:42:29 -07002250 // Get format from the shim, which will be different than the HAL format
2251 // if playing compressed audio over HDMI passthrough.
2252 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002253 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002254 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002255 }
Andy Hung6146c082014-03-18 11:56:15 -07002256 if ((mType == MIXER || mType == DUPLICATING)
2257 && !isValidPcmSinkFormat(mFormat)) {
2258 LOG_FATAL("HAL format %#x not supported for mixed output",
2259 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002260 }
Phil Burk062e67a2015-02-11 13:40:50 -08002261 mFrameSize = mOutput->getFrameSize();
Glenn Kasten70949c42013-08-06 07:40:12 -07002262 mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
2263 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002264 if (mFrameCount & 15) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002265 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002266 mFrameCount);
2267 }
2268
Eric Laurentbfb1b832013-01-07 09:53:42 -08002269 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
2270 (mOutput->stream->set_callback != NULL)) {
2271 if (mOutput->stream->set_callback(mOutput->stream,
2272 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
2273 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002274 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002275 }
2276 }
2277
Eric Laurentd1f69b02014-12-15 14:33:13 -08002278 mHwSupportsPause = false;
2279 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
2280 if (mOutput->stream->pause != NULL) {
2281 if (mOutput->stream->resume != NULL) {
2282 mHwSupportsPause = true;
2283 } else {
2284 ALOGW("direct output implements pause but not resume");
2285 }
2286 } else if (mOutput->stream->resume != NULL) {
2287 ALOGW("direct output implements resume but not pause");
2288 }
2289 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002290 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2291 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2292 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002293
Andy Hungfbfc3952015-01-15 13:33:51 -08002294 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2295 // For best precision, we use float instead of the associated output
2296 // device format (typically PCM 16 bit).
2297
2298 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2299 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2300 mBufferSize = mFrameSize * mFrameCount;
2301
2302 // TODO: We currently use the associated output device channel mask and sample rate.
2303 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2304 // (if a valid mask) to avoid premature downmix.
2305 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2306 // instead of the output device sample rate to avoid loss of high frequency information.
2307 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2308 }
2309
Andy Hung09a50072014-02-27 14:30:47 -08002310 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002311 double multiplier = 1.0;
2312 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2313 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002314 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2315 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Eric Laurent81784c32012-11-19 14:55:58 -08002316 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2317 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2318 maxNormalFrameCount = maxNormalFrameCount & ~15;
2319 if (maxNormalFrameCount < minNormalFrameCount) {
2320 maxNormalFrameCount = minNormalFrameCount;
2321 }
2322 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2323 if (multiplier <= 1.0) {
2324 multiplier = 1.0;
2325 } else if (multiplier <= 2.0) {
2326 if (2 * mFrameCount <= maxNormalFrameCount) {
2327 multiplier = 2.0;
2328 } else {
2329 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2330 }
2331 } else {
2332 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
Andy Hung09a50072014-02-27 14:30:47 -08002333 // 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 -08002334 // track, but we sometimes have to do this to satisfy the maximum frame count
2335 // constraint)
2336 // FIXME this rounding up should not be done if no HAL SRC
2337 uint32_t truncMult = (uint32_t) multiplier;
2338 if ((truncMult & 1)) {
2339 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2340 ++truncMult;
2341 }
2342 }
2343 multiplier = (double) truncMult;
2344 }
2345 }
2346 mNormalFrameCount = multiplier * mFrameCount;
2347 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002348 if (mType == MIXER || mType == DUPLICATING) {
2349 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2350 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002351 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002352 mNormalFrameCount);
2353
Andy Hung08fb1742015-05-31 23:22:10 -07002354 // Check if we want to throttle the processing to no more than 2x normal rate
2355 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002356 mThreadThrottleTimeMs = 0;
2357 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002358 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2359
Andy Hung010a1a12014-03-13 13:57:33 -07002360 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2361 // Originally this was int16_t[] array, need to remove legacy implications.
2362 free(mSinkBuffer);
2363 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002364 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2365 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2366 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002367 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002368
Andy Hung69aed5f2014-02-25 17:24:40 -08002369 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2370 // drives the output.
2371 free(mMixerBuffer);
2372 mMixerBuffer = NULL;
2373 if (mMixerBufferEnabled) {
2374 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2375 mMixerBufferSize = mNormalFrameCount * mChannelCount
2376 * audio_bytes_per_sample(mMixerBufferFormat);
2377 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2378 }
Andy Hung98ef9782014-03-04 14:46:50 -08002379 free(mEffectBuffer);
2380 mEffectBuffer = NULL;
2381 if (mEffectBufferEnabled) {
2382 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2383 mEffectBufferSize = mNormalFrameCount * mChannelCount
2384 * audio_bytes_per_sample(mEffectBufferFormat);
2385 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2386 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002387
Eric Laurent81784c32012-11-19 14:55:58 -08002388 // force reconfiguration of effect chains and engines to take new buffer size and audio
2389 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002390 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002391 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2392 // matter.
2393 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2394 Vector< sp<EffectChain> > effectChains = mEffectChains;
2395 for (size_t i = 0; i < effectChains.size(); i ++) {
2396 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2397 }
2398}
2399
2400
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002401status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002402{
2403 if (halFrames == NULL || dspFrames == NULL) {
2404 return BAD_VALUE;
2405 }
2406 Mutex::Autolock _l(mLock);
2407 if (initCheck() != NO_ERROR) {
2408 return INVALID_OPERATION;
2409 }
Andy Hung818e7a32016-02-16 18:08:07 -08002410 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002411 *halFrames = framesWritten;
2412
2413 if (isSuspended()) {
2414 // return an estimation of rendered frames when the output is suspended
2415 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002416 *dspFrames = (uint32_t)
2417 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002418 return NO_ERROR;
2419 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002420 status_t status;
2421 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002422 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002423 *dspFrames = (size_t)frames;
2424 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002425 }
2426}
2427
Glenn Kastend848eb42016-03-08 13:42:11 -08002428uint32_t AudioFlinger::PlaybackThread::hasAudioSession(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08002429{
2430 Mutex::Autolock _l(mLock);
2431 uint32_t result = 0;
2432 if (getEffectChain_l(sessionId) != 0) {
2433 result = EFFECT_SESSION;
2434 }
2435
2436 for (size_t i = 0; i < mTracks.size(); ++i) {
2437 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002438 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002439 result |= TRACK_SESSION;
2440 break;
2441 }
2442 }
2443
2444 return result;
2445}
2446
Glenn Kastend848eb42016-03-08 13:42:11 -08002447uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08002448{
2449 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2450 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2451 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2452 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2453 }
2454 for (size_t i = 0; i < mTracks.size(); i++) {
2455 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002456 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002457 return AudioSystem::getStrategyForStream(track->streamType());
2458 }
2459 }
2460 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2461}
2462
2463
Phil Burk062e67a2015-02-11 13:40:50 -08002464AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002465{
2466 Mutex::Autolock _l(mLock);
2467 return mOutput;
2468}
2469
Phil Burk062e67a2015-02-11 13:40:50 -08002470AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002471{
2472 Mutex::Autolock _l(mLock);
2473 AudioStreamOut *output = mOutput;
2474 mOutput = NULL;
2475 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2476 // must push a NULL and wait for ack
2477 mOutputSink.clear();
2478 mPipeSink.clear();
2479 mNormalSink.clear();
2480 return output;
2481}
2482
2483// this method must always be called either with ThreadBase mLock held or inside the thread loop
2484audio_stream_t* AudioFlinger::PlaybackThread::stream() const
2485{
2486 if (mOutput == NULL) {
2487 return NULL;
2488 }
2489 return &mOutput->stream->common;
2490}
2491
2492uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2493{
2494 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2495}
2496
2497status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2498{
2499 if (!isValidSyncEvent(event)) {
2500 return BAD_VALUE;
2501 }
2502
2503 Mutex::Autolock _l(mLock);
2504
2505 for (size_t i = 0; i < mTracks.size(); ++i) {
2506 sp<Track> track = mTracks[i];
2507 if (event->triggerSession() == track->sessionId()) {
2508 (void) track->setSyncEvent(event);
2509 return NO_ERROR;
2510 }
2511 }
2512
2513 return NAME_NOT_FOUND;
2514}
2515
2516bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2517{
2518 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2519}
2520
2521void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2522 const Vector< sp<Track> >& tracksToRemove)
2523{
2524 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002525 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002526 for (size_t i = 0 ; i < count ; i++) {
2527 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002528 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002529 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002530 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002531#ifdef ADD_BATTERY_DATA
2532 // to track the speaker usage
2533 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2534#endif
2535 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002536 AudioSystem::releaseOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002537 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002538 }
Eric Laurent81784c32012-11-19 14:55:58 -08002539 }
2540 }
2541 }
Eric Laurent81784c32012-11-19 14:55:58 -08002542}
2543
2544void AudioFlinger::PlaybackThread::checkSilentMode_l()
2545{
2546 if (!mMasterMute) {
2547 char value[PROPERTY_VALUE_MAX];
2548 if (property_get("ro.audio.silent", value, "0") > 0) {
2549 char *endptr;
2550 unsigned long ul = strtoul(value, &endptr, 0);
2551 if (*endptr == '\0' && ul != 0) {
2552 ALOGD("Silence is golden");
2553 // The setprop command will not allow a property to be changed after
2554 // the first time it is set, so we don't have to worry about un-muting.
2555 setMasterMute_l(true);
2556 }
2557 }
2558 }
2559}
2560
2561// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002562ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002563{
2564 // FIXME rewrite to reduce number of system calls
2565 mLastWriteTime = systemTime();
2566 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002567 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002568 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002569
2570 // If an NBAIO sink is present, use it to write the normal mixer's submix
2571 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002572
Andy Hung010a1a12014-03-13 13:57:33 -07002573 const size_t count = mBytesRemaining / mFrameSize;
2574
Simon Wilson2d590962012-11-29 15:18:50 -08002575 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002576 // update the setpoint when AudioFlinger::mScreenState changes
2577 uint32_t screenState = AudioFlinger::mScreenState;
2578 if (screenState != mScreenState) {
2579 mScreenState = screenState;
2580 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2581 if (pipe != NULL) {
2582 pipe->setAvgFrames((mScreenState & 1) ?
2583 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2584 }
2585 }
Andy Hung010a1a12014-03-13 13:57:33 -07002586 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002587 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002588 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002589 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002590 } else {
2591 bytesWritten = framesWritten;
2592 }
2593 // otherwise use the HAL / AudioStreamOut directly
2594 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002595 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002596
Eric Laurentbfb1b832013-01-07 09:53:42 -08002597 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002598 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2599 mWriteAckSequence += 2;
2600 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002601 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002602 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002603 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002604 // FIXME We should have an implementation of timestamps for direct output threads.
2605 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002606 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurent51716182016-02-29 18:00:56 -08002607
Eric Laurentbfb1b832013-01-07 09:53:42 -08002608 if (mUseAsyncWrite &&
2609 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2610 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002611 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002612 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002613 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002614 }
Eric Laurent81784c32012-11-19 14:55:58 -08002615 }
2616
Eric Laurent81784c32012-11-19 14:55:58 -08002617 mNumWrites++;
2618 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002619 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002620 return bytesWritten;
2621}
2622
2623void AudioFlinger::PlaybackThread::threadLoop_drain()
2624{
2625 if (mOutput->stream->drain) {
2626 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2627 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002628 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2629 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002630 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002631 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002632 }
2633 mOutput->stream->drain(mOutput->stream,
2634 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2635 : AUDIO_DRAIN_ALL);
2636 }
2637}
2638
2639void AudioFlinger::PlaybackThread::threadLoop_exit()
2640{
Eric Laurent275e8e92014-11-30 15:14:47 -08002641 {
2642 Mutex::Autolock _l(mLock);
2643 for (size_t i = 0; i < mTracks.size(); i++) {
2644 sp<Track> track = mTracks[i];
2645 track->invalidate();
2646 }
2647 }
Eric Laurent81784c32012-11-19 14:55:58 -08002648}
2649
2650/*
2651The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002652 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002653 - mActiveSleepTimeUs from activeSleepTimeUs()
2654 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08002655 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
2656 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08002657 - maxPeriod from frame count and sample rate (MIXER only)
2658
2659The parameters that affect these derived values are:
2660 - frame count
2661 - frame size
2662 - sample rate
2663 - device type: A2DP or not
2664 - device latency
2665 - format: PCM or not
2666 - active sleep time
2667 - idle sleep time
2668*/
2669
2670void AudioFlinger::PlaybackThread::cacheParameters_l()
2671{
Andy Hung25c2dac2014-02-27 14:56:00 -08002672 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002673 mActiveSleepTimeUs = activeSleepTimeUs();
2674 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08002675
2676 // make sure standby delay is not too short when connected to an A2DP sink to avoid
2677 // truncating audio when going to standby.
2678 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
2679 if ((mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != 0) {
2680 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
2681 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
2682 }
2683 }
Eric Laurent81784c32012-11-19 14:55:58 -08002684}
2685
2686void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2687{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002688 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08002689 this, streamType, mTracks.size());
2690 Mutex::Autolock _l(mLock);
2691
2692 size_t size = mTracks.size();
2693 for (size_t i = 0; i < size; i++) {
2694 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07002695 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002696 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08002697 }
2698 }
2699}
2700
2701status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2702{
Glenn Kastend848eb42016-03-08 13:42:11 -08002703 audio_session_t session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002704 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2705 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002706 bool ownsBuffer = false;
2707
2708 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Glenn Kastend848eb42016-03-08 13:42:11 -08002709 if (session > AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002710 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002711 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002712 if (mType != DIRECT) {
2713 size_t numSamples = mNormalFrameCount * mChannelCount;
2714 buffer = new int16_t[numSamples];
2715 memset(buffer, 0, numSamples * sizeof(int16_t));
2716 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2717 ownsBuffer = true;
2718 }
2719
2720 // Attach all tracks with same session ID to this chain.
2721 for (size_t i = 0; i < mTracks.size(); ++i) {
2722 sp<Track> track = mTracks[i];
2723 if (session == track->sessionId()) {
2724 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2725 buffer);
2726 track->setMainBuffer(buffer);
2727 chain->incTrackCnt();
2728 }
2729 }
2730
2731 // indicate all active tracks in the chain
2732 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2733 sp<Track> track = mActiveTracks[i].promote();
2734 if (track == 0) {
2735 continue;
2736 }
2737 if (session == track->sessionId()) {
2738 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2739 chain->incActiveTrackCnt();
2740 }
2741 }
2742 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002743 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08002744 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002745 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2746 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002747 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Glenn Kastend848eb42016-03-08 13:42:11 -08002748 // chains list in order to be processed last as it contains output stage effects.
Eric Laurent81784c32012-11-19 14:55:58 -08002749 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2750 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08002751 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08002752 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08002753 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08002754 // Effect chain for other sessions are inserted at beginning of effect
2755 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08002756 // sessions is not important.
2757 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
2758 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX,
2759 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08002760 size_t size = mEffectChains.size();
2761 size_t i = 0;
2762 for (i = 0; i < size; i++) {
2763 if (mEffectChains[i]->sessionId() < session) {
2764 break;
2765 }
2766 }
2767 mEffectChains.insertAt(chain, i);
2768 checkSuspendOnAddEffectChain_l(chain);
2769
2770 return NO_ERROR;
2771}
2772
2773size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2774{
Glenn Kastend848eb42016-03-08 13:42:11 -08002775 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08002776
2777 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2778
2779 for (size_t i = 0; i < mEffectChains.size(); i++) {
2780 if (chain == mEffectChains[i]) {
2781 mEffectChains.removeAt(i);
2782 // detach all active tracks from the chain
2783 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2784 sp<Track> track = mActiveTracks[i].promote();
2785 if (track == 0) {
2786 continue;
2787 }
2788 if (session == track->sessionId()) {
2789 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2790 chain.get(), session);
2791 chain->decActiveTrackCnt();
2792 }
2793 }
2794
2795 // detach all tracks with same session ID from this chain
2796 for (size_t i = 0; i < mTracks.size(); ++i) {
2797 sp<Track> track = mTracks[i];
2798 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002799 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002800 chain->decTrackCnt();
2801 }
2802 }
2803 break;
2804 }
2805 }
2806 return mEffectChains.size();
2807}
2808
2809status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2810 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2811{
2812 Mutex::Autolock _l(mLock);
2813 return attachAuxEffect_l(track, EffectId);
2814}
2815
2816status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2817 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2818{
2819 status_t status = NO_ERROR;
2820
2821 if (EffectId == 0) {
2822 track->setAuxBuffer(0, NULL);
2823 } else {
2824 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2825 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2826 if (effect != 0) {
2827 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2828 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2829 } else {
2830 status = INVALID_OPERATION;
2831 }
2832 } else {
2833 status = BAD_VALUE;
2834 }
2835 }
2836 return status;
2837}
2838
2839void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2840{
2841 for (size_t i = 0; i < mTracks.size(); ++i) {
2842 sp<Track> track = mTracks[i];
2843 if (track->auxEffectId() == effectId) {
2844 attachAuxEffect_l(track, 0);
2845 }
2846 }
2847}
2848
2849bool AudioFlinger::PlaybackThread::threadLoop()
2850{
2851 Vector< sp<Track> > tracksToRemove;
2852
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002853 mStandbyTimeNs = systemTime();
Eric Laurent81784c32012-11-19 14:55:58 -08002854
2855 // MIXER
2856 nsecs_t lastWarning = 0;
2857
2858 // DUPLICATING
2859 // FIXME could this be made local to while loop?
2860 writeFrames = 0;
2861
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002862 int lastGeneration = 0;
2863
Eric Laurent81784c32012-11-19 14:55:58 -08002864 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002865 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002866
2867 if (mType == MIXER) {
2868 sleepTimeShift = 0;
2869 }
2870
2871 CpuStats cpuStats;
2872 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2873
2874 acquireWakeLock();
2875
Glenn Kasten9e58b552013-01-18 15:09:48 -08002876 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2877 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2878 // and then that string will be logged at the next convenient opportunity.
2879 const char *logString = NULL;
2880
Eric Laurent664539d2013-09-23 18:24:31 -07002881 checkSilentMode_l();
2882
Eric Laurent81784c32012-11-19 14:55:58 -08002883 while (!exitPending())
2884 {
2885 cpuStats.sample(myName);
2886
2887 Vector< sp<EffectChain> > effectChains;
2888
Eric Laurent81784c32012-11-19 14:55:58 -08002889 { // scope for mLock
2890
2891 Mutex::Autolock _l(mLock);
2892
Eric Laurent021cf962014-05-13 10:18:14 -07002893 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002894
Glenn Kasten9e58b552013-01-18 15:09:48 -08002895 if (logString != NULL) {
2896 mNBLogWriter->logTimestamp();
2897 mNBLogWriter->log(logString);
2898 logString = NULL;
2899 }
2900
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002901 // Gather the framesReleased counters for all active tracks,
Andy Hunge10393e2015-06-12 13:59:33 -07002902 // and associate with the sink frames written out. We need
2903 // this to convert the sink timestamp to the track timestamp.
2904 if (mNormalSink != 0) {
Andy Hungc54b1ff2016-02-23 14:07:07 -08002905 // Note: The DuplicatingThread may not have a mNormalSink.
Andy Hung818e7a32016-02-16 18:08:07 -08002906 // We always fetch the timestamp here because often the downstream
2907 // sink will block whie writing.
2908 ExtendedTimestamp timestamp; // use private copy to fetch
2909 (void) mNormalSink->getTimestamp(timestamp);
2910 // copy over kernel info
2911 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
2912 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
2913 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
2914 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hungc54b1ff2016-02-23 14:07:07 -08002915 }
2916 // mFramesWritten for non-offloaded tracks are contiguous
2917 // even after standby() is called. This is useful for the track frame
2918 // to sink frame mapping.
2919 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
2920 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
2921 const size_t size = mActiveTracks.size();
2922 for (size_t i = 0; i < size; ++i) {
2923 sp<Track> t = mActiveTracks[i].promote();
2924 if (t != 0 && !t->isFastTrack()) {
2925 t->updateTrackFrameInfo(
2926 t->mAudioTrackServerProxy->framesReleased(),
2927 mFramesWritten,
2928 mTimestamp);
Andy Hunge10393e2015-06-12 13:59:33 -07002929 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002930 }
2931
Eric Laurent81784c32012-11-19 14:55:58 -08002932 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002933 if (mSignalPending) {
2934 // A signal was raised while we were unlocked
2935 mSignalPending = false;
2936 } else if (waitingAsyncCallback_l()) {
2937 if (exitPending()) {
2938 break;
2939 }
Marco Nelissen078538c2015-05-12 09:17:57 -07002940 bool released = false;
2941 // The following works around a bug in the offload driver. Ideally we would release
2942 // the wake lock every time, but that causes the last offload buffer(s) to be
2943 // dropped while the device is on battery, so we need to hold a wake lock during
2944 // the drain phase.
2945 if (mBytesRemaining && !(mDrainSequence & 1)) {
2946 releaseWakeLock_l();
2947 released = true;
2948 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002949 mWakeLockUids.clear();
2950 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002951 ALOGV("wait async completion");
2952 mWaitWorkCV.wait(mLock);
2953 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07002954 if (released) {
2955 acquireWakeLock_l();
2956 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002957 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
2958 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002959
2960 continue;
2961 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002962 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002963 isSuspended()) {
2964 // put audio hardware into standby after short delay
2965 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002966
2967 threadLoop_standby();
2968
2969 mStandby = true;
2970 }
2971
2972 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2973 // we're about to wait, flush the binder command buffer
2974 IPCThreadState::self()->flushCommands();
2975
2976 clearOutputTracks();
2977
2978 if (exitPending()) {
2979 break;
2980 }
2981
2982 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002983 mWakeLockUids.clear();
2984 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002985 // wait until we have something to do...
2986 ALOGV("%s going to sleep", myName.string());
2987 mWaitWorkCV.wait(mLock);
2988 ALOGV("%s waking up", myName.string());
2989 acquireWakeLock_l();
2990
2991 mMixerStatus = MIXER_IDLE;
2992 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2993 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002994 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002995 checkSilentMode_l();
2996
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002997 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
2998 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002999 if (mType == MIXER) {
3000 sleepTimeShift = 0;
3001 }
3002
3003 continue;
3004 }
3005 }
Eric Laurent81784c32012-11-19 14:55:58 -08003006 // mMixerStatusIgnoringFastTracks is also updated internally
3007 mMixerStatus = prepareTracks_l(&tracksToRemove);
3008
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003009 // compare with previously applied list
3010 if (lastGeneration != mActiveTracksGeneration) {
3011 // update wakelock
3012 updateWakeLockUids_l(mWakeLockUids);
3013 lastGeneration = mActiveTracksGeneration;
3014 }
3015
Eric Laurent81784c32012-11-19 14:55:58 -08003016 // prevent any changes in effect chain list and in each effect chain
3017 // during mixing and effect process as the audio buffers could be deleted
3018 // or modified if an effect is created or deleted
3019 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003020 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003021
Eric Laurentbfb1b832013-01-07 09:53:42 -08003022 if (mBytesRemaining == 0) {
3023 mCurrentWriteLength = 0;
3024 if (mMixerStatus == MIXER_TRACKS_READY) {
3025 // threadLoop_mix() sets mCurrentWriteLength
3026 threadLoop_mix();
3027 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3028 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003029 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003030 // must be written to HAL
3031 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003032 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003033 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003034 }
3035 }
Andy Hung98ef9782014-03-04 14:46:50 -08003036 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003037 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003038 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3039 // or mSinkBuffer (if there are no effects).
3040 //
3041 // This is done pre-effects computation; if effects change to
3042 // support higher precision, this needs to move.
3043 //
3044 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003045 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003046 if (mMixerBufferValid) {
3047 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3048 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3049
Andy Hung2ddee192015-12-18 17:34:44 -08003050 // mono blend occurs for mixer threads only (not direct or offloaded)
3051 // and is handled here if we're going directly to the sink.
3052 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003053 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3054 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003055 }
3056
Andy Hung98ef9782014-03-04 14:46:50 -08003057 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
3058 mNormalFrameCount * mChannelCount);
3059 }
3060
Eric Laurentbfb1b832013-01-07 09:53:42 -08003061 mBytesRemaining = mCurrentWriteLength;
3062 if (isSuspended()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003063 mSleepTimeUs = suspendSleepTimeUs();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003064 // simulate write to HAL when suspended
Andy Hung25c2dac2014-02-27 14:56:00 -08003065 mBytesWritten += mSinkBufferSize;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003066 mFramesWritten += mSinkBufferSize / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003067 mBytesRemaining = 0;
3068 }
Eric Laurent81784c32012-11-19 14:55:58 -08003069
Eric Laurentbfb1b832013-01-07 09:53:42 -08003070 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003071 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003072 for (size_t i = 0; i < effectChains.size(); i ++) {
3073 effectChains[i]->process_l();
3074 }
Eric Laurent81784c32012-11-19 14:55:58 -08003075 }
3076 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003077 // Process effect chains for offloaded thread even if no audio
3078 // was read from audio track: process only updates effect state
3079 // and thus does have to be synchronized with audio writes but may have
3080 // to be called while waiting for async write callback
3081 if (mType == OFFLOAD) {
3082 for (size_t i = 0; i < effectChains.size(); i ++) {
3083 effectChains[i]->process_l();
3084 }
3085 }
Eric Laurent81784c32012-11-19 14:55:58 -08003086
Andy Hung98ef9782014-03-04 14:46:50 -08003087 // Only if the Effects buffer is enabled and there is data in the
3088 // Effects buffer (buffer valid), we need to
3089 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003090 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003091 if (mEffectBufferValid) {
3092 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003093
3094 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003095 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3096 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003097 }
3098
Andy Hung98ef9782014-03-04 14:46:50 -08003099 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
3100 mNormalFrameCount * mChannelCount);
3101 }
3102
Eric Laurent81784c32012-11-19 14:55:58 -08003103 // enable changes in effect chain
3104 unlockEffectChains(effectChains);
3105
Eric Laurentbfb1b832013-01-07 09:53:42 -08003106 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003107 // mSleepTimeUs == 0 means we must write to audio hardware
3108 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003109 ssize_t ret = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003110 if (mBytesRemaining) {
Andy Hung08fb1742015-05-31 23:22:10 -07003111 ret = threadLoop_write();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003112 if (ret < 0) {
3113 mBytesRemaining = 0;
3114 } else {
3115 mBytesWritten += ret;
3116 mBytesRemaining -= ret;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003117 mFramesWritten += ret / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003118 }
3119 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3120 (mMixerStatus == MIXER_DRAIN_ALL)) {
3121 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003122 }
Andy Hung08fb1742015-05-31 23:22:10 -07003123 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003124 // write blocked detection
3125 nsecs_t now = systemTime();
3126 nsecs_t delta = now - mLastWriteTime;
Andy Hung08fb1742015-05-31 23:22:10 -07003127 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003128 mNumDelayedWrites++;
3129 if ((now - lastWarning) > kWarningThrottleNs) {
3130 ATRACE_NAME("underrun");
3131 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003132 (unsigned long long) ns2ms(delta), mNumDelayedWrites, this);
Glenn Kasten4944acb2013-08-19 08:39:20 -07003133 lastWarning = now;
3134 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003135 }
Andy Hung08fb1742015-05-31 23:22:10 -07003136
3137 if (mThreadThrottle
3138 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
3139 && ret > 0) { // we wrote something
3140 // Limit MixerThread data processing to no more than twice the
3141 // expected processing rate.
3142 //
3143 // This helps prevent underruns with NuPlayer and other applications
3144 // which may set up buffers that are close to the minimum size, or use
3145 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3146 //
3147 // The throttle smooths out sudden large data drains from the device,
3148 // e.g. when it comes out of standby, which often causes problems with
3149 // (1) mixer threads without a fast mixer (which has its own warm-up)
3150 // (2) minimum buffer sized tracks (even if the track is full,
3151 // the app won't fill fast enough to handle the sudden draw).
3152
3153 const int32_t deltaMs = delta / 1000000;
3154 const int32_t throttleMs = mHalfBufferMs - deltaMs;
3155 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3156 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003157 // notify of throttle start on verbose log
3158 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3159 "mixer(%p) throttle begin:"
3160 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003161 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003162 mThreadThrottleTimeMs += throttleMs;
3163 } else {
3164 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3165 if (diff > 0) {
3166 // notify of throttle end on debug log
3167 ALOGD("mixer(%p) throttle end: throttle time(%u)", this, diff);
3168 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3169 }
Andy Hung08fb1742015-05-31 23:22:10 -07003170 }
3171 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003172 }
Eric Laurent81784c32012-11-19 14:55:58 -08003173
Eric Laurentbfb1b832013-01-07 09:53:42 -08003174 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003175 ATRACE_BEGIN("sleep");
Eric Laurent51716182016-02-29 18:00:56 -08003176 if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
3177 Mutex::Autolock _l(mLock);
3178 if (!mSignalPending && !exitPending()) {
3179 // Do not sleep more than one buffer duration since last write and not
3180 // less than kDirectMinSleepTimeUs
3181 // Wake up if a command is received
3182 nsecs_t now = systemTime();
3183 uint32_t deltaUs = (uint32_t)((now - mLastWriteTime) / 1000);
3184 uint32_t timeoutUs = mSleepTimeUs;
3185 if (timeoutUs + deltaUs > mBufferDurationUs) {
3186 if (mBufferDurationUs > deltaUs) {
3187 timeoutUs = mBufferDurationUs - deltaUs;
3188 if (timeoutUs < kDirectMinSleepTimeUs) {
3189 timeoutUs = kDirectMinSleepTimeUs;
3190 }
3191 } else {
3192 timeoutUs = kDirectMinSleepTimeUs;
3193 }
3194 }
3195 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)timeoutUs));
3196 }
3197 } else {
3198 usleep(mSleepTimeUs);
3199 }
Glenn Kastene7754022014-10-31 12:11:26 -07003200 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003201 }
Eric Laurent81784c32012-11-19 14:55:58 -08003202 }
3203
3204 // Finally let go of removed track(s), without the lock held
3205 // since we can't guarantee the destructors won't acquire that
3206 // same lock. This will also mutate and push a new fast mixer state.
3207 threadLoop_removeTracks(tracksToRemove);
3208 tracksToRemove.clear();
3209
3210 // FIXME I don't understand the need for this here;
3211 // it was in the original code but maybe the
3212 // assignment in saveOutputTracks() makes this unnecessary?
3213 clearOutputTracks();
3214
3215 // Effect chains will be actually deleted here if they were removed from
3216 // mEffectChains list during mixing or effects processing
3217 effectChains.clear();
3218
3219 // FIXME Note that the above .clear() is no longer necessary since effectChains
3220 // is now local to this block, but will keep it for now (at least until merge done).
3221 }
3222
Eric Laurentbfb1b832013-01-07 09:53:42 -08003223 threadLoop_exit();
3224
Eric Laurentcf817a22014-08-04 20:36:31 -07003225 if (!mStandby) {
3226 threadLoop_standby();
3227 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003228 }
3229
3230 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003231 mWakeLockUids.clear();
3232 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08003233
3234 ALOGV("Thread %p type %d exiting", this, mType);
3235 return false;
3236}
3237
Eric Laurentbfb1b832013-01-07 09:53:42 -08003238// removeTracks_l() must be called with ThreadBase::mLock held
3239void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3240{
3241 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003242 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003243 for (size_t i=0 ; i<count ; i++) {
3244 const sp<Track>& track = tracksToRemove.itemAt(i);
3245 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003246 mWakeLockUids.remove(track->uid());
3247 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003248 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3249 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3250 if (chain != 0) {
3251 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3252 track->sessionId());
3253 chain->decActiveTrackCnt();
3254 }
3255 if (track->isTerminated()) {
3256 removeTrack_l(track);
3257 }
3258 }
3259 }
3260
3261}
Eric Laurent81784c32012-11-19 14:55:58 -08003262
Eric Laurentaccc1472013-09-20 09:36:34 -07003263status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3264{
3265 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08003266 ExtendedTimestamp ets;
3267 status_t status = mNormalSink->getTimestamp(ets);
3268 if (status == NO_ERROR) {
3269 status = ets.getBestTimestamp(&timestamp);
3270 }
3271 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07003272 }
Andy Hung9a1c8892014-12-03 11:37:42 -08003273 if ((mType == OFFLOAD || mType == DIRECT)
3274 && mOutput != NULL && mOutput->stream->get_presentation_position) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003275 uint64_t position64;
Phil Burk062e67a2015-02-11 13:40:50 -08003276 int ret = mOutput->getPresentationPosition(&position64, &timestamp.mTime);
Eric Laurentaccc1472013-09-20 09:36:34 -07003277 if (ret == 0) {
3278 timestamp.mPosition = (uint32_t)position64;
3279 return NO_ERROR;
3280 }
3281 }
3282 return INVALID_OPERATION;
3283}
Eric Laurent1c333e22014-05-20 10:48:17 -07003284
Eric Laurent054d9d32015-04-24 08:48:48 -07003285status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3286 audio_patch_handle_t *handle)
3287{
Glenn Kastenc05b8d72016-03-24 09:48:17 -07003288 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent054d9d32015-04-24 08:48:48 -07003289
Glenn Kastenc05b8d72016-03-24 09:48:17 -07003290 status_t status = PlaybackThread::createAudioPatch_l(patch, handle);
Eric Laurent054d9d32015-04-24 08:48:48 -07003291
3292 return status;
3293}
3294
Eric Laurent1c333e22014-05-20 10:48:17 -07003295status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3296 audio_patch_handle_t *handle)
3297{
3298 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003299
3300 // store new device and send to effects
3301 audio_devices_t type = AUDIO_DEVICE_NONE;
3302 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3303 type |= patch->sinks[i].ext.device.type;
3304 }
3305
3306#ifdef ADD_BATTERY_DATA
3307 // when changing the audio output device, call addBatteryData to notify
3308 // the change
3309 if (mOutDevice != type) {
3310 uint32_t params = 0;
3311 // check whether speaker is on
3312 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3313 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003314 }
3315
Eric Laurent054d9d32015-04-24 08:48:48 -07003316 audio_devices_t deviceWithoutSpeaker
3317 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3318 // check if any other device (except speaker) is on
3319 if (type & deviceWithoutSpeaker) {
3320 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3321 }
3322
3323 if (params != 0) {
3324 addBatteryData(params);
3325 }
3326 }
3327#endif
3328
3329 for (size_t i = 0; i < mEffectChains.size(); i++) {
3330 mEffectChains[i]->setDevice_l(type);
3331 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003332
3333 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3334 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3335 bool configChanged = mPrevOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003336 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003337 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003338
3339 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003340 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3341 status = hwDevice->create_audio_patch(hwDevice,
3342 patch->num_sources,
3343 patch->sources,
3344 patch->num_sinks,
3345 patch->sinks,
3346 handle);
3347 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003348 char *address;
3349 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3350 //FIXME: we only support address on first sink with HAL version < 3.0
3351 address = audio_device_address_to_parameter(
3352 patch->sinks[0].ext.device.type,
3353 patch->sinks[0].ext.device.address);
3354 } else {
3355 address = (char *)calloc(1, 1);
3356 }
3357 AudioParameter param = AudioParameter(String8(address));
3358 free(address);
3359 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), (int)type);
3360 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3361 param.toString().string());
3362 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003363 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003364 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003365 mPrevOutDevice = type;
Eric Laurente8726fe2015-06-26 09:39:24 -07003366 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3367 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003368 return status;
3369}
3370
Eric Laurent054d9d32015-04-24 08:48:48 -07003371status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3372{
Glenn Kastenc05b8d72016-03-24 09:48:17 -07003373 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent054d9d32015-04-24 08:48:48 -07003374
3375 status_t status = PlaybackThread::releaseAudioPatch_l(handle);
3376
Eric Laurent054d9d32015-04-24 08:48:48 -07003377 return status;
3378}
3379
Eric Laurent1c333e22014-05-20 10:48:17 -07003380status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3381{
3382 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003383
3384 mOutDevice = AUDIO_DEVICE_NONE;
3385
Eric Laurent1c333e22014-05-20 10:48:17 -07003386 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
3387 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3388 status = hwDevice->release_audio_patch(hwDevice, handle);
3389 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003390 AudioParameter param;
3391 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
3392 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3393 param.toString().string());
Eric Laurent1c333e22014-05-20 10:48:17 -07003394 }
3395 return status;
3396}
3397
Eric Laurent83b88082014-06-20 18:31:16 -07003398void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3399{
3400 Mutex::Autolock _l(mLock);
3401 mTracks.add(track);
3402}
3403
3404void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3405{
3406 Mutex::Autolock _l(mLock);
3407 destroyTrack_l(track);
3408}
3409
3410void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3411{
3412 ThreadBase::getAudioPortConfig(config);
3413 config->role = AUDIO_PORT_ROLE_SOURCE;
3414 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3415 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3416}
3417
Eric Laurent81784c32012-11-19 14:55:58 -08003418// ----------------------------------------------------------------------------
3419
3420AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003421 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3422 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003423 // mAudioMixer below
3424 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08003425 mFastMixerFutex(0),
3426 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08003427 // mOutputSink below
3428 // mPipeSink below
3429 // mNormalSink below
3430{
3431 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003432 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%zu, "
3433 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003434 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3435 mNormalFrameCount);
3436 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3437
Andy Hungfbfc3952015-01-15 13:33:51 -08003438 if (type == DUPLICATING) {
3439 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3440 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3441 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3442 return;
3443 }
Eric Laurent81784c32012-11-19 14:55:58 -08003444 // create an NBAIO sink for the HAL output stream, and negotiate
3445 mOutputSink = new AudioStreamOutSink(output->stream);
3446 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003447 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003448#if !LOG_NDEBUG
3449 ssize_t index =
3450#else
3451 (void)
3452#endif
3453 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003454 ALOG_ASSERT(index == 0);
3455
3456 // initialize fast mixer depending on configuration
3457 bool initFastMixer;
3458 switch (kUseFastMixer) {
3459 case FastMixer_Never:
3460 initFastMixer = false;
3461 break;
3462 case FastMixer_Always:
3463 initFastMixer = true;
3464 break;
3465 case FastMixer_Static:
3466 case FastMixer_Dynamic:
3467 initFastMixer = mFrameCount < mNormalFrameCount;
3468 break;
3469 }
3470 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003471 audio_format_t fastMixerFormat;
3472 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3473 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3474 } else {
3475 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3476 }
3477 if (mFormat != fastMixerFormat) {
3478 // change our Sink format to accept our intermediate precision
3479 mFormat = fastMixerFormat;
3480 free(mSinkBuffer);
3481 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3482 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3483 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3484 }
Eric Laurent81784c32012-11-19 14:55:58 -08003485
3486 // create a MonoPipe to connect our submix to FastMixer
3487 NBAIO_Format format = mOutputSink->format();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003488#ifdef TEE_SINK
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003489 NBAIO_Format origformat = format;
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003490#endif
Andy Hung1258c1a2014-05-23 21:22:17 -07003491 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07003492 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003493 format.mFormat = fastMixerFormat;
3494 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3495
Eric Laurent81784c32012-11-19 14:55:58 -08003496 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3497 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3498 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3499 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3500 const NBAIO_Format offers[1] = {format};
3501 size_t numCounterOffers = 0;
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003502#if !LOG_NDEBUG
3503 ssize_t index =
3504#else
3505 (void)
3506#endif
3507 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003508 ALOG_ASSERT(index == 0);
3509 monoPipe->setAvgFrames((mScreenState & 1) ?
3510 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3511 mPipeSink = monoPipe;
3512
Glenn Kasten46909e72013-02-26 09:20:22 -08003513#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003514 if (mTeeSinkOutputEnabled) {
3515 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003516 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3517 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003518 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003519 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003520 ALOG_ASSERT(index == 0);
3521 mTeeSink = teeSink;
3522 PipeReader *teeSource = new PipeReader(*teeSink);
3523 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003524 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003525 ALOG_ASSERT(index == 0);
3526 mTeeSource = teeSource;
3527 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003528#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003529
3530 // create fast mixer and configure it initially with just one fast track for our submix
3531 mFastMixer = new FastMixer();
3532 FastMixerStateQueue *sq = mFastMixer->sq();
3533#ifdef STATE_QUEUE_DUMP
3534 sq->setObserverDump(&mStateQueueObserverDump);
3535 sq->setMutatorDump(&mStateQueueMutatorDump);
3536#endif
3537 FastMixerState *state = sq->begin();
3538 FastTrack *fastTrack = &state->mFastTracks[0];
3539 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3540 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3541 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003542 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3543 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003544 fastTrack->mGeneration++;
3545 state->mFastTracksGen++;
3546 state->mTrackMask = 1;
3547 // fast mixer will use the HAL output sink
3548 state->mOutputSink = mOutputSink.get();
3549 state->mOutputSinkGen++;
3550 state->mFrameCount = mFrameCount;
3551 state->mCommand = FastMixerState::COLD_IDLE;
3552 // already done in constructor initialization list
3553 //mFastMixerFutex = 0;
3554 state->mColdFutexAddr = &mFastMixerFutex;
3555 state->mColdGen++;
3556 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003557#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003558 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003559#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003560 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3561 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003562 sq->end();
3563 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3564
3565 // start the fast mixer
3566 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3567 pid_t tid = mFastMixer->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003568 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003569
3570#ifdef AUDIO_WATCHDOG
3571 // create and start the watchdog
3572 mAudioWatchdog = new AudioWatchdog();
3573 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3574 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3575 tid = mAudioWatchdog->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003576 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003577#endif
3578
Eric Laurent81784c32012-11-19 14:55:58 -08003579 }
3580
3581 switch (kUseFastMixer) {
3582 case FastMixer_Never:
3583 case FastMixer_Dynamic:
3584 mNormalSink = mOutputSink;
3585 break;
3586 case FastMixer_Always:
3587 mNormalSink = mPipeSink;
3588 break;
3589 case FastMixer_Static:
3590 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3591 break;
3592 }
3593}
3594
3595AudioFlinger::MixerThread::~MixerThread()
3596{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003597 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003598 FastMixerStateQueue *sq = mFastMixer->sq();
3599 FastMixerState *state = sq->begin();
3600 if (state->mCommand == FastMixerState::COLD_IDLE) {
3601 int32_t old = android_atomic_inc(&mFastMixerFutex);
3602 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003603 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003604 }
3605 }
3606 state->mCommand = FastMixerState::EXIT;
3607 sq->end();
3608 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3609 mFastMixer->join();
3610 // Though the fast mixer thread has exited, it's state queue is still valid.
3611 // We'll use that extract the final state which contains one remaining fast track
3612 // corresponding to our sub-mix.
3613 state = sq->begin();
3614 ALOG_ASSERT(state->mTrackMask == 1);
3615 FastTrack *fastTrack = &state->mFastTracks[0];
3616 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3617 delete fastTrack->mBufferProvider;
3618 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003619 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003620#ifdef AUDIO_WATCHDOG
3621 if (mAudioWatchdog != 0) {
3622 mAudioWatchdog->requestExit();
3623 mAudioWatchdog->requestExitAndWait();
3624 mAudioWatchdog.clear();
3625 }
3626#endif
3627 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003628 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003629 delete mAudioMixer;
3630}
3631
3632
3633uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3634{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003635 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003636 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3637 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3638 }
3639 return latency;
3640}
3641
3642
3643void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3644{
3645 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3646}
3647
Eric Laurentbfb1b832013-01-07 09:53:42 -08003648ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003649{
3650 // FIXME we should only do one push per cycle; confirm this is true
3651 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003652 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003653 FastMixerStateQueue *sq = mFastMixer->sq();
3654 FastMixerState *state = sq->begin();
3655 if (state->mCommand != FastMixerState::MIX_WRITE &&
3656 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3657 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07003658
3659 // FIXME workaround for first HAL write being CPU bound on some devices
3660 ATRACE_BEGIN("write");
3661 mOutput->write((char *)mSinkBuffer, 0);
3662 ATRACE_END();
3663
Eric Laurent81784c32012-11-19 14:55:58 -08003664 int32_t old = android_atomic_inc(&mFastMixerFutex);
3665 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003666 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003667 }
3668#ifdef AUDIO_WATCHDOG
3669 if (mAudioWatchdog != 0) {
3670 mAudioWatchdog->resume();
3671 }
3672#endif
3673 }
3674 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003675#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003676 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003677 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003678#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003679 sq->end();
3680 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3681 if (kUseFastMixer == FastMixer_Dynamic) {
3682 mNormalSink = mPipeSink;
3683 }
3684 } else {
3685 sq->end(false /*didModify*/);
3686 }
3687 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003688 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003689}
3690
3691void AudioFlinger::MixerThread::threadLoop_standby()
3692{
3693 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003694 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003695 FastMixerStateQueue *sq = mFastMixer->sq();
3696 FastMixerState *state = sq->begin();
3697 if (!(state->mCommand & FastMixerState::IDLE)) {
3698 state->mCommand = FastMixerState::COLD_IDLE;
3699 state->mColdFutexAddr = &mFastMixerFutex;
3700 state->mColdGen++;
3701 mFastMixerFutex = 0;
3702 sq->end();
3703 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3704 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3705 if (kUseFastMixer == FastMixer_Dynamic) {
3706 mNormalSink = mOutputSink;
3707 }
3708#ifdef AUDIO_WATCHDOG
3709 if (mAudioWatchdog != 0) {
3710 mAudioWatchdog->pause();
3711 }
3712#endif
3713 } else {
3714 sq->end(false /*didModify*/);
3715 }
3716 }
3717 PlaybackThread::threadLoop_standby();
3718}
3719
Eric Laurentbfb1b832013-01-07 09:53:42 -08003720bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3721{
3722 return false;
3723}
3724
3725bool AudioFlinger::PlaybackThread::shouldStandby_l()
3726{
3727 return !mStandby;
3728}
3729
3730bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3731{
3732 Mutex::Autolock _l(mLock);
3733 return waitingAsyncCallback_l();
3734}
3735
Eric Laurent81784c32012-11-19 14:55:58 -08003736// shared by MIXER and DIRECT, overridden by DUPLICATING
3737void AudioFlinger::PlaybackThread::threadLoop_standby()
3738{
3739 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08003740 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003741 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003742 // discard any pending drain or write ack by incrementing sequence
3743 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3744 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003745 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003746 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3747 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003748 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003749 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003750}
3751
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003752void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3753{
3754 ALOGV("signal playback thread");
3755 broadcast_l();
3756}
3757
Eric Laurent81784c32012-11-19 14:55:58 -08003758void AudioFlinger::MixerThread::threadLoop_mix()
3759{
Eric Laurent81784c32012-11-19 14:55:58 -08003760 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08003761 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08003762 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003763 // increase sleep time progressively when application underrun condition clears.
3764 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3765 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3766 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003767 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003768 sleepTimeShift--;
3769 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003770 mSleepTimeUs = 0;
3771 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08003772 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003773
Eric Laurent81784c32012-11-19 14:55:58 -08003774}
3775
3776void AudioFlinger::MixerThread::threadLoop_sleepTime()
3777{
3778 // If no tracks are ready, sleep once for the duration of an output
3779 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003780 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003781 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003782 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
3783 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
3784 mSleepTimeUs = kMinThreadSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003785 }
3786 // reduce sleep time in case of consecutive application underruns to avoid
3787 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3788 // duration we would end up writing less data than needed by the audio HAL if
3789 // the condition persists.
3790 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3791 sleepTimeShift++;
3792 }
3793 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003794 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003795 }
3796 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003797 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3798 // before effects processing or output.
3799 if (mMixerBufferValid) {
3800 memset(mMixerBuffer, 0, mMixerBufferSize);
3801 } else {
3802 memset(mSinkBuffer, 0, mSinkBufferSize);
3803 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003804 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003805 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3806 "anticipated start");
3807 }
3808 // TODO add standby time extension fct of effect tail
3809}
3810
3811// prepareTracks_l() must be called with ThreadBase::mLock held
3812AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3813 Vector< sp<Track> > *tracksToRemove)
3814{
3815
3816 mixer_state mixerStatus = MIXER_IDLE;
3817 // find out which tracks need to be processed
3818 size_t count = mActiveTracks.size();
3819 size_t mixedTracks = 0;
3820 size_t tracksWithEffect = 0;
3821 // counts only _active_ fast tracks
3822 size_t fastTracks = 0;
3823 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3824
3825 float masterVolume = mMasterVolume;
3826 bool masterMute = mMasterMute;
3827
3828 if (masterMute) {
3829 masterVolume = 0;
3830 }
3831 // Delegate master volume control to effect in output mix effect chain if needed
3832 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3833 if (chain != 0) {
3834 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3835 chain->setVolume_l(&v, &v);
3836 masterVolume = (float)((v + (1 << 23)) >> 24);
3837 chain.clear();
3838 }
3839
3840 // prepare a new state to push
3841 FastMixerStateQueue *sq = NULL;
3842 FastMixerState *state = NULL;
3843 bool didModify = false;
3844 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003845 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003846 sq = mFastMixer->sq();
3847 state = sq->begin();
3848 }
3849
Andy Hung69aed5f2014-02-25 17:24:40 -08003850 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003851 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003852
Eric Laurent81784c32012-11-19 14:55:58 -08003853 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003854 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003855 if (t == 0) {
3856 continue;
3857 }
3858
3859 // this const just means the local variable doesn't change
3860 Track* const track = t.get();
3861
3862 // process fast tracks
3863 if (track->isFastTrack()) {
3864
3865 // It's theoretically possible (though unlikely) for a fast track to be created
3866 // and then removed within the same normal mix cycle. This is not a problem, as
3867 // the track never becomes active so it's fast mixer slot is never touched.
3868 // The converse, of removing an (active) track and then creating a new track
3869 // at the identical fast mixer slot within the same normal mix cycle,
3870 // is impossible because the slot isn't marked available until the end of each cycle.
3871 int j = track->mFastIndex;
3872 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
3873 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3874 FastTrack *fastTrack = &state->mFastTracks[j];
3875
3876 // Determine whether the track is currently in underrun condition,
3877 // and whether it had a recent underrun.
3878 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3879 FastTrackUnderruns underruns = ftDump->mUnderruns;
3880 uint32_t recentFull = (underruns.mBitFields.mFull -
3881 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3882 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3883 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3884 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3885 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3886 uint32_t recentUnderruns = recentPartial + recentEmpty;
3887 track->mObservedUnderruns = underruns;
3888 // don't count underruns that occur while stopping or pausing
3889 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07003890 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3891 recentUnderruns > 0) {
3892 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3893 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Phil Burk2812d9e2016-01-04 10:34:30 -08003894 } else {
3895 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Eric Laurent81784c32012-11-19 14:55:58 -08003896 }
3897
3898 // This is similar to the state machine for normal tracks,
3899 // with a few modifications for fast tracks.
3900 bool isActive = true;
3901 switch (track->mState) {
3902 case TrackBase::STOPPING_1:
3903 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08003904 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003905 track->mState = TrackBase::STOPPING_2;
3906 }
3907 break;
3908 case TrackBase::PAUSING:
3909 // ramp down is not yet implemented
3910 track->setPaused();
3911 break;
3912 case TrackBase::RESUMING:
3913 // ramp up is not yet implemented
3914 track->mState = TrackBase::ACTIVE;
3915 break;
3916 case TrackBase::ACTIVE:
3917 if (recentFull > 0 || recentPartial > 0) {
3918 // track has provided at least some frames recently: reset retry count
3919 track->mRetryCount = kMaxTrackRetries;
3920 }
3921 if (recentUnderruns == 0) {
3922 // no recent underruns: stay active
3923 break;
3924 }
3925 // there has recently been an underrun of some kind
3926 if (track->sharedBuffer() == 0) {
3927 // were any of the recent underruns "empty" (no frames available)?
3928 if (recentEmpty == 0) {
3929 // no, then ignore the partial underruns as they are allowed indefinitely
3930 break;
3931 }
3932 // there has recently been an "empty" underrun: decrement the retry counter
3933 if (--(track->mRetryCount) > 0) {
3934 break;
3935 }
3936 // indicate to client process that the track was disabled because of underrun;
3937 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08003938 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08003939 // remove from active list, but state remains ACTIVE [confusing but true]
3940 isActive = false;
3941 break;
3942 }
3943 // fall through
3944 case TrackBase::STOPPING_2:
3945 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003946 case TrackBase::STOPPED:
3947 case TrackBase::FLUSHED: // flush() while active
3948 // Check for presentation complete if track is inactive
3949 // We have consumed all the buffers of this track.
3950 // This would be incomplete if we auto-paused on underrun
3951 {
3952 size_t audioHALFrames =
3953 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08003954 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003955 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
3956 // track stays in active list until presentation is complete
3957 break;
3958 }
3959 }
3960 if (track->isStopping_2()) {
3961 track->mState = TrackBase::STOPPED;
3962 }
3963 if (track->isStopped()) {
3964 // Can't reset directly, as fast mixer is still polling this track
3965 // track->reset();
3966 // So instead mark this track as needing to be reset after push with ack
3967 resetMask |= 1 << i;
3968 }
3969 isActive = false;
3970 break;
3971 case TrackBase::IDLE:
3972 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08003973 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08003974 }
3975
3976 if (isActive) {
3977 // was it previously inactive?
3978 if (!(state->mTrackMask & (1 << j))) {
3979 ExtendedAudioBufferProvider *eabp = track;
3980 VolumeProvider *vp = track;
3981 fastTrack->mBufferProvider = eabp;
3982 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08003983 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003984 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08003985 fastTrack->mGeneration++;
3986 state->mTrackMask |= 1 << j;
3987 didModify = true;
3988 // no acknowledgement required for newly active tracks
3989 }
3990 // cache the combined master volume and stream type volume for fast mixer; this
3991 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08003992 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08003993 ++fastTracks;
3994 } else {
3995 // was it previously active?
3996 if (state->mTrackMask & (1 << j)) {
3997 fastTrack->mBufferProvider = NULL;
3998 fastTrack->mGeneration++;
3999 state->mTrackMask &= ~(1 << j);
4000 didModify = true;
4001 // If any fast tracks were removed, we must wait for acknowledgement
4002 // because we're about to decrement the last sp<> on those tracks.
4003 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4004 } else {
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08004005 LOG_ALWAYS_FATAL("fast track %d should have been active; "
4006 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
4007 j, track->mState, state->mTrackMask, recentUnderruns,
4008 track->sharedBuffer() != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004009 }
4010 tracksToRemove->add(track);
4011 // Avoids a misleading display in dumpsys
4012 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
4013 }
4014 continue;
4015 }
4016
4017 { // local variable scope to avoid goto warning
4018
4019 audio_track_cblk_t* cblk = track->cblk();
4020
4021 // The first time a track is added we wait
4022 // for all its buffers to be filled before processing it
4023 int name = track->name();
4024 // make sure that we have enough frames to mix one full buffer.
4025 // enforce this condition only once to enable draining the buffer in case the client
4026 // app does not call stop() and relies on underrun to stop:
4027 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
4028 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004029 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07004030 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004031 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004032
4033 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004034 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004035 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
4036 // add frames already consumed but not yet released by the resampler
4037 // because mAudioTrackServerProxy->framesReady() will include these frames
4038 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
4039
Eric Laurent81784c32012-11-19 14:55:58 -08004040 uint32_t minFrames = 1;
4041 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
4042 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004043 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08004044 }
Eric Laurent13e4c962013-12-20 17:36:01 -08004045
4046 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07004047 if (ATRACE_ENABLED()) {
4048 // I wish we had formatted trace names
4049 char traceName[16];
4050 strcpy(traceName, "nRdy");
4051 int name = track->name();
4052 if (AudioMixer::TRACK0 <= name &&
4053 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
4054 name -= AudioMixer::TRACK0;
4055 traceName[4] = (name / 10) + '0';
4056 traceName[5] = (name % 10) + '0';
4057 } else {
4058 traceName[4] = '?';
4059 traceName[5] = '?';
4060 }
4061 traceName[6] = '\0';
4062 ATRACE_INT(traceName, framesReady);
4063 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004064 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08004065 !track->isPaused() && !track->isTerminated())
4066 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004067 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004068
4069 mixedTracks++;
4070
Andy Hung69aed5f2014-02-25 17:24:40 -08004071 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
4072 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08004073 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08004074 if (track->mainBuffer() != mSinkBuffer &&
4075 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004076 if (mEffectBufferEnabled) {
4077 mEffectBufferValid = true; // Later can set directly.
4078 }
Eric Laurent81784c32012-11-19 14:55:58 -08004079 chain = getEffectChain_l(track->sessionId());
4080 // Delegate volume control to effect in track effect chain if needed
4081 if (chain != 0) {
4082 tracksWithEffect++;
4083 } else {
4084 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
4085 "session %d",
4086 name, track->sessionId());
4087 }
4088 }
4089
4090
4091 int param = AudioMixer::VOLUME;
4092 if (track->mFillingUpStatus == Track::FS_FILLED) {
4093 // no ramp for the first volume setting
4094 track->mFillingUpStatus = Track::FS_ACTIVE;
4095 if (track->mState == TrackBase::RESUMING) {
4096 track->mState = TrackBase::ACTIVE;
4097 param = AudioMixer::RAMP_VOLUME;
4098 }
4099 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004100 // FIXME should not make a decision based on mServer
4101 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004102 // If the track is stopped before the first frame was mixed,
4103 // do not apply ramp
4104 param = AudioMixer::RAMP_VOLUME;
4105 }
4106
4107 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07004108 uint32_t vl, vr; // in U8.24 integer format
4109 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08004110 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07004111 vl = vr = 0;
4112 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08004113 if (track->isPausing()) {
4114 track->setPaused();
4115 }
4116 } else {
4117
4118 // read original volumes with volume control
4119 float typeVolume = mStreamTypes[track->streamType()].volume;
4120 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004121 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004122 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07004123 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
4124 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08004125 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07004126 if (vlf > GAIN_FLOAT_UNITY) {
4127 ALOGV("Track left volume out of range: %.3g", vlf);
4128 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004129 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07004130 if (vrf > GAIN_FLOAT_UNITY) {
4131 ALOGV("Track right volume out of range: %.3g", vrf);
4132 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004133 }
4134 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07004135 vlf *= v;
4136 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08004137 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07004138 // then derive vl and vr as U8.24 versions for the effect chain
4139 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
4140 vl = (uint32_t) (scaleto8_24 * vlf);
4141 vr = (uint32_t) (scaleto8_24 * vrf);
4142 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08004143 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08004144 // send level comes from shared memory and so may be corrupt
4145 if (sendLevel > MAX_GAIN_INT) {
4146 ALOGV("Track send level out of range: %04X", sendLevel);
4147 sendLevel = MAX_GAIN_INT;
4148 }
Andy Hung6be49402014-05-30 10:42:03 -07004149 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4150 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08004151 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004152
Eric Laurent81784c32012-11-19 14:55:58 -08004153 // Delegate volume control to effect in track effect chain if needed
4154 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4155 // Do not ramp volume if volume is controlled by effect
4156 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08004157 // Update remaining floating point volume levels
4158 vlf = (float)vl / (1 << 24);
4159 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004160 track->mHasVolumeController = true;
4161 } else {
4162 // force no volume ramp when volume controller was just disabled or removed
4163 // from effect chain to avoid volume spike
4164 if (track->mHasVolumeController) {
4165 param = AudioMixer::VOLUME;
4166 }
4167 track->mHasVolumeController = false;
4168 }
4169
Eric Laurent81784c32012-11-19 14:55:58 -08004170 // XXX: these things DON'T need to be done each time
4171 mAudioMixer->setBufferProvider(name, track);
4172 mAudioMixer->enable(name);
4173
Andy Hung6be49402014-05-30 10:42:03 -07004174 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
4175 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
4176 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004177 mAudioMixer->setParameter(
4178 name,
4179 AudioMixer::TRACK,
4180 AudioMixer::FORMAT, (void *)track->format());
4181 mAudioMixer->setParameter(
4182 name,
4183 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004184 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004185 mAudioMixer->setParameter(
4186 name,
4187 AudioMixer::TRACK,
4188 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004189 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004190 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004191 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004192 if (reqSampleRate == 0) {
4193 reqSampleRate = mSampleRate;
4194 } else if (reqSampleRate > maxSampleRate) {
4195 reqSampleRate = maxSampleRate;
4196 }
Eric Laurent81784c32012-11-19 14:55:58 -08004197 mAudioMixer->setParameter(
4198 name,
4199 AudioMixer::RESAMPLE,
4200 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004201 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004202
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004203 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004204 mAudioMixer->setParameter(
4205 name,
4206 AudioMixer::TIMESTRETCH,
4207 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004208 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004209
Andy Hung69aed5f2014-02-25 17:24:40 -08004210 /*
4211 * Select the appropriate output buffer for the track.
4212 *
Andy Hung98ef9782014-03-04 14:46:50 -08004213 * Tracks with effects go into their own effects chain buffer
4214 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004215 *
4216 * Other tracks can use mMixerBuffer for higher precision
4217 * channel accumulation. If this buffer is enabled
4218 * (mMixerBufferEnabled true), then selected tracks will accumulate
4219 * into it.
4220 *
4221 */
4222 if (mMixerBufferEnabled
4223 && (track->mainBuffer() == mSinkBuffer
4224 || track->mainBuffer() == mMixerBuffer)) {
4225 mAudioMixer->setParameter(
4226 name,
4227 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004228 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004229 mAudioMixer->setParameter(
4230 name,
4231 AudioMixer::TRACK,
4232 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4233 // TODO: override track->mainBuffer()?
4234 mMixerBufferValid = true;
4235 } else {
4236 mAudioMixer->setParameter(
4237 name,
4238 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004239 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004240 mAudioMixer->setParameter(
4241 name,
4242 AudioMixer::TRACK,
4243 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4244 }
Eric Laurent81784c32012-11-19 14:55:58 -08004245 mAudioMixer->setParameter(
4246 name,
4247 AudioMixer::TRACK,
4248 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4249
4250 // reset retry count
4251 track->mRetryCount = kMaxTrackRetries;
4252
4253 // If one track is ready, set the mixer ready if:
4254 // - the mixer was not ready during previous round OR
4255 // - no other track is not ready
4256 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4257 mixerStatus != MIXER_TRACKS_ENABLED) {
4258 mixerStatus = MIXER_TRACKS_READY;
4259 }
4260 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004261 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hung08fb1742015-05-31 23:22:10 -07004262 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)",
4263 track, framesReady, desiredFrames);
Glenn Kasten82aaf942013-07-17 16:05:07 -07004264 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08004265 } else {
4266 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004267 }
Phil Burk2812d9e2016-01-04 10:34:30 -08004268
Eric Laurent81784c32012-11-19 14:55:58 -08004269 // clear effect chain input buffer if an active track underruns to avoid sending
4270 // previous audio buffer again to effects
4271 chain = getEffectChain_l(track->sessionId());
4272 if (chain != 0) {
4273 chain->clearInputBuffer();
4274 }
4275
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004276 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004277 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4278 track->isStopped() || track->isPaused()) {
4279 // We have consumed all the buffers of this track.
4280 // Remove it from the list of active tracks.
4281 // TODO: use actual buffer filling status instead of latency when available from
4282 // audio HAL
4283 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004284 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004285 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4286 if (track->isStopped()) {
4287 track->reset();
4288 }
4289 tracksToRemove->add(track);
4290 }
4291 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004292 // No buffers for this track. Give it a few chances to
4293 // fill a buffer, then remove it from active list.
4294 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004295 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004296 tracksToRemove->add(track);
4297 // indicate to client process that the track was disabled because of underrun;
4298 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004299 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004300 // If one track is not ready, mark the mixer also not ready if:
4301 // - the mixer was ready during previous round OR
4302 // - no other track is ready
4303 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4304 mixerStatus != MIXER_TRACKS_READY) {
4305 mixerStatus = MIXER_TRACKS_ENABLED;
4306 }
4307 }
4308 mAudioMixer->disable(name);
4309 }
4310
4311 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08004312
4313 }
4314
4315 // Push the new FastMixer state if necessary
4316 bool pauseAudioWatchdog = false;
4317 if (didModify) {
4318 state->mFastTracksGen++;
4319 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4320 if (kUseFastMixer == FastMixer_Dynamic &&
4321 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4322 state->mCommand = FastMixerState::COLD_IDLE;
4323 state->mColdFutexAddr = &mFastMixerFutex;
4324 state->mColdGen++;
4325 mFastMixerFutex = 0;
4326 if (kUseFastMixer == FastMixer_Dynamic) {
4327 mNormalSink = mOutputSink;
4328 }
4329 // If we go into cold idle, need to wait for acknowledgement
4330 // so that fast mixer stops doing I/O.
4331 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4332 pauseAudioWatchdog = true;
4333 }
Eric Laurent81784c32012-11-19 14:55:58 -08004334 }
4335 if (sq != NULL) {
4336 sq->end(didModify);
4337 sq->push(block);
4338 }
4339#ifdef AUDIO_WATCHDOG
4340 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4341 mAudioWatchdog->pause();
4342 }
4343#endif
4344
4345 // Now perform the deferred reset on fast tracks that have stopped
4346 while (resetMask != 0) {
4347 size_t i = __builtin_ctz(resetMask);
4348 ALOG_ASSERT(i < count);
4349 resetMask &= ~(1 << i);
4350 sp<Track> t = mActiveTracks[i].promote();
4351 if (t == 0) {
4352 continue;
4353 }
4354 Track* track = t.get();
4355 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4356 track->reset();
4357 }
4358
4359 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004360 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004361
Eric Laurent97d547d2014-09-02 14:45:53 -07004362 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4363 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004364 }
4365
4366 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004367 // as long as there are effects we should clear the effects buffer, to avoid
4368 // passing a non-clean buffer to the effect chain
4369 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004370 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004371 // sink or mix buffer must be cleared if all tracks are connected to an
4372 // effect chain as in this case the mixer will not write to the sink or mix buffer
4373 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004374 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4375 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004376 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004377 if (mMixerBufferValid) {
4378 memset(mMixerBuffer, 0, mMixerBufferSize);
4379 // TODO: In testing, mSinkBuffer below need not be cleared because
4380 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4381 // after mixing.
4382 //
4383 // To enforce this guarantee:
4384 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4385 // (mixedTracks == 0 && fastTracks > 0))
4386 // must imply MIXER_TRACKS_READY.
4387 // Later, we may clear buffers regardless, and skip much of this logic.
4388 }
Andy Hung98ef9782014-03-04 14:46:50 -08004389 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004390 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004391 }
4392
4393 // if any fast tracks, then status is ready
4394 mMixerStatusIgnoringFastTracks = mixerStatus;
4395 if (fastTracks > 0) {
4396 mixerStatus = MIXER_TRACKS_READY;
4397 }
4398 return mixerStatus;
4399}
4400
4401// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07004402int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
Glenn Kastend848eb42016-03-08 13:42:11 -08004403 audio_format_t format, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08004404{
Andy Hunge8a1ced2014-05-09 15:02:21 -07004405 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08004406}
4407
4408// deleteTrackName_l() must be called with ThreadBase::mLock held
4409void AudioFlinger::MixerThread::deleteTrackName_l(int name)
4410{
4411 ALOGV("remove track (%d) and delete from mixer", name);
4412 mAudioMixer->deleteTrackName(name);
4413}
4414
Eric Laurent10351942014-05-08 18:49:52 -07004415// checkForNewParameter_l() must be called with ThreadBase::mLock held
4416bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4417 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004418{
Eric Laurent81784c32012-11-19 14:55:58 -08004419 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08004420 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004421
Eric Laurent10351942014-05-08 18:49:52 -07004422 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004423
Glenn Kastenc05b8d72016-03-24 09:48:17 -07004424 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004425
Eric Laurent10351942014-05-08 18:49:52 -07004426 AudioParameter param = AudioParameter(keyValuePair);
4427 int value;
4428 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4429 reconfig = true;
4430 }
4431 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004432 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004433 status = BAD_VALUE;
4434 } else {
4435 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004436 reconfig = true;
4437 }
Eric Laurent10351942014-05-08 18:49:52 -07004438 }
4439 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004440 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004441 status = BAD_VALUE;
4442 } else {
4443 // no need to save value, since it's constant
4444 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004445 }
Eric Laurent10351942014-05-08 18:49:52 -07004446 }
4447 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4448 // do not accept frame count changes if tracks are open as the track buffer
4449 // size depends on frame count and correct behavior would not be guaranteed
4450 // if frame count is changed after track creation
4451 if (!mTracks.isEmpty()) {
4452 status = INVALID_OPERATION;
4453 } else {
4454 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004455 }
Eric Laurent10351942014-05-08 18:49:52 -07004456 }
4457 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004458#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004459 // when changing the audio output device, call addBatteryData to notify
4460 // the change
4461 if (mOutDevice != value) {
4462 uint32_t params = 0;
4463 // check whether speaker is on
4464 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4465 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004466 }
Eric Laurent10351942014-05-08 18:49:52 -07004467
4468 audio_devices_t deviceWithoutSpeaker
4469 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4470 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07004471 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07004472 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4473 }
4474
4475 if (params != 0) {
4476 addBatteryData(params);
4477 }
4478 }
Eric Laurent81784c32012-11-19 14:55:58 -08004479#endif
4480
Eric Laurent10351942014-05-08 18:49:52 -07004481 // forward device change to effects that have requested to be
4482 // aware of attached audio device.
4483 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08004484 a2dpDeviceChanged =
4485 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07004486 mOutDevice = value;
4487 for (size_t i = 0; i < mEffectChains.size(); i++) {
4488 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004489 }
4490 }
Eric Laurent10351942014-05-08 18:49:52 -07004491 }
Eric Laurent81784c32012-11-19 14:55:58 -08004492
Eric Laurent10351942014-05-08 18:49:52 -07004493 if (status == NO_ERROR) {
4494 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4495 keyValuePair.string());
4496 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004497 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004498 mStandby = true;
4499 mBytesWritten = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004500 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Eric Laurent10351942014-05-08 18:49:52 -07004501 keyValuePair.string());
Eric Laurent81784c32012-11-19 14:55:58 -08004502 }
Eric Laurent10351942014-05-08 18:49:52 -07004503 if (status == NO_ERROR && reconfig) {
4504 readOutputParameters_l();
4505 delete mAudioMixer;
4506 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4507 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004508 int name = getTrackName_l(mTracks[i]->mChannelMask,
4509 mTracks[i]->mFormat, mTracks[i]->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07004510 if (name < 0) {
4511 break;
4512 }
4513 mTracks[i]->mName = name;
4514 }
Eric Laurent73e26b62015-04-27 16:55:58 -07004515 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004516 }
Eric Laurent81784c32012-11-19 14:55:58 -08004517 }
4518
Eric Laurent42537be2016-01-08 17:16:42 -08004519 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08004520}
4521
4522
4523void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4524{
Eric Laurent81784c32012-11-19 14:55:58 -08004525 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07004526 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Elliott Hughes87cebad2014-05-22 10:14:43 -07004527 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Andy Hung2ddee192015-12-18 17:34:44 -08004528 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent81784c32012-11-19 14:55:58 -08004529
4530 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten2f90c512015-12-02 11:40:09 -08004531 // while we are dumping it. It may be inconsistent, but it won't mutate!
4532 // This is a large object so we place it on the heap.
4533 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
4534 const FastMixerDumpState *copy = new FastMixerDumpState(mFastMixerDumpState);
4535 copy->dump(fd);
4536 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08004537
4538#ifdef STATE_QUEUE_DUMP
4539 // Similar for state queue
4540 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4541 observerCopy.dump(fd);
4542 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4543 mutatorCopy.dump(fd);
4544#endif
4545
Glenn Kasten46909e72013-02-26 09:20:22 -08004546#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004547 // Write the tee output to a .wav file
4548 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08004549#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004550
4551#ifdef AUDIO_WATCHDOG
4552 if (mAudioWatchdog != 0) {
4553 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4554 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4555 wdCopy.dump(fd);
4556 }
4557#endif
4558}
4559
4560uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4561{
4562 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4563}
4564
4565uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4566{
4567 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4568}
4569
4570void AudioFlinger::MixerThread::cacheParameters_l()
4571{
4572 PlaybackThread::cacheParameters_l();
4573
4574 // FIXME: Relaxed timing because of a certain device that can't meet latency
4575 // Should be reduced to 2x after the vendor fixes the driver issue
4576 // increase threshold again due to low power audio mode. The way this warning
4577 // threshold is calculated and its usefulness should be reconsidered anyway.
4578 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4579}
4580
4581// ----------------------------------------------------------------------------
4582
4583AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent51716182016-02-29 18:00:56 -08004584 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady,
4585 uint32_t bitRate)
4586 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady, bitRate)
Eric Laurent81784c32012-11-19 14:55:58 -08004587 // mLeftVolFloat, mRightVolFloat
4588{
4589}
4590
Eric Laurentbfb1b832013-01-07 09:53:42 -08004591AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4592 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurent51716182016-02-29 18:00:56 -08004593 ThreadBase::type_t type, bool systemReady, uint32_t bitRate)
4594 : PlaybackThread(audioFlinger, output, id, device, type, systemReady, bitRate)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004595 // mLeftVolFloat, mRightVolFloat
4596{
4597}
4598
Eric Laurent81784c32012-11-19 14:55:58 -08004599AudioFlinger::DirectOutputThread::~DirectOutputThread()
4600{
4601}
4602
Eric Laurentbfb1b832013-01-07 09:53:42 -08004603void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
4604{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004605 float left, right;
4606
4607 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4608 left = right = 0;
4609 } else {
4610 float typeVolume = mStreamTypes[track->streamType()].volume;
4611 float v = mMasterVolume * typeVolume;
4612 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004613 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4614 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4615 if (left > GAIN_FLOAT_UNITY) {
4616 left = GAIN_FLOAT_UNITY;
4617 }
4618 left *= v;
4619 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4620 if (right > GAIN_FLOAT_UNITY) {
4621 right = GAIN_FLOAT_UNITY;
4622 }
4623 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004624 }
4625
4626 if (lastTrack) {
4627 if (left != mLeftVolFloat || right != mRightVolFloat) {
4628 mLeftVolFloat = left;
4629 mRightVolFloat = right;
4630
4631 // Convert volumes from float to 8.24
4632 uint32_t vl = (uint32_t)(left * (1 << 24));
4633 uint32_t vr = (uint32_t)(right * (1 << 24));
4634
4635 // Delegate volume control to effect in track effect chain if needed
4636 // only one effect chain can be present on DirectOutputThread, so if
4637 // there is one, the track is connected to it
4638 if (!mEffectChains.isEmpty()) {
4639 mEffectChains[0]->setVolume_l(&vl, &vr);
4640 left = (float)vl / (1 << 24);
4641 right = (float)vr / (1 << 24);
4642 }
4643 if (mOutput->stream->set_volume) {
4644 mOutput->stream->set_volume(mOutput->stream, left, right);
4645 }
4646 }
4647 }
4648}
4649
Phil Burk43b4dcc2015-06-09 16:53:44 -07004650void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
4651{
4652 sp<Track> previousTrack = mPreviousTrack.promote();
4653 sp<Track> latestTrack = mLatestActiveTrack.promote();
4654
Eric Laurent0f0631e2015-07-06 18:01:25 -07004655 if (previousTrack != 0 && latestTrack != 0) {
4656 if (mType == DIRECT) {
4657 if (previousTrack.get() != latestTrack.get()) {
4658 mFlushPending = true;
4659 }
4660 } else /* mType == OFFLOAD */ {
4661 if (previousTrack->sessionId() != latestTrack->sessionId()) {
4662 mFlushPending = true;
4663 }
4664 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004665 }
4666 PlaybackThread::onAddNewTrack_l();
4667}
Eric Laurentbfb1b832013-01-07 09:53:42 -08004668
Eric Laurent81784c32012-11-19 14:55:58 -08004669AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4670 Vector< sp<Track> > *tracksToRemove
4671)
4672{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004673 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004674 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004675 bool doHwPause = false;
4676 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004677
4678 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07004679 for (size_t i = 0; i < count; i++) {
4680 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08004681 // The track died recently
4682 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004683 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08004684 }
4685
Phil Burk43b4dcc2015-06-09 16:53:44 -07004686 if (t->isInvalid()) {
4687 ALOGW("An invalidated track shouldn't be in active list");
4688 tracksToRemove->add(t);
4689 continue;
4690 }
4691
Eric Laurent81784c32012-11-19 14:55:58 -08004692 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004693#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08004694 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004695#endif
Eric Laurentfd477972013-10-25 18:10:40 -07004696 // Only consider last track started for volume and mixer state control.
4697 // In theory an older track could underrun and restart after the new one starts
4698 // but as we only care about the transition phase between two tracks on a
4699 // direct output, it is not a problem to ignore the underrun case.
4700 sp<Track> l = mLatestActiveTrack.promote();
4701 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004702
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004703 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004704 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004705 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004706 doHwPause = true;
4707 mHwPaused = true;
4708 }
4709 tracksToRemove->add(track);
4710 } else if (track->isFlushPending()) {
4711 track->flushAck();
4712 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004713 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004714 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004715 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004716 track->resumeAck();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004717 if (last && mHwPaused) {
4718 doHwResume = true;
4719 mHwPaused = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004720 }
4721 }
4722
Eric Laurent81784c32012-11-19 14:55:58 -08004723 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004724 // for all its buffers to be filled before processing it.
4725 // Allow draining the buffer in case the client
4726 // app does not call stop() and relies on underrun to stop:
4727 // hence the test on (track->mRetryCount > 1).
4728 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07004729 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08004730 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004731 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08004732 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004733 minFrames = mNormalFrameCount;
4734 } else {
4735 minFrames = 1;
4736 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004737
Eric Laurentab5cdba2014-06-09 17:22:27 -07004738 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4739 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004740 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004741 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004742
4743 if (track->mFillingUpStatus == Track::FS_FILLED) {
4744 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004745 // make sure processVolume_l() will apply new volume even if 0
4746 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004747 if (!mHwSupportsPause) {
4748 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004749 }
4750 }
4751
4752 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004753 processVolume_l(track, last);
4754 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004755 sp<Track> previousTrack = mPreviousTrack.promote();
4756 if (previousTrack != 0) {
4757 if (track != previousTrack.get()) {
4758 // Flush any data still being written from last track
4759 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07004760 // Invalidate previous track to force a seek when resuming.
4761 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004762 }
4763 }
4764 mPreviousTrack = track;
4765
Eric Laurentd595b7c2013-04-03 17:27:56 -07004766 // reset retry count
4767 track->mRetryCount = kMaxTrackRetriesDirect;
4768 mActiveTrack = t;
4769 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07004770 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004771 doHwResume = true;
4772 mHwPaused = false;
4773 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004774 }
Eric Laurent81784c32012-11-19 14:55:58 -08004775 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004776 // clear effect chain input buffer if the last active track started underruns
4777 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004778 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004779 mEffectChains[0]->clearInputBuffer();
4780 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004781 if (track->isStopping_1()) {
4782 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07004783 if (last && mHwPaused) {
4784 doHwResume = true;
4785 mHwPaused = false;
4786 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004787 }
4788 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4789 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004790 // We have consumed all the buffers of this track.
4791 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004792 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08004793 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004794 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4795 } else {
4796 audioHALFrames = 0;
4797 }
4798
Andy Hung818e7a32016-02-16 18:08:07 -08004799 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004800 if (mStandby || !last ||
4801 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004802 if (track->isStopping_2()) {
4803 track->mState = TrackBase::STOPPED;
4804 }
Eric Laurent81784c32012-11-19 14:55:58 -08004805 if (track->isStopped()) {
4806 track->reset();
4807 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004808 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004809 }
4810 } else {
4811 // No buffers for this track. Give it a few chances to
4812 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004813 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004814 if (--(track->mRetryCount) <= 0) {
4815 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004816 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004817 // indicate to client process that the track was disabled because of underrun;
4818 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004819 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004820 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07004821 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
4822 "minFrames = %u, mFormat = %#x",
4823 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08004824 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07004825 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004826 doHwPause = true;
4827 mHwPaused = true;
4828 }
Eric Laurent81784c32012-11-19 14:55:58 -08004829 }
4830 }
4831 }
4832 }
4833
Eric Laurentd1f69b02014-12-15 14:33:13 -08004834 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07004835 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004836 for (size_t i = 0; i < mTracks.size(); i++) {
4837 if (mTracks[i]->isFlushPending()) {
4838 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004839 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004840 }
4841 }
4842 }
4843
4844 // make sure the pause/flush/resume sequence is executed in the right order.
4845 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4846 // before flush and then resume HW. This can happen in case of pause/flush/resume
4847 // if resume is received before pause is executed.
4848 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07004849 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004850 mOutput->stream->pause(mOutput->stream);
4851 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004852 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004853 flushHw_l();
4854 }
4855 if (mHwSupportsPause && !mStandby && doHwResume) {
4856 mOutput->stream->resume(mOutput->stream);
4857 }
Eric Laurent81784c32012-11-19 14:55:58 -08004858 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004859 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004860
4861 return mixerStatus;
4862}
4863
4864void AudioFlinger::DirectOutputThread::threadLoop_mix()
4865{
Eric Laurent81784c32012-11-19 14:55:58 -08004866 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08004867 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004868 // output audio to hardware
4869 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07004870 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004871 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08004872 status_t status = mActiveTrack->getNextBuffer(&buffer);
4873 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08004874 // no need to pad with 0 for compressed audio
4875 if (audio_has_proportional_frames(mFormat)) {
4876 memset(curBuf, 0, frameCount * mFrameSize);
4877 }
Eric Laurent81784c32012-11-19 14:55:58 -08004878 break;
4879 }
4880 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
4881 frameCount -= buffer.frameCount;
4882 curBuf += buffer.frameCount * mFrameSize;
4883 mActiveTrack->releaseBuffer(&buffer);
4884 }
Andy Hung2098f272014-02-27 14:00:06 -08004885 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004886 mSleepTimeUs = 0;
4887 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004888 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004889}
4890
4891void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
4892{
Eric Laurentd1f69b02014-12-15 14:33:13 -08004893 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004894 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004895 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004896 return;
4897 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004898 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004899 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurent51716182016-02-29 18:00:56 -08004900 // For compressed offload, use faster sleep time when underruning until more than an
4901 // entire buffer was written to the audio HAL
4902 if (!audio_has_proportional_frames(mFormat) &&
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004903 (mType == OFFLOAD) && (mBytesWritten < (int64_t) mBufferSize)) {
Eric Laurent51716182016-02-29 18:00:56 -08004904 mSleepTimeUs = kDirectMinSleepTimeUs;
4905 } else {
4906 mSleepTimeUs = mActiveSleepTimeUs;
4907 }
Eric Laurent81784c32012-11-19 14:55:58 -08004908 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004909 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004910 }
Phil Burkfdb3c072016-02-09 10:47:02 -08004911 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08004912 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004913 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004914 }
4915}
4916
Eric Laurentd1f69b02014-12-15 14:33:13 -08004917void AudioFlinger::DirectOutputThread::threadLoop_exit()
4918{
4919 {
4920 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08004921 for (size_t i = 0; i < mTracks.size(); i++) {
4922 if (mTracks[i]->isFlushPending()) {
4923 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004924 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004925 }
4926 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004927 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004928 flushHw_l();
4929 }
4930 }
4931 PlaybackThread::threadLoop_exit();
4932}
4933
4934// must be called with thread mutex locked
4935bool AudioFlinger::DirectOutputThread::shouldStandby_l()
4936{
4937 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07004938 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004939
vivek mehta9cd7ad12016-03-17 00:18:29 -07004940 if ((mType == DIRECT) && audio_is_linear_pcm(mFormat) && !usesHwAvSync()) {
4941 return !mStandby;
4942 }
4943
Eric Laurentd1f69b02014-12-15 14:33:13 -08004944 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4945 // after a timeout and we will enter standby then.
4946 if (mTracks.size() > 0) {
4947 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07004948 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
4949 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004950 }
4951
Eric Laurent5cff4032015-05-26 13:49:58 -07004952 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08004953}
4954
Eric Laurent81784c32012-11-19 14:55:58 -08004955// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004956int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Glenn Kastend848eb42016-03-08 13:42:11 -08004957 audio_format_t format __unused, audio_session_t sessionId __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004958{
4959 return 0;
4960}
4961
4962// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004963void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004964{
4965}
4966
Eric Laurent10351942014-05-08 18:49:52 -07004967// checkForNewParameter_l() must be called with ThreadBase::mLock held
4968bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
4969 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004970{
4971 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08004972 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004973
Eric Laurent10351942014-05-08 18:49:52 -07004974 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004975
Eric Laurent10351942014-05-08 18:49:52 -07004976 AudioParameter param = AudioParameter(keyValuePair);
4977 int value;
4978 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4979 // forward device change to effects that have requested to be
4980 // aware of attached audio device.
4981 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08004982 a2dpDeviceChanged =
4983 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07004984 mOutDevice = value;
4985 for (size_t i = 0; i < mEffectChains.size(); i++) {
4986 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07004987 }
4988 }
Eric Laurent81784c32012-11-19 14:55:58 -08004989 }
Eric Laurent10351942014-05-08 18:49:52 -07004990 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4991 // do not accept frame count changes if tracks are open as the track buffer
4992 // size depends on frame count and correct behavior would not be garantied
4993 // if frame count is changed after track creation
4994 if (!mTracks.isEmpty()) {
4995 status = INVALID_OPERATION;
4996 } else {
4997 reconfig = true;
4998 }
4999 }
5000 if (status == NO_ERROR) {
5001 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
5002 keyValuePair.string());
5003 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005004 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005005 mStandby = true;
5006 mBytesWritten = 0;
5007 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
5008 keyValuePair.string());
5009 }
5010 if (status == NO_ERROR && reconfig) {
5011 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07005012 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005013 }
5014 }
5015
Eric Laurent42537be2016-01-08 17:16:42 -08005016 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005017}
5018
5019uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
5020{
5021 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005022 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005023 time = PlaybackThread::activeSleepTimeUs();
5024 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005025 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005026 }
5027 return time;
5028}
5029
5030uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
5031{
5032 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005033 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005034 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
5035 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005036 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005037 }
5038 return time;
5039}
5040
5041uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
5042{
5043 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005044 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005045 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
5046 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005047 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005048 }
5049 return time;
5050}
5051
5052void AudioFlinger::DirectOutputThread::cacheParameters_l()
5053{
5054 PlaybackThread::cacheParameters_l();
5055
5056 // use shorter standby delay as on normal output to release
5057 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07005058 // no delay on outputs with HW A/V sync
5059 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005060 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08005061 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005062 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07005063 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005064 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07005065 }
Eric Laurent81784c32012-11-19 14:55:58 -08005066}
5067
Eric Laurente659ef42014-09-29 13:06:46 -07005068void AudioFlinger::DirectOutputThread::flushHw_l()
5069{
Phil Burk062e67a2015-02-11 13:40:50 -08005070 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08005071 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005072 mFlushPending = false;
Eric Laurente659ef42014-09-29 13:06:46 -07005073}
5074
Eric Laurent81784c32012-11-19 14:55:58 -08005075// ----------------------------------------------------------------------------
5076
Eric Laurentbfb1b832013-01-07 09:53:42 -08005077AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07005078 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005079 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07005080 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07005081 mWriteAckSequence(0),
5082 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005083{
5084}
5085
5086AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
5087{
5088}
5089
5090void AudioFlinger::AsyncCallbackThread::onFirstRef()
5091{
5092 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
5093}
5094
5095bool AudioFlinger::AsyncCallbackThread::threadLoop()
5096{
5097 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005098 uint32_t writeAckSequence;
5099 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005100
5101 {
5102 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005103 while (!((mWriteAckSequence & 1) ||
5104 (mDrainSequence & 1) ||
5105 exitPending())) {
5106 mWaitWorkCV.wait(mLock);
5107 }
5108
Eric Laurentbfb1b832013-01-07 09:53:42 -08005109 if (exitPending()) {
5110 break;
5111 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005112 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
5113 mWriteAckSequence, mDrainSequence);
5114 writeAckSequence = mWriteAckSequence;
5115 mWriteAckSequence &= ~1;
5116 drainSequence = mDrainSequence;
5117 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005118 }
5119 {
Eric Laurent4de95592013-09-26 15:28:21 -07005120 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
5121 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005122 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005123 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005124 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005125 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005126 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005127 }
5128 }
5129 }
5130 }
5131 return false;
5132}
5133
5134void AudioFlinger::AsyncCallbackThread::exit()
5135{
5136 ALOGV("AsyncCallbackThread::exit");
5137 Mutex::Autolock _l(mLock);
5138 requestExit();
5139 mWaitWorkCV.broadcast();
5140}
5141
Eric Laurent3b4529e2013-09-05 18:09:19 -07005142void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005143{
5144 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005145 // bit 0 is cleared
5146 mWriteAckSequence = sequence << 1;
5147}
5148
5149void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5150{
5151 Mutex::Autolock _l(mLock);
5152 // ignore unexpected callbacks
5153 if (mWriteAckSequence & 2) {
5154 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005155 mWaitWorkCV.signal();
5156 }
5157}
5158
Eric Laurent3b4529e2013-09-05 18:09:19 -07005159void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005160{
5161 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005162 // bit 0 is cleared
5163 mDrainSequence = sequence << 1;
5164}
5165
5166void AudioFlinger::AsyncCallbackThread::resetDraining()
5167{
5168 Mutex::Autolock _l(mLock);
5169 // ignore unexpected callbacks
5170 if (mDrainSequence & 2) {
5171 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005172 mWaitWorkCV.signal();
5173 }
5174}
5175
5176
5177// ----------------------------------------------------------------------------
5178AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent51716182016-02-29 18:00:56 -08005179 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady,
5180 uint32_t bitRate)
5181 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady, bitRate),
Eric Laurentd7e59222013-11-15 12:02:28 -08005182 mPausedBytesRemaining(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005183{
Eric Laurentfd477972013-10-25 18:10:40 -07005184 //FIXME: mStandby should be set to true by ThreadBase constructor
5185 mStandby = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005186}
5187
Eric Laurentbfb1b832013-01-07 09:53:42 -08005188void AudioFlinger::OffloadThread::threadLoop_exit()
5189{
5190 if (mFlushPending || mHwPaused) {
5191 // If a flush is pending or track was paused, just discard buffered data
5192 flushHw_l();
5193 } else {
5194 mMixerStatus = MIXER_DRAIN_ALL;
5195 threadLoop_drain();
5196 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005197 if (mUseAsyncWrite) {
5198 ALOG_ASSERT(mCallbackThread != 0);
5199 mCallbackThread->exit();
5200 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005201 PlaybackThread::threadLoop_exit();
5202}
5203
5204AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5205 Vector< sp<Track> > *tracksToRemove
5206)
5207{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005208 size_t count = mActiveTracks.size();
5209
5210 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005211 bool doHwPause = false;
5212 bool doHwResume = false;
5213
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005214 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07005215
Eric Laurentbfb1b832013-01-07 09:53:42 -08005216 // find out which tracks need to be processed
5217 for (size_t i = 0; i < count; i++) {
5218 sp<Track> t = mActiveTracks[i].promote();
5219 // The track died recently
5220 if (t == 0) {
5221 continue;
5222 }
5223 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005224#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08005225 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005226#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005227 // Only consider last track started for volume and mixer state control.
5228 // In theory an older track could underrun and restart after the new one starts
5229 // but as we only care about the transition phase between two tracks on a
5230 // direct output, it is not a problem to ignore the underrun case.
5231 sp<Track> l = mLatestActiveTrack.promote();
5232 bool last = l.get() == track;
5233
Haynes Mathew George7844f672014-01-15 12:32:55 -08005234 if (track->isInvalid()) {
5235 ALOGW("An invalidated track shouldn't be in active list");
5236 tracksToRemove->add(track);
5237 continue;
5238 }
5239
5240 if (track->mState == TrackBase::IDLE) {
5241 ALOGW("An idle track shouldn't be in active list");
5242 continue;
5243 }
5244
Eric Laurentbfb1b832013-01-07 09:53:42 -08005245 if (track->isPausing()) {
5246 track->setPaused();
5247 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005248 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005249 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005250 mHwPaused = true;
5251 }
5252 // If we were part way through writing the mixbuffer to
5253 // the HAL we must save this until we resume
5254 // BUG - this will be wrong if a different track is made active,
5255 // in that case we want to discard the pending data in the
5256 // mixbuffer and tell the client to present it again when the
5257 // track is resumed
5258 mPausedWriteLength = mCurrentWriteLength;
5259 mPausedBytesRemaining = mBytesRemaining;
5260 mBytesRemaining = 0; // stop writing
5261 }
5262 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005263 } else if (track->isFlushPending()) {
Eric Laurent51716182016-02-29 18:00:56 -08005264 track->mRetryCount = kMaxTrackRetriesOffload;
Haynes Mathew George7844f672014-01-15 12:32:55 -08005265 track->flushAck();
5266 if (last) {
5267 mFlushPending = true;
5268 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005269 } else if (track->isResumePending()){
5270 track->resumeAck();
5271 if (last) {
5272 if (mPausedBytesRemaining) {
5273 // Need to continue write that was interrupted
5274 mCurrentWriteLength = mPausedWriteLength;
5275 mBytesRemaining = mPausedBytesRemaining;
5276 mPausedBytesRemaining = 0;
5277 }
5278 if (mHwPaused) {
5279 doHwResume = true;
5280 mHwPaused = false;
5281 // threadLoop_mix() will handle the case that we need to
5282 // resume an interrupted write
5283 }
5284 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005285 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005286
5287 // Do not handle new data in this iteration even if track->framesReady()
5288 mixerStatus = MIXER_TRACKS_ENABLED;
5289 }
5290 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005291 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005292 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005293 if (track->mFillingUpStatus == Track::FS_FILLED) {
5294 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07005295 // make sure processVolume_l() will apply new volume even if 0
5296 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005297 }
5298
5299 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005300 sp<Track> previousTrack = mPreviousTrack.promote();
5301 if (previousTrack != 0) {
5302 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005303 // Flush any data still being written from last track
5304 mBytesRemaining = 0;
5305 if (mPausedBytesRemaining) {
5306 // Last track was paused so we also need to flush saved
5307 // mixbuffer state and invalidate track so that it will
5308 // re-submit that unwritten data when it is next resumed
5309 mPausedBytesRemaining = 0;
5310 // Invalidate is a bit drastic - would be more efficient
5311 // to have a flag to tell client that some of the
5312 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005313 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005314 }
5315 // flush data already sent to the DSP if changing audio session as audio
5316 // comes from a different source. Also invalidate previous track to force a
5317 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005318 if (previousTrack->sessionId() != track->sessionId()) {
5319 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005320 }
5321 }
5322 }
5323 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005324 // reset retry count
5325 track->mRetryCount = kMaxTrackRetriesOffload;
5326 mActiveTrack = t;
5327 mixerStatus = MIXER_TRACKS_READY;
5328 }
5329 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005330 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005331 if (track->isStopping_1()) {
5332 // Hardware buffer can hold a large amount of audio so we must
5333 // wait for all current track's data to drain before we say
5334 // that the track is stopped.
5335 if (mBytesRemaining == 0) {
5336 // Only start draining when all data in mixbuffer
5337 // has been written
5338 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5339 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005340 // do not drain if no data was ever sent to HAL (mStandby == true)
5341 if (last && !mStandby) {
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005342 // do not modify drain sequence if we are already draining. This happens
5343 // when resuming from pause after drain.
5344 if ((mDrainSequence & 1) == 0) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005345 mSleepTimeUs = 0;
5346 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005347 mixerStatus = MIXER_DRAIN_TRACK;
5348 mDrainSequence += 2;
5349 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005350 if (mHwPaused) {
5351 // It is possible to move from PAUSED to STOPPING_1 without
5352 // a resume so we must ensure hardware is running
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005353 doHwResume = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005354 mHwPaused = false;
5355 }
5356 }
5357 }
5358 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005359 // Drain has completed or we are in standby, signal presentation complete
5360 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005361 track->mState = TrackBase::STOPPED;
5362 size_t audioHALFrames =
5363 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005364 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005365 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005366 track->presentationComplete(framesWritten, audioHALFrames);
5367 track->reset();
5368 tracksToRemove->add(track);
5369 }
5370 } else {
5371 // No buffers for this track. Give it a few chances to
5372 // fill a buffer, then remove it from active list.
5373 if (--(track->mRetryCount) <= 0) {
5374 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5375 track->name());
5376 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005377 // indicate to client process that the track was disabled because of underrun;
5378 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005379 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005380 } else if (last){
5381 mixerStatus = MIXER_TRACKS_ENABLED;
5382 }
5383 }
5384 }
5385 // compute volume for this track
5386 processVolume_l(track, last);
5387 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005388
Eric Laurentea0fade2013-10-04 16:23:48 -07005389 // make sure the pause/flush/resume sequence is executed in the right order.
5390 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5391 // before flush and then resume HW. This can happen in case of pause/flush/resume
5392 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07005393 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07005394 mOutput->stream->pause(mOutput->stream);
5395 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005396 if (mFlushPending) {
5397 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005398 }
Eric Laurentfd477972013-10-25 18:10:40 -07005399 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07005400 mOutput->stream->resume(mOutput->stream);
5401 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005402
Eric Laurentbfb1b832013-01-07 09:53:42 -08005403 // remove all the tracks that need to be...
5404 removeTracks_l(*tracksToRemove);
5405
5406 return mixerStatus;
5407}
5408
Eric Laurentbfb1b832013-01-07 09:53:42 -08005409// must be called with thread mutex locked
5410bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5411{
Eric Laurent3b4529e2013-09-05 18:09:19 -07005412 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5413 mWriteAckSequence, mDrainSequence);
5414 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005415 return true;
5416 }
5417 return false;
5418}
5419
Eric Laurentbfb1b832013-01-07 09:53:42 -08005420bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5421{
5422 Mutex::Autolock _l(mLock);
5423 return waitingAsyncCallback_l();
5424}
5425
5426void AudioFlinger::OffloadThread::flushHw_l()
5427{
Eric Laurente659ef42014-09-29 13:06:46 -07005428 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005429 // Flush anything still waiting in the mixbuffer
5430 mCurrentWriteLength = 0;
5431 mBytesRemaining = 0;
5432 mPausedWriteLength = 0;
5433 mPausedBytesRemaining = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08005434
Eric Laurentbfb1b832013-01-07 09:53:42 -08005435 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005436 // discard any pending drain or write ack by incrementing sequence
5437 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5438 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005439 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005440 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5441 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005442 }
5443}
5444
Eric Laurent51716182016-02-29 18:00:56 -08005445uint32_t AudioFlinger::OffloadThread::activeSleepTimeUs() const
5446{
5447 uint32_t time;
5448 if (audio_has_proportional_frames(mFormat)) {
5449 time = PlaybackThread::activeSleepTimeUs();
5450 } else {
5451 // sleep time is half the duration of an audio HAL buffer.
5452 // Note: This can be problematic in case of underrun with variable bit rate and
5453 // current rate is much less than initial rate.
5454 time = (uint32_t)max(kDirectMinSleepTimeUs, mBufferDurationUs / 2);
5455 }
5456 return time;
5457}
5458
Eric Laurentbfb1b832013-01-07 09:53:42 -08005459// ----------------------------------------------------------------------------
5460
Eric Laurent81784c32012-11-19 14:55:58 -08005461AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005462 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005463 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07005464 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08005465 mWaitTimeMs(UINT_MAX)
5466{
5467 addOutputTrack(mainThread);
5468}
5469
5470AudioFlinger::DuplicatingThread::~DuplicatingThread()
5471{
5472 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5473 mOutputTracks[i]->destroy();
5474 }
5475}
5476
5477void AudioFlinger::DuplicatingThread::threadLoop_mix()
5478{
5479 // mix buffers...
5480 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08005481 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08005482 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005483 if (mMixerBufferValid) {
5484 memset(mMixerBuffer, 0, mMixerBufferSize);
5485 } else {
5486 memset(mSinkBuffer, 0, mSinkBufferSize);
5487 }
Eric Laurent81784c32012-11-19 14:55:58 -08005488 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005489 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005490 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005491 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005492 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005493}
5494
5495void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5496{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005497 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005498 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005499 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005500 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005501 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005502 }
5503 } else if (mBytesWritten != 0) {
5504 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5505 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005506 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005507 } else {
5508 // flush remaining overflow buffers in output tracks
5509 writeFrames = 0;
5510 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005511 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005512 }
5513}
5514
Eric Laurentbfb1b832013-01-07 09:53:42 -08005515ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005516{
5517 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005518 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005519 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005520 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005521 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005522}
5523
5524void AudioFlinger::DuplicatingThread::threadLoop_standby()
5525{
5526 // DuplicatingThread implements standby by stopping all tracks
5527 for (size_t i = 0; i < outputTracks.size(); i++) {
5528 outputTracks[i]->stop();
5529 }
5530}
5531
5532void AudioFlinger::DuplicatingThread::saveOutputTracks()
5533{
5534 outputTracks = mOutputTracks;
5535}
5536
5537void AudioFlinger::DuplicatingThread::clearOutputTracks()
5538{
5539 outputTracks.clear();
5540}
5541
5542void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5543{
5544 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005545 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5546 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5547 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5548 const size_t frameCount =
5549 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5550 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5551 // from different OutputTracks and their associated MixerThreads (e.g. one may
5552 // nearly empty and the other may be dropping data).
5553
5554 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005555 this,
5556 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005557 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005558 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005559 frameCount,
5560 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08005561 if (outputTrack->cblk() != NULL) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005562 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
Eric Laurent81784c32012-11-19 14:55:58 -08005563 mOutputTracks.add(outputTrack);
Andy Hungc25b84a2015-01-14 19:04:10 -08005564 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005565 updateWaitTime_l();
5566 }
5567}
5568
5569void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5570{
5571 Mutex::Autolock _l(mLock);
5572 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5573 if (mOutputTracks[i]->thread() == thread) {
5574 mOutputTracks[i]->destroy();
5575 mOutputTracks.removeAt(i);
5576 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07005577 if (thread->getOutput() == mOutput) {
5578 mOutput = NULL;
5579 }
Eric Laurent81784c32012-11-19 14:55:58 -08005580 return;
5581 }
5582 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07005583 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005584}
5585
5586// caller must hold mLock
5587void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5588{
5589 mWaitTimeMs = UINT_MAX;
5590 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5591 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5592 if (strong != 0) {
5593 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5594 if (waitTimeMs < mWaitTimeMs) {
5595 mWaitTimeMs = waitTimeMs;
5596 }
5597 }
5598 }
5599}
5600
5601
5602bool AudioFlinger::DuplicatingThread::outputsReady(
5603 const SortedVector< sp<OutputTrack> > &outputTracks)
5604{
5605 for (size_t i = 0; i < outputTracks.size(); i++) {
5606 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5607 if (thread == 0) {
5608 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5609 outputTracks[i].get());
5610 return false;
5611 }
5612 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5613 // see note at standby() declaration
5614 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5615 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5616 thread.get());
5617 return false;
5618 }
5619 }
5620 return true;
5621}
5622
5623uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5624{
5625 return (mWaitTimeMs * 1000) / 2;
5626}
5627
5628void AudioFlinger::DuplicatingThread::cacheParameters_l()
5629{
5630 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5631 updateWaitTime_l();
5632
5633 MixerThread::cacheParameters_l();
5634}
5635
5636// ----------------------------------------------------------------------------
5637// Record
5638// ----------------------------------------------------------------------------
5639
5640AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5641 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005642 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005643 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07005644 audio_devices_t inDevice,
5645 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08005646#ifdef TEE_SINK
5647 , const sp<NBAIO_Sink>& teeSink
5648#endif
5649 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07005650 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005651 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005652 // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005653 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005654#ifdef TEE_SINK
5655 , mTeeSink(teeSink)
5656#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005657 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5658 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005659 // mFastCapture below
5660 , mFastCaptureFutex(0)
5661 // mInputSource
5662 // mPipeSink
5663 // mPipeSource
5664 , mPipeFramesP2(0)
5665 // mPipeMemory
5666 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005667 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005668{
Glenn Kastend7dca052015-03-05 16:05:54 -08005669 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5670 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08005671
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005672 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005673
5674 // create an NBAIO source for the HAL input stream, and negotiate
5675 mInputSource = new AudioStreamInSource(input->stream);
5676 size_t numCounterOffers = 0;
5677 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005678#if !LOG_NDEBUG
5679 ssize_t index =
5680#else
5681 (void)
5682#endif
5683 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005684 ALOG_ASSERT(index == 0);
5685
5686 // initialize fast capture depending on configuration
5687 bool initFastCapture;
5688 switch (kUseFastCapture) {
5689 case FastCapture_Never:
5690 initFastCapture = false;
5691 break;
5692 case FastCapture_Always:
5693 initFastCapture = true;
5694 break;
5695 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07005696 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005697 break;
5698 // case FastCapture_Dynamic:
5699 }
5700
5701 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07005702 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005703 NBAIO_Format format = mInputSource->format();
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005704 size_t pipeFramesP2 = roundup(mSampleRate / 25); // double-buffering of 20 ms each
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005705 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5706 void *pipeBuffer;
5707 const sp<MemoryDealer> roHeap(readOnlyHeap());
5708 sp<IMemory> pipeMemory;
5709 if ((roHeap == 0) ||
5710 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5711 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5712 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5713 goto failed;
5714 }
5715 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5716 memset(pipeBuffer, 0, pipeSize);
5717 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5718 const NBAIO_Format offers[1] = {format};
5719 size_t numCounterOffers = 0;
5720 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5721 ALOG_ASSERT(index == 0);
5722 mPipeSink = pipe;
5723 PipeReader *pipeReader = new PipeReader(*pipe);
5724 numCounterOffers = 0;
5725 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5726 ALOG_ASSERT(index == 0);
5727 mPipeSource = pipeReader;
5728 mPipeFramesP2 = pipeFramesP2;
5729 mPipeMemory = pipeMemory;
5730
5731 // create fast capture
5732 mFastCapture = new FastCapture();
5733 FastCaptureStateQueue *sq = mFastCapture->sq();
5734#ifdef STATE_QUEUE_DUMP
5735 // FIXME
5736#endif
5737 FastCaptureState *state = sq->begin();
5738 state->mCblk = NULL;
5739 state->mInputSource = mInputSource.get();
5740 state->mInputSourceGen++;
5741 state->mPipeSink = pipe;
5742 state->mPipeSinkGen++;
5743 state->mFrameCount = mFrameCount;
5744 state->mCommand = FastCaptureState::COLD_IDLE;
5745 // already done in constructor initialization list
5746 //mFastCaptureFutex = 0;
5747 state->mColdFutexAddr = &mFastCaptureFutex;
5748 state->mColdGen++;
5749 state->mDumpState = &mFastCaptureDumpState;
5750#ifdef TEE_SINK
5751 // FIXME
5752#endif
5753 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
5754 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
5755 sq->end();
5756 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5757
5758 // start the fast capture
5759 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
5760 pid_t tid = mFastCapture->getTid();
Glenn Kasten8379b722016-03-18 14:54:17 -07005761 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005762#ifdef AUDIO_WATCHDOG
5763 // FIXME
5764#endif
5765
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005766 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005767 }
5768failed: ;
5769
5770 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08005771}
5772
Eric Laurent81784c32012-11-19 14:55:58 -08005773AudioFlinger::RecordThread::~RecordThread()
5774{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005775 if (mFastCapture != 0) {
5776 FastCaptureStateQueue *sq = mFastCapture->sq();
5777 FastCaptureState *state = sq->begin();
5778 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5779 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5780 if (old == -1) {
5781 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5782 }
5783 }
5784 state->mCommand = FastCaptureState::EXIT;
5785 sq->end();
5786 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5787 mFastCapture->join();
5788 mFastCapture.clear();
5789 }
5790 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07005791 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07005792 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08005793}
5794
5795void AudioFlinger::RecordThread::onFirstRef()
5796{
Glenn Kastend7dca052015-03-05 16:05:54 -08005797 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08005798}
5799
Eric Laurent81784c32012-11-19 14:55:58 -08005800bool AudioFlinger::RecordThread::threadLoop()
5801{
Eric Laurent81784c32012-11-19 14:55:58 -08005802 nsecs_t lastWarning = 0;
5803
5804 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08005805
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005806reacquire_wakelock:
5807 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08005808 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005809 {
5810 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005811 size_t size = mActiveTracks.size();
5812 activeTracksGen = mActiveTracksGen;
5813 if (size > 0) {
5814 // FIXME an arbitrary choice
5815 activeTrack = mActiveTracks[0];
5816 acquireWakeLock_l(activeTrack->uid());
5817 if (size > 1) {
5818 SortedVector<int> tmp;
5819 for (size_t i = 0; i < size; i++) {
5820 tmp.add(mActiveTracks[i]->uid());
5821 }
5822 updateWakeLockUids_l(tmp);
5823 }
5824 } else {
5825 acquireWakeLock_l(-1);
5826 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005827 }
5828
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005829 // used to request a deferred sleep, to be executed later while mutex is unlocked
5830 uint32_t sleepUs = 0;
5831
5832 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005833 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005834 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07005835
Glenn Kasten5edadd42013-08-14 16:30:49 -07005836 // sleep with mutex unlocked
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005837 if (sleepUs > 0) {
Glenn Kastene7754022014-10-31 12:11:26 -07005838 ATRACE_BEGIN("sleep");
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005839 usleep(sleepUs);
Glenn Kastene7754022014-10-31 12:11:26 -07005840 ATRACE_END();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005841 sleepUs = 0;
Glenn Kasten5edadd42013-08-14 16:30:49 -07005842 }
5843
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005844 // activeTracks accumulates a copy of a subset of mActiveTracks
5845 Vector< sp<RecordTrack> > activeTracks;
5846
Glenn Kasten735f45f2014-08-18 15:51:59 -07005847 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005848 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07005849
Glenn Kasten735f45f2014-08-18 15:51:59 -07005850 // reference to a fast track which is about to be removed
5851 sp<RecordTrack> fastTrackToRemove;
5852
Eric Laurent81784c32012-11-19 14:55:58 -08005853 { // scope for mLock
5854 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08005855
Eric Laurent021cf962014-05-13 10:18:14 -07005856 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005857
Eric Laurent000a4192014-01-29 15:17:32 -08005858 // check exitPending here because checkForNewParameters_l() and
5859 // checkForNewParameters_l() can temporarily release mLock
5860 if (exitPending()) {
5861 break;
5862 }
5863
Glenn Kasten2b806402013-11-20 16:37:38 -08005864 // if no active track(s), then standby and release wakelock
5865 size_t size = mActiveTracks.size();
5866 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07005867 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005868 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08005869 releaseWakeLock_l();
5870 ALOGV("RecordThread: loop stopping");
5871 // go to sleep
5872 mWaitWorkCV.wait(mLock);
5873 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005874 goto reacquire_wakelock;
5875 }
5876
Glenn Kasten2b806402013-11-20 16:37:38 -08005877 if (mActiveTracksGen != activeTracksGen) {
5878 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005879 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08005880 for (size_t i = 0; i < size; i++) {
5881 tmp.add(mActiveTracks[i]->uid());
5882 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005883 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08005884 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005885
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005886 bool doBroadcast = false;
5887 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07005888
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005889 activeTrack = mActiveTracks[i];
5890 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07005891 if (activeTrack->isFastTrack()) {
5892 ALOG_ASSERT(fastTrackToRemove == 0);
5893 fastTrackToRemove = activeTrack;
5894 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005895 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08005896 mActiveTracks.remove(activeTrack);
5897 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005898 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07005899 continue;
5900 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005901
5902 TrackBase::track_state activeTrackState = activeTrack->mState;
5903 switch (activeTrackState) {
5904
5905 case TrackBase::PAUSING:
5906 mActiveTracks.remove(activeTrack);
5907 mActiveTracksGen++;
5908 doBroadcast = true;
5909 size--;
5910 continue;
5911
5912 case TrackBase::STARTING_1:
5913 sleepUs = 10000;
5914 i++;
5915 continue;
5916
5917 case TrackBase::STARTING_2:
5918 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005919 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07005920 activeTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005921 break;
5922
5923 case TrackBase::ACTIVE:
5924 break;
5925
5926 case TrackBase::IDLE:
5927 i++;
5928 continue;
5929
5930 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08005931 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07005932 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005933
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005934 activeTracks.add(activeTrack);
5935 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07005936
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005937 if (activeTrack->isFastTrack()) {
5938 ALOG_ASSERT(!mFastTrackAvail);
5939 ALOG_ASSERT(fastTrack == 0);
5940 fastTrack = activeTrack;
5941 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005942 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005943 if (doBroadcast) {
5944 mStartStopCond.broadcast();
5945 }
5946
5947 // sleep if there are no active tracks to process
5948 if (activeTracks.size() == 0) {
5949 if (sleepUs == 0) {
5950 sleepUs = kRecordThreadSleepUs;
5951 }
5952 continue;
5953 }
5954 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07005955
Eric Laurent81784c32012-11-19 14:55:58 -08005956 lockEffectChains_l(effectChains);
5957 }
5958
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005959 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07005960
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005961 size_t size = effectChains.size();
5962 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005963 // thread mutex is not locked, but effect chain is locked
5964 effectChains[i]->process_l();
5965 }
5966
Glenn Kasten735f45f2014-08-18 15:51:59 -07005967 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005968 if (mFastCapture != 0) {
5969 FastCaptureStateQueue *sq = mFastCapture->sq();
5970 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07005971 bool didModify = false;
5972 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005973 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
5974 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
5975 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5976 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5977 if (old == -1) {
5978 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5979 }
5980 }
5981 state->mCommand = FastCaptureState::READ_WRITE;
5982#if 0 // FIXME
5983 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08005984 FastThreadDumpState::kSamplingNforLowRamDevice :
5985 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005986#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07005987 didModify = true;
5988 }
5989 audio_track_cblk_t *cblkOld = state->mCblk;
5990 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
5991 if (cblkNew != cblkOld) {
5992 state->mCblk = cblkNew;
5993 // block until acked if removing a fast track
5994 if (cblkOld != NULL) {
5995 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
5996 }
5997 didModify = true;
5998 }
5999 sq->end(didModify);
6000 if (didModify) {
6001 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006002#if 0
6003 if (kUseFastCapture == FastCapture_Dynamic) {
6004 mNormalSource = mPipeSource;
6005 }
6006#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006007 }
6008 }
6009
Glenn Kasten735f45f2014-08-18 15:51:59 -07006010 // now run the fast track destructor with thread mutex unlocked
6011 fastTrackToRemove.clear();
6012
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006013 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
6014 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
6015 // slow, then this RecordThread will overrun by not calling HAL read often enough.
6016 // If destination is non-contiguous, first read past the nominal end of buffer, then
6017 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006018
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006019 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006020 ssize_t framesRead;
6021
6022 // If an NBAIO source is present, use it to read the normal capture's data
6023 if (mPipeSource != 0) {
6024 size_t framesToRead = mBufferSize / mFrameSize;
Andy Hung57446612015-04-19 23:56:46 -07006025 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
Glenn Kastend79072e2016-01-06 08:41:20 -08006026 framesToRead);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006027 if (framesRead == 0) {
6028 // since pipe is non-blocking, simulate blocking input
6029 sleepUs = (framesToRead * 1000000LL) / mSampleRate;
6030 }
6031 // otherwise use the HAL / AudioStreamIn directly
6032 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07006033 ATRACE_BEGIN("read");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006034 ssize_t bytesRead = mInput->stream->read(mInput->stream,
Andy Hung57446612015-04-19 23:56:46 -07006035 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize);
Glenn Kastenec6a7032016-03-14 07:40:23 -07006036 ATRACE_END();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006037 if (bytesRead < 0) {
6038 framesRead = bytesRead;
6039 } else {
6040 framesRead = bytesRead / mFrameSize;
6041 }
6042 }
6043
Andy Hung3f0c9022016-01-15 17:49:46 -08006044 // Update server timestamp with server stats
6045 // systemTime() is optional if the hardware supports timestamps.
6046 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
6047 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6048
6049 // Update server timestamp with kernel stats
6050 if (mInput->stream->get_capture_position != nullptr) {
6051 int64_t position, time;
6052 int ret = mInput->stream->get_capture_position(mInput->stream, &position, &time);
6053 if (ret == NO_ERROR) {
6054 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
6055 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
6056 // Note: In general record buffers should tend to be empty in
6057 // a properly running pipeline.
6058 //
6059 // Also, it is not advantageous to call get_presentation_position during the read
6060 // as the read obtains a lock, preventing the timestamp call from executing.
6061 }
6062 }
6063 // Use this to track timestamp information
6064 // ALOGD("%s", mTimestamp.toString().c_str());
6065
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006066 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006067 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006068 // Force input into standby so that it tries to recover at next read attempt
6069 inputStandBy();
6070 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006071 }
6072 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006073 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006074 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006075 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006076
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006077 if (mTeeSink != 0) {
Andy Hung57446612015-04-19 23:56:46 -07006078 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006079 }
6080 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006081 {
6082 size_t part1 = mRsmpInFramesP2 - rear;
6083 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07006084 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006085 (framesRead - part1) * mFrameSize);
6086 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006087 }
6088 rear = mRsmpInRear += framesRead;
6089
6090 size = activeTracks.size();
6091 // loop over each active track
6092 for (size_t i = 0; i < size; i++) {
6093 activeTrack = activeTracks[i];
6094
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006095 // skip fast tracks, as those are handled directly by FastCapture
6096 if (activeTrack->isFastTrack()) {
6097 continue;
6098 }
6099
Andy Hung73c02e42015-03-29 01:13:58 -07006100 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07006101 // TODO: Update the activeTrack buffer converter in case of reconfigure.
6102
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006103 enum {
6104 OVERRUN_UNKNOWN,
6105 OVERRUN_TRUE,
6106 OVERRUN_FALSE
6107 } overrun = OVERRUN_UNKNOWN;
6108
6109 // loop over getNextBuffer to handle circular sink
6110 for (;;) {
6111
6112 activeTrack->mSink.frameCount = ~0;
6113 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
6114 size_t framesOut = activeTrack->mSink.frameCount;
6115 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
6116
Andy Hung73c02e42015-03-29 01:13:58 -07006117 // check available frames and handle overrun conditions
6118 // if the record track isn't draining fast enough.
6119 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006120 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07006121 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
6122 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006123 overrun = OVERRUN_TRUE;
6124 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006125 if (framesOut == 0 || framesIn == 0) {
6126 break;
6127 }
6128
Andy Hung6770c6f2015-04-07 13:43:36 -07006129 // Don't allow framesOut to be larger than what is possible with resampling
6130 // from framesIn.
6131 // This isn't strictly necessary but helps limit buffer resizing in
6132 // RecordBufferConverter. TODO: remove when no longer needed.
6133 framesOut = min(framesOut,
6134 destinationFramesPossible(
6135 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07006136 // process frames from the RecordThread buffer provider to the RecordTrack buffer
6137 framesOut = activeTrack->mRecordBufferConverter->convert(
6138 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006139
6140 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
6141 overrun = OVERRUN_FALSE;
6142 }
6143
6144 if (activeTrack->mFramesToDrop == 0) {
6145 if (framesOut > 0) {
6146 activeTrack->mSink.frameCount = framesOut;
6147 activeTrack->releaseBuffer(&activeTrack->mSink);
6148 }
6149 } else {
6150 // FIXME could do a partial drop of framesOut
6151 if (activeTrack->mFramesToDrop > 0) {
6152 activeTrack->mFramesToDrop -= framesOut;
6153 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006154 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006155 }
6156 } else {
6157 activeTrack->mFramesToDrop += framesOut;
6158 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
6159 activeTrack->mSyncStartEvent->isCancelled()) {
6160 ALOGW("Synced record %s, session %d, trigger session %d",
6161 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
6162 activeTrack->sessionId(),
6163 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08006164 activeTrack->mSyncStartEvent->triggerSession() :
6165 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006166 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006167 }
6168 }
6169 }
6170
6171 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006172 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006173 }
6174 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006175
6176 switch (overrun) {
6177 case OVERRUN_TRUE:
6178 // client isn't retrieving buffers fast enough
6179 if (!activeTrack->setOverflow()) {
6180 nsecs_t now = systemTime();
6181 // FIXME should lastWarning per track?
6182 if ((now - lastWarning) > kWarningThrottleNs) {
6183 ALOGW("RecordThread: buffer overflow");
6184 lastWarning = now;
6185 }
6186 }
6187 break;
6188 case OVERRUN_FALSE:
6189 activeTrack->clearOverflow();
6190 break;
6191 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006192 break;
6193 }
6194
Andy Hung3f0c9022016-01-15 17:49:46 -08006195 // update frame information and push timestamp out
6196 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08006197 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08006198 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
6199 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006200 }
6201
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006202unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08006203 // enable changes in effect chain
6204 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006205 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08006206 }
6207
Glenn Kasten93e471f2013-08-19 08:40:07 -07006208 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08006209
6210 {
6211 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07006212 for (size_t i = 0; i < mTracks.size(); i++) {
6213 sp<RecordTrack> track = mTracks[i];
6214 track->invalidate();
6215 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006216 mActiveTracks.clear();
6217 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08006218 mStartStopCond.broadcast();
6219 }
6220
6221 releaseWakeLock();
6222
6223 ALOGV("RecordThread %p exiting", this);
6224 return false;
6225}
6226
Glenn Kasten93e471f2013-08-19 08:40:07 -07006227void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08006228{
6229 if (!mStandby) {
6230 inputStandBy();
6231 mStandby = true;
6232 }
6233}
6234
6235void AudioFlinger::RecordThread::inputStandBy()
6236{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006237 // Idle the fast capture if it's currently running
6238 if (mFastCapture != 0) {
6239 FastCaptureStateQueue *sq = mFastCapture->sq();
6240 FastCaptureState *state = sq->begin();
6241 if (!(state->mCommand & FastCaptureState::IDLE)) {
6242 state->mCommand = FastCaptureState::COLD_IDLE;
6243 state->mColdFutexAddr = &mFastCaptureFutex;
6244 state->mColdGen++;
6245 mFastCaptureFutex = 0;
6246 sq->end();
6247 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
6248 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
6249#if 0
6250 if (kUseFastCapture == FastCapture_Dynamic) {
6251 // FIXME
6252 }
6253#endif
6254#ifdef AUDIO_WATCHDOG
6255 // FIXME
6256#endif
6257 } else {
6258 sq->end(false /*didModify*/);
6259 }
6260 }
Eric Laurent81784c32012-11-19 14:55:58 -08006261 mInput->stream->common.standby(&mInput->stream->common);
6262}
6263
Glenn Kasten05997e22014-03-13 15:08:33 -07006264// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07006265sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08006266 const sp<AudioFlinger::Client>& client,
6267 uint32_t sampleRate,
6268 audio_format_t format,
6269 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08006270 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08006271 audio_session_t sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07006272 size_t *notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006273 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07006274 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08006275 pid_t tid,
6276 status_t *status)
6277{
Glenn Kasten74935e42013-12-19 08:56:45 -08006278 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08006279 sp<RecordTrack> track;
6280 status_t lStatus;
6281
Glenn Kasten90e58b12013-07-31 16:16:02 -07006282 // client expresses a preference for FAST, but we get the final say
6283 if (*flags & IAudioFlinger::TRACK_FAST) {
6284 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07006285 // we formerly checked for a callback handler (non-0 tid),
6286 // but that is no longer required for TRANSFER_OBTAIN mode
6287 //
Glenn Kasten74105912014-07-03 12:28:53 -07006288 // frame count is not specified, or is exactly the pipe depth
6289 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006290 // PCM data
6291 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006292 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006293 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006294 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006295 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006296 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07006297 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006298 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006299 hasFastCapture() &&
6300 // there are sufficient fast track slots available
6301 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07006302 ) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006303 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
Glenn Kasten90e58b12013-07-31 16:16:02 -07006304 frameCount, mFrameCount);
6305 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006306 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
Glenn Kasten74105912014-07-03 12:28:53 -07006307 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006308 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07006309 frameCount, mFrameCount, mPipeFramesP2,
6310 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
6311 hasFastCapture(), tid, mFastTrackAvail);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006312 *flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kasten74105912014-07-03 12:28:53 -07006313 }
6314 }
6315
6316 // compute track buffer size in frames, and suggest the notification frame count
6317 if (*flags & IAudioFlinger::TRACK_FAST) {
6318 // fast track: frame count is exactly the pipe depth
6319 frameCount = mPipeFramesP2;
6320 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
6321 *notificationFrames = mFrameCount;
6322 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006323 // not fast track: max notification period is resampled equivalent of one HAL buffer time
6324 // or 20 ms if there is a fast capture
6325 // TODO This could be a roundupRatio inline, and const
6326 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
6327 * sampleRate + mSampleRate - 1) / mSampleRate;
6328 // minimum number of notification periods is at least kMinNotifications,
6329 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
6330 static const size_t kMinNotifications = 3;
6331 static const uint32_t kMinMs = 30;
6332 // TODO This could be a roundupRatio inline
6333 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
6334 // TODO This could be a roundupRatio inline
6335 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
6336 maxNotificationFrames;
6337 const size_t minFrameCount = maxNotificationFrames *
6338 max(kMinNotifications, minNotificationsByMs);
6339 frameCount = max(frameCount, minFrameCount);
6340 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
6341 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07006342 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07006343 }
Glenn Kasten74935e42013-12-19 08:56:45 -08006344 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07006345
Glenn Kasten15e57982013-09-24 11:52:37 -07006346 lStatus = initCheck();
6347 if (lStatus != NO_ERROR) {
6348 ALOGE("createRecordTrack_l() audio driver not initialized");
6349 goto Exit;
6350 }
Eric Laurent81784c32012-11-19 14:55:58 -08006351
6352 { // scope for mLock
6353 Mutex::Autolock _l(mLock);
6354
6355 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07006356 format, channelMask, frameCount, NULL, sessionId, uid,
6357 *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08006358
Glenn Kasten03003332013-08-06 15:40:54 -07006359 lStatus = track->initCheck();
6360 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07006361 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08006362 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08006363 goto Exit;
6364 }
6365 mTracks.add(track);
6366
6367 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6368 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6369 mAudioFlinger->btNrecIsOff();
6370 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6371 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006372
6373 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
6374 pid_t callingPid = IPCThreadState::self()->getCallingPid();
6375 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
6376 // so ask activity manager to do this on our behalf
6377 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
6378 }
Eric Laurent81784c32012-11-19 14:55:58 -08006379 }
Glenn Kasten05997e22014-03-13 15:08:33 -07006380
Eric Laurent81784c32012-11-19 14:55:58 -08006381 lStatus = NO_ERROR;
6382
6383Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07006384 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08006385 return track;
6386}
6387
6388status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6389 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08006390 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08006391{
6392 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6393 sp<ThreadBase> strongMe = this;
6394 status_t status = NO_ERROR;
6395
6396 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006397 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006398 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006399 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08006400 triggerSession,
6401 recordTrack->sessionId(),
6402 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006403 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08006404 // Sync event can be cancelled by the trigger session if the track is not in a
6405 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006406 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006407 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006408 } else {
6409 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006410 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006411 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08006412 }
6413 }
6414
6415 {
Glenn Kasten47c20702013-08-13 15:37:35 -07006416 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08006417 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006418 if (mActiveTracks.indexOf(recordTrack) >= 0) {
6419 if (recordTrack->mState == TrackBase::PAUSING) {
6420 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006421 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006422 } else {
6423 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08006424 }
6425 return status;
6426 }
6427
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006428 // TODO consider other ways of handling this, such as changing the state to :STARTING and
6429 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6430 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006431 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08006432 mActiveTracks.add(recordTrack);
6433 mActiveTracksGen++;
Eric Laurent83b88082014-06-20 18:31:16 -07006434 status_t status = NO_ERROR;
6435 if (recordTrack->isExternalTrack()) {
6436 mLock.unlock();
Glenn Kastend848eb42016-03-08 13:42:11 -08006437 status = AudioSystem::startInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006438 mLock.lock();
6439 // FIXME should verify that recordTrack is still in mActiveTracks
6440 if (status != NO_ERROR) {
6441 mActiveTracks.remove(recordTrack);
6442 mActiveTracksGen++;
6443 recordTrack->clearSyncStartEvent();
6444 ALOGV("RecordThread::start error %d", status);
6445 return status;
6446 }
Eric Laurent81784c32012-11-19 14:55:58 -08006447 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006448 // Catch up with current buffer indices if thread is already running.
6449 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
6450 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6451 // see previously buffered data before it called start(), but with greater risk of overrun.
6452
Andy Hung73c02e42015-03-29 01:13:58 -07006453 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07006454 // clear any converter state as new data will be discontinuous
6455 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006456 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08006457 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08006458 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08006459 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006460 ALOGV("Record failed to start");
6461 status = BAD_VALUE;
6462 goto startError;
6463 }
Eric Laurent81784c32012-11-19 14:55:58 -08006464 return status;
6465 }
Glenn Kasten7c027242012-12-26 14:43:16 -08006466
Eric Laurent81784c32012-11-19 14:55:58 -08006467startError:
Eric Laurent83b88082014-06-20 18:31:16 -07006468 if (recordTrack->isExternalTrack()) {
Glenn Kastend848eb42016-03-08 13:42:11 -08006469 AudioSystem::stopInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006470 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006471 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006472 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08006473 return status;
6474}
6475
Eric Laurent81784c32012-11-19 14:55:58 -08006476void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6477{
6478 sp<SyncEvent> strongEvent = event.promote();
6479
6480 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08006481 sp<RefBase> ptr = strongEvent->cookie().promote();
6482 if (ptr != 0) {
6483 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6484 recordTrack->handleSyncStartEvent(strongEvent);
6485 }
Eric Laurent81784c32012-11-19 14:55:58 -08006486 }
6487}
6488
Glenn Kastena8356f62013-07-25 14:37:52 -07006489bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08006490 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07006491 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006492 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08006493 return false;
6494 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006495 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006496 recordTrack->mState = TrackBase::PAUSING;
6497 // do not wait for mStartStopCond if exiting
6498 if (exitPending()) {
6499 return true;
6500 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006501 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08006502 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006503 // if we have been restarted, recordTrack is in mActiveTracks here
6504 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006505 ALOGV("Record stopped OK");
6506 return true;
6507 }
6508 return false;
6509}
6510
Glenn Kasten0f11b512014-01-31 16:18:54 -08006511bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08006512{
6513 return false;
6514}
6515
Glenn Kasten0f11b512014-01-31 16:18:54 -08006516status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006517{
6518#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6519 if (!isValidSyncEvent(event)) {
6520 return BAD_VALUE;
6521 }
6522
Glenn Kastend848eb42016-03-08 13:42:11 -08006523 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08006524 status_t ret = NAME_NOT_FOUND;
6525
6526 Mutex::Autolock _l(mLock);
6527
6528 for (size_t i = 0; i < mTracks.size(); i++) {
6529 sp<RecordTrack> track = mTracks[i];
6530 if (eventSession == track->sessionId()) {
6531 (void) track->setSyncEvent(event);
6532 ret = NO_ERROR;
6533 }
6534 }
6535 return ret;
6536#else
6537 return BAD_VALUE;
6538#endif
6539}
6540
6541// destroyTrack_l() must be called with ThreadBase::mLock held
6542void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6543{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006544 track->terminate();
6545 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006546 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006547 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006548 removeTrack_l(track);
6549 }
6550}
6551
6552void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6553{
6554 mTracks.remove(track);
6555 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006556 if (track->isFastTrack()) {
6557 ALOG_ASSERT(!mFastTrackAvail);
6558 mFastTrackAvail = true;
6559 }
Eric Laurent81784c32012-11-19 14:55:58 -08006560}
6561
6562void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6563{
6564 dumpInternals(fd, args);
6565 dumpTracks(fd, args);
6566 dumpEffectChains(fd, args);
6567}
6568
6569void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6570{
Elliott Hughes87cebad2014-05-22 10:14:43 -07006571 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08006572
Glenn Kasten44182c22015-03-05 17:12:23 -08006573 dumpBase(fd, args);
6574
6575 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006576 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006577 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006578 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006579 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08006580
Glenn Kasten2f90c512015-12-02 11:40:09 -08006581 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
6582 // while we are dumping it. It may be inconsistent, but it won't mutate!
6583 // This is a large object so we place it on the heap.
6584 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
6585 const FastCaptureDumpState *copy = new FastCaptureDumpState(mFastCaptureDumpState);
6586 copy->dump(fd);
6587 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08006588}
6589
Glenn Kasten0f11b512014-01-31 16:18:54 -08006590void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006591{
6592 const size_t SIZE = 256;
6593 char buffer[SIZE];
6594 String8 result;
6595
Marco Nelissenb2208842014-02-07 14:00:50 -08006596 size_t numtracks = mTracks.size();
6597 size_t numactive = mActiveTracks.size();
6598 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006599 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006600 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006601 dprintf(fd, " of which %zu are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006602 RecordTrack::appendDumpHeader(result);
6603 for (size_t i = 0; i < numtracks ; ++i) {
6604 sp<RecordTrack> track = mTracks[i];
6605 if (track != 0) {
6606 bool active = mActiveTracks.indexOf(track) >= 0;
6607 if (active) {
6608 numactiveseen++;
6609 }
6610 track->dump(buffer, SIZE, active);
6611 result.append(buffer);
6612 }
Eric Laurent81784c32012-11-19 14:55:58 -08006613 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006614 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006615 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006616 }
6617
Marco Nelissenb2208842014-02-07 14:00:50 -08006618 if (numactiveseen != numactive) {
6619 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6620 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006621 result.append(buffer);
6622 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006623 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006624 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006625 if (mTracks.indexOf(track) < 0) {
6626 track->dump(buffer, SIZE, true);
6627 result.append(buffer);
6628 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006629 }
Eric Laurent81784c32012-11-19 14:55:58 -08006630
6631 }
6632 write(fd, result.string(), result.size());
6633}
6634
Andy Hung73c02e42015-03-29 01:13:58 -07006635
6636void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
6637{
6638 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6639 RecordThread *recordThread = (RecordThread *) threadBase.get();
6640 mRsmpInFront = recordThread->mRsmpInRear;
6641 mRsmpInUnrel = 0;
6642}
6643
6644void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
6645 size_t *framesAvailable, bool *hasOverrun)
6646{
6647 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6648 RecordThread *recordThread = (RecordThread *) threadBase.get();
6649 const int32_t rear = recordThread->mRsmpInRear;
6650 const int32_t front = mRsmpInFront;
6651 const ssize_t filled = rear - front;
6652
6653 size_t framesIn;
6654 bool overrun = false;
6655 if (filled < 0) {
6656 // should not happen, but treat like a massive overrun and re-sync
6657 framesIn = 0;
6658 mRsmpInFront = rear;
6659 overrun = true;
6660 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
6661 framesIn = (size_t) filled;
6662 } else {
6663 // client is not keeping up with server, but give it latest data
6664 framesIn = recordThread->mRsmpInFrames;
6665 mRsmpInFront = /* front = */ rear - framesIn;
6666 overrun = true;
6667 }
6668 if (framesAvailable != NULL) {
6669 *framesAvailable = framesIn;
6670 }
6671 if (hasOverrun != NULL) {
6672 *hasOverrun = overrun;
6673 }
6674}
6675
Eric Laurent81784c32012-11-19 14:55:58 -08006676// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006677status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08006678 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006679{
Andy Hung73c02e42015-03-29 01:13:58 -07006680 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006681 if (threadBase == 0) {
6682 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006683 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006684 return NOT_ENOUGH_DATA;
6685 }
6686 RecordThread *recordThread = (RecordThread *) threadBase.get();
6687 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07006688 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07006689 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006690 // FIXME should not be P2 (don't want to increase latency)
6691 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006692 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07006693 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006694 front &= recordThread->mRsmpInFramesP2 - 1;
6695 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07006696 if (part1 > (size_t) filled) {
6697 part1 = filled;
6698 }
6699 size_t ask = buffer->frameCount;
6700 ALOG_ASSERT(ask > 0);
6701 if (part1 > ask) {
6702 part1 = ask;
6703 }
6704 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07006705 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07006706 buffer->raw = NULL;
6707 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07006708 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07006709 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08006710 }
6711
Andy Hung57446612015-04-19 23:56:46 -07006712 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07006713 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07006714 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08006715 return NO_ERROR;
6716}
6717
6718// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006719void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
6720 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006721{
Glenn Kasten85948432013-08-19 12:09:05 -07006722 size_t stepCount = buffer->frameCount;
6723 if (stepCount == 0) {
6724 return;
6725 }
Andy Hung73c02e42015-03-29 01:13:58 -07006726 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
6727 mRsmpInUnrel -= stepCount;
6728 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006729 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006730 buffer->frameCount = 0;
6731}
6732
Andy Hung97a893e2015-03-29 01:03:07 -07006733AudioFlinger::RecordThread::RecordBufferConverter::RecordBufferConverter(
6734 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6735 uint32_t srcSampleRate,
6736 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6737 uint32_t dstSampleRate) :
6738 mSrcChannelMask(AUDIO_CHANNEL_INVALID), // updateParameters will set following vars
6739 // mSrcFormat
6740 // mSrcSampleRate
6741 // mDstChannelMask
6742 // mDstFormat
6743 // mDstSampleRate
6744 // mSrcChannelCount
6745 // mDstChannelCount
6746 // mDstFrameSize
6747 mBuf(NULL), mBufFrames(0), mBufFrameSize(0),
Andy Hungd330ee42015-04-20 13:23:41 -07006748 mResampler(NULL),
6749 mIsLegacyDownmix(false),
6750 mIsLegacyUpmix(false),
6751 mRequiresFloat(false),
6752 mInputConverterProvider(NULL)
Andy Hung97a893e2015-03-29 01:03:07 -07006753{
6754 (void)updateParameters(srcChannelMask, srcFormat, srcSampleRate,
6755 dstChannelMask, dstFormat, dstSampleRate);
6756}
6757
6758AudioFlinger::RecordThread::RecordBufferConverter::~RecordBufferConverter() {
6759 free(mBuf);
6760 delete mResampler;
Andy Hungd330ee42015-04-20 13:23:41 -07006761 delete mInputConverterProvider;
Andy Hung97a893e2015-03-29 01:03:07 -07006762}
6763
6764size_t AudioFlinger::RecordThread::RecordBufferConverter::convert(void *dst,
6765 AudioBufferProvider *provider, size_t frames)
6766{
Andy Hungd330ee42015-04-20 13:23:41 -07006767 if (mInputConverterProvider != NULL) {
6768 mInputConverterProvider->setBufferProvider(provider);
6769 provider = mInputConverterProvider;
6770 }
6771
6772 if (mResampler == NULL) {
Andy Hung97a893e2015-03-29 01:03:07 -07006773 ALOGVV("NO RESAMPLING sampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6774 mSrcSampleRate, mSrcFormat, mDstFormat);
6775
6776 AudioBufferProvider::Buffer buffer;
6777 for (size_t i = frames; i > 0; ) {
6778 buffer.frameCount = i;
Glenn Kastend79072e2016-01-06 08:41:20 -08006779 status_t status = provider->getNextBuffer(&buffer);
Andy Hung97a893e2015-03-29 01:03:07 -07006780 if (status != OK || buffer.frameCount == 0) {
6781 frames -= i; // cannot fill request.
6782 break;
6783 }
Andy Hungd330ee42015-04-20 13:23:41 -07006784 // format convert to destination buffer
6785 convertNoResampler(dst, buffer.raw, buffer.frameCount);
Andy Hung97a893e2015-03-29 01:03:07 -07006786
6787 dst = (int8_t*)dst + buffer.frameCount * mDstFrameSize;
6788 i -= buffer.frameCount;
6789 provider->releaseBuffer(&buffer);
6790 }
6791 } else {
6792 ALOGVV("RESAMPLING mSrcSampleRate:%u mDstSampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6793 mSrcSampleRate, mDstSampleRate, mSrcFormat, mDstFormat);
6794
Andy Hungd330ee42015-04-20 13:23:41 -07006795 // reallocate buffer if needed
6796 if (mBufFrameSize != 0 && mBufFrames < frames) {
6797 free(mBuf);
6798 mBufFrames = frames;
6799 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6800 }
Andy Hung97a893e2015-03-29 01:03:07 -07006801 // resampler accumulates, but we only have one source track
Andy Hungd330ee42015-04-20 13:23:41 -07006802 memset(mBuf, 0, frames * mBufFrameSize);
6803 frames = mResampler->resample((int32_t*)mBuf, frames, provider);
6804 // format convert to destination buffer
6805 convertResampler(dst, mBuf, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006806 }
6807 return frames;
6808}
6809
6810status_t AudioFlinger::RecordThread::RecordBufferConverter::updateParameters(
6811 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6812 uint32_t srcSampleRate,
6813 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6814 uint32_t dstSampleRate)
6815{
6816 // quick evaluation if there is any change.
6817 if (mSrcFormat == srcFormat
6818 && mSrcChannelMask == srcChannelMask
6819 && mSrcSampleRate == srcSampleRate
6820 && mDstFormat == dstFormat
6821 && mDstChannelMask == dstChannelMask
6822 && mDstSampleRate == dstSampleRate) {
6823 return NO_ERROR;
6824 }
6825
Andy Hungdb4c0312015-05-06 08:46:52 -07006826 ALOGV("RecordBufferConverter updateParameters srcMask:%#x dstMask:%#x"
6827 " srcFormat:%#x dstFormat:%#x srcRate:%u dstRate:%u",
6828 srcChannelMask, dstChannelMask, srcFormat, dstFormat, srcSampleRate, dstSampleRate);
Andy Hung97a893e2015-03-29 01:03:07 -07006829 const bool valid =
6830 audio_is_input_channel(srcChannelMask)
6831 && audio_is_input_channel(dstChannelMask)
6832 && audio_is_valid_format(srcFormat) && audio_is_linear_pcm(srcFormat)
6833 && audio_is_valid_format(dstFormat) && audio_is_linear_pcm(dstFormat)
6834 && (srcSampleRate <= dstSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX)
6835 ; // no upsampling checks for now
6836 if (!valid) {
6837 return BAD_VALUE;
6838 }
6839
6840 mSrcFormat = srcFormat;
6841 mSrcChannelMask = srcChannelMask;
6842 mSrcSampleRate = srcSampleRate;
6843 mDstFormat = dstFormat;
6844 mDstChannelMask = dstChannelMask;
6845 mDstSampleRate = dstSampleRate;
6846
6847 // compute derived parameters
6848 mSrcChannelCount = audio_channel_count_from_in_mask(srcChannelMask);
6849 mDstChannelCount = audio_channel_count_from_in_mask(dstChannelMask);
6850 mDstFrameSize = mDstChannelCount * audio_bytes_per_sample(mDstFormat);
6851
Andy Hungd330ee42015-04-20 13:23:41 -07006852 // do we need to resample?
6853 delete mResampler;
6854 mResampler = NULL;
6855 if (mSrcSampleRate != mDstSampleRate) {
6856 mResampler = AudioResampler::create(AUDIO_FORMAT_PCM_FLOAT,
6857 mSrcChannelCount, mDstSampleRate);
6858 mResampler->setSampleRate(mSrcSampleRate);
6859 mResampler->setVolume(AudioMixer::UNITY_GAIN_FLOAT, AudioMixer::UNITY_GAIN_FLOAT);
6860 }
6861
6862 // are we running legacy channel conversion modes?
6863 mIsLegacyDownmix = (mSrcChannelMask == AUDIO_CHANNEL_IN_STEREO
6864 || mSrcChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK)
6865 && mDstChannelMask == AUDIO_CHANNEL_IN_MONO;
6866 mIsLegacyUpmix = mSrcChannelMask == AUDIO_CHANNEL_IN_MONO
6867 && (mDstChannelMask == AUDIO_CHANNEL_IN_STEREO
6868 || mDstChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK);
6869
6870 // do we need to process in float?
6871 mRequiresFloat = mResampler != NULL || mIsLegacyDownmix || mIsLegacyUpmix;
6872
6873 // do we need a staging buffer to convert for destination (we can still optimize this)?
6874 // we use mBufFrameSize > 0 to indicate both frame size as well as buffer necessity
6875 if (mResampler != NULL) {
6876 mBufFrameSize = max(mSrcChannelCount, FCC_2)
6877 * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
Andy Hunga97630b2015-07-22 23:27:24 -07006878 } else if (mIsLegacyUpmix || mIsLegacyDownmix) { // legacy modes always float
Andy Hungd330ee42015-04-20 13:23:41 -07006879 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
6880 } else if (mSrcChannelMask != mDstChannelMask && mDstFormat != mSrcFormat) {
Andy Hung97a893e2015-03-29 01:03:07 -07006881 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(mSrcFormat);
6882 } else {
6883 mBufFrameSize = 0;
6884 }
6885 mBufFrames = 0; // force the buffer to be resized.
6886
Andy Hungd330ee42015-04-20 13:23:41 -07006887 // do we need an input converter buffer provider to give us float?
6888 delete mInputConverterProvider;
6889 mInputConverterProvider = NULL;
6890 if (mRequiresFloat && mSrcFormat != AUDIO_FORMAT_PCM_FLOAT) {
6891 mInputConverterProvider = new ReformatBufferProvider(
6892 audio_channel_count_from_in_mask(mSrcChannelMask),
6893 mSrcFormat,
6894 AUDIO_FORMAT_PCM_FLOAT,
6895 256 /* provider buffer frame count */);
6896 }
6897
6898 // do we need a remixer to do channel mask conversion
6899 if (!mIsLegacyDownmix && !mIsLegacyUpmix && mSrcChannelMask != mDstChannelMask) {
6900 (void) memcpy_by_index_array_initialization_from_channel_mask(
6901 mIdxAry, ARRAY_SIZE(mIdxAry), mDstChannelMask, mSrcChannelMask);
Andy Hung97a893e2015-03-29 01:03:07 -07006902 }
6903 return NO_ERROR;
6904}
6905
Andy Hungd330ee42015-04-20 13:23:41 -07006906void AudioFlinger::RecordThread::RecordBufferConverter::convertNoResampler(
6907 void *dst, const void *src, size_t frames)
Andy Hung97a893e2015-03-29 01:03:07 -07006908{
Andy Hungd330ee42015-04-20 13:23:41 -07006909 // src is native type unless there is legacy upmix or downmix, whereupon it is float.
Andy Hung97a893e2015-03-29 01:03:07 -07006910 if (mBufFrameSize != 0 && mBufFrames < frames) {
6911 free(mBuf);
6912 mBufFrames = frames;
6913 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6914 }
Andy Hungd330ee42015-04-20 13:23:41 -07006915 // do we need to do legacy upmix and downmix?
6916 if (mIsLegacyUpmix || mIsLegacyDownmix) {
Andy Hung97a893e2015-03-29 01:03:07 -07006917 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07006918 if (mIsLegacyUpmix) {
6919 upmix_to_stereo_float_from_mono_float((float *)dstBuf,
6920 (const float *)src, frames);
6921 } else /*mIsLegacyDownmix */ {
6922 downmix_to_mono_float_from_stereo_float((float *)dstBuf,
6923 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006924 }
Andy Hungd330ee42015-04-20 13:23:41 -07006925 if (mBuf != NULL) {
6926 memcpy_by_audio_format(dst, mDstFormat, mBuf, AUDIO_FORMAT_PCM_FLOAT,
6927 frames * mDstChannelCount);
6928 }
6929 return;
6930 }
6931 // do we need to do channel mask conversion?
6932 if (mSrcChannelMask != mDstChannelMask) {
Andy Hung97a893e2015-03-29 01:03:07 -07006933 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07006934 memcpy_by_index_array(dstBuf, mDstChannelCount,
6935 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mSrcFormat), frames);
6936 if (dstBuf == dst) {
6937 return; // format is the same
6938 }
6939 }
6940 // convert to destination buffer
6941 const void *convertBuf = mBuf != NULL ? mBuf : src;
6942 memcpy_by_audio_format(dst, mDstFormat, convertBuf, mSrcFormat,
6943 frames * mDstChannelCount);
6944}
6945
6946void AudioFlinger::RecordThread::RecordBufferConverter::convertResampler(
6947 void *dst, /*not-a-const*/ void *src, size_t frames)
6948{
6949 // src buffer format is ALWAYS float when entering this routine
6950 if (mIsLegacyUpmix) {
6951 ; // mono to stereo already handled by resampler
6952 } else if (mIsLegacyDownmix
6953 || (mSrcChannelMask == mDstChannelMask && mSrcChannelCount == 1)) {
6954 // the resampler outputs stereo for mono input channel (a feature?)
6955 // must convert to mono
6956 downmix_to_mono_float_from_stereo_float((float *)src,
6957 (const float *)src, frames);
6958 } else if (mSrcChannelMask != mDstChannelMask) {
6959 // convert to mono channel again for channel mask conversion (could be skipped
6960 // with further optimization).
Andy Hung97a893e2015-03-29 01:03:07 -07006961 if (mSrcChannelCount == 1) {
Andy Hungd330ee42015-04-20 13:23:41 -07006962 downmix_to_mono_float_from_stereo_float((float *)src,
6963 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006964 }
Andy Hungd330ee42015-04-20 13:23:41 -07006965 // convert to destination format (in place, OK as float is larger than other types)
6966 if (mDstFormat != AUDIO_FORMAT_PCM_FLOAT) {
6967 memcpy_by_audio_format(src, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
6968 frames * mSrcChannelCount);
6969 }
6970 // channel convert and save to dst
6971 memcpy_by_index_array(dst, mDstChannelCount,
6972 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mDstFormat), frames);
6973 return;
Andy Hung97a893e2015-03-29 01:03:07 -07006974 }
Andy Hungd330ee42015-04-20 13:23:41 -07006975 // convert to destination format and save to dst
6976 memcpy_by_audio_format(dst, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
6977 frames * mDstChannelCount);
Andy Hung97a893e2015-03-29 01:03:07 -07006978}
6979
Eric Laurent10351942014-05-08 18:49:52 -07006980bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
6981 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006982{
6983 bool reconfig = false;
6984
Eric Laurent10351942014-05-08 18:49:52 -07006985 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006986
Eric Laurent10351942014-05-08 18:49:52 -07006987 audio_format_t reqFormat = mFormat;
6988 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07006989 // 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 -07006990 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
6991
6992 AudioParameter param = AudioParameter(keyValuePair);
6993 int value;
6994 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
6995 // channel count change can be requested. Do we mandate the first client defines the
6996 // HAL sampling rate and channel count or do we allow changes on the fly?
6997 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6998 samplingRate = value;
6999 reconfig = true;
7000 }
7001 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07007002 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07007003 status = BAD_VALUE;
7004 } else {
7005 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08007006 reconfig = true;
7007 }
Eric Laurent10351942014-05-08 18:49:52 -07007008 }
7009 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
7010 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07007011 if (!audio_is_input_channel(mask) ||
7012 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007013 status = BAD_VALUE;
7014 } else {
7015 channelMask = mask;
7016 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007017 }
Eric Laurent10351942014-05-08 18:49:52 -07007018 }
7019 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7020 // do not accept frame count changes if tracks are open as the track buffer
7021 // size depends on frame count and correct behavior would not be guaranteed
7022 // if frame count is changed after track creation
7023 if (mActiveTracks.size() > 0) {
7024 status = INVALID_OPERATION;
7025 } else {
7026 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007027 }
Eric Laurent10351942014-05-08 18:49:52 -07007028 }
7029 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7030 // forward device change to effects that have requested to be
7031 // aware of attached audio device.
7032 for (size_t i = 0; i < mEffectChains.size(); i++) {
7033 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08007034 }
Eric Laurent81784c32012-11-19 14:55:58 -08007035
Eric Laurent10351942014-05-08 18:49:52 -07007036 // store input device and output device but do not forward output device to audio HAL.
7037 // Note that status is ignored by the caller for output device
7038 // (see AudioFlinger::setParameters()
7039 if (audio_is_output_devices(value)) {
7040 mOutDevice = value;
7041 status = BAD_VALUE;
7042 } else {
7043 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07007044 if (value != AUDIO_DEVICE_NONE) {
7045 mPrevInDevice = value;
7046 }
Eric Laurent10351942014-05-08 18:49:52 -07007047 // disable AEC and NS if the device is a BT SCO headset supporting those
7048 // pre processings
7049 if (mTracks.size() > 0) {
7050 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7051 mAudioFlinger->btNrecIsOff();
7052 for (size_t i = 0; i < mTracks.size(); i++) {
7053 sp<RecordTrack> track = mTracks[i];
7054 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7055 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08007056 }
7057 }
7058 }
Eric Laurent10351942014-05-08 18:49:52 -07007059 }
7060 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
7061 mAudioSource != (audio_source_t)value) {
7062 // forward device change to effects that have requested to be
7063 // aware of attached audio device.
7064 for (size_t i = 0; i < mEffectChains.size(); i++) {
7065 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08007066 }
Eric Laurent10351942014-05-08 18:49:52 -07007067 mAudioSource = (audio_source_t)value;
7068 }
Glenn Kastene198c362013-08-13 09:13:36 -07007069
Eric Laurent10351942014-05-08 18:49:52 -07007070 if (status == NO_ERROR) {
7071 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7072 keyValuePair.string());
7073 if (status == INVALID_OPERATION) {
7074 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08007075 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7076 keyValuePair.string());
Eric Laurent10351942014-05-08 18:49:52 -07007077 }
7078 if (reconfig) {
7079 if (status == BAD_VALUE &&
Andy Hung97a893e2015-03-29 01:03:07 -07007080 audio_is_linear_pcm(mInput->stream->common.get_format(&mInput->stream->common)) &&
7081 audio_is_linear_pcm(reqFormat) &&
Eric Laurent10351942014-05-08 18:49:52 -07007082 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
Andy Hung97a893e2015-03-29 01:03:07 -07007083 <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate)) &&
Andy Hunge5412692014-05-16 11:25:07 -07007084 audio_channel_count_from_in_mask(
Andy Hungd1abb8f2015-05-05 23:42:34 -07007085 mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007086 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007087 }
Eric Laurent10351942014-05-08 18:49:52 -07007088 if (status == NO_ERROR) {
7089 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007090 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08007091 }
7092 }
Eric Laurent81784c32012-11-19 14:55:58 -08007093 }
Eric Laurent10351942014-05-08 18:49:52 -07007094
Eric Laurent81784c32012-11-19 14:55:58 -08007095 return reconfig;
7096}
7097
7098String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
7099{
Eric Laurent81784c32012-11-19 14:55:58 -08007100 Mutex::Autolock _l(mLock);
7101 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07007102 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08007103 }
7104
Glenn Kastend8ea6992013-07-16 14:17:15 -07007105 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
7106 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08007107 free(s);
7108 return out_s8;
7109}
7110
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007111void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007112 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7113
7114 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08007115
7116 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007117 case AUDIO_INPUT_OPENED:
7118 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07007119 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07007120 desc->mChannelMask = mChannelMask;
7121 desc->mSamplingRate = mSampleRate;
7122 desc->mFormat = mFormat;
7123 desc->mFrameCount = mFrameCount;
7124 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007125 break;
7126
Eric Laurent73e26b62015-04-27 16:55:58 -07007127 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08007128 default:
7129 break;
7130 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007131 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08007132}
7133
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007134void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007135{
Eric Laurent81784c32012-11-19 14:55:58 -08007136 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
7137 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Andy Hunge5412692014-05-16 11:25:07 -07007138 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Andy Hungd330ee42015-04-20 13:23:41 -07007139 if (mChannelCount > FCC_8) {
7140 ALOGE("HAL channel count %d > %d", mChannelCount, FCC_8);
7141 }
Andy Hung463be252014-07-10 16:56:07 -07007142 mHALFormat = mInput->stream->common.get_format(&mInput->stream->common);
7143 mFormat = mHALFormat;
Andy Hungd330ee42015-04-20 13:23:41 -07007144 if (!audio_is_linear_pcm(mFormat)) {
7145 ALOGE("HAL format %#x is not linear pcm", mFormat);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07007146 }
Eric Laurent665470b2014-07-03 16:37:08 -07007147 mFrameSize = audio_stream_in_frame_size(mInput->stream);
Glenn Kasten548efc92012-11-29 08:48:51 -08007148 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
7149 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007150 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08007151 // 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 -07007152 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08007153 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007154 // A larger value should allow more old data to be read after a track calls start(),
7155 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07007156 //
7157 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08007158 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07007159 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07007160 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07007161 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007162
7163 // TODO optimize audio capture buffer sizes ...
7164 // Here we calculate the size of the sliding buffer used as a source
7165 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
7166 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
7167 // be better to have it derived from the pipe depth in the long term.
7168 // The current value is higher than necessary. However it should not add to latency.
7169
Glenn Kasten85948432013-08-19 12:09:05 -07007170 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Andy Hung0a01c2f2015-09-21 12:44:54 -07007171 size_t bufferSize = (mRsmpInFramesP2 + mFrameCount - 1) * mFrameSize;
7172 (void)posix_memalign(&mRsmpInBuffer, 32, bufferSize);
7173 memset(mRsmpInBuffer, 0, bufferSize); // if posix_memalign fails, will segv here.
Eric Laurent81784c32012-11-19 14:55:58 -08007174
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007175 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
7176 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08007177}
7178
Glenn Kasten5f972c02014-01-13 09:59:31 -08007179uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08007180{
7181 Mutex::Autolock _l(mLock);
7182 if (initCheck() != NO_ERROR) {
7183 return 0;
7184 }
7185
7186 return mInput->stream->get_input_frames_lost(mInput->stream);
7187}
7188
Glenn Kastend848eb42016-03-08 13:42:11 -08007189uint32_t AudioFlinger::RecordThread::hasAudioSession(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08007190{
7191 Mutex::Autolock _l(mLock);
7192 uint32_t result = 0;
7193 if (getEffectChain_l(sessionId) != 0) {
7194 result = EFFECT_SESSION;
7195 }
7196
7197 for (size_t i = 0; i < mTracks.size(); ++i) {
7198 if (sessionId == mTracks[i]->sessionId()) {
7199 result |= TRACK_SESSION;
7200 break;
7201 }
7202 }
7203
7204 return result;
7205}
7206
Glenn Kastend848eb42016-03-08 13:42:11 -08007207KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08007208{
Glenn Kastend848eb42016-03-08 13:42:11 -08007209 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08007210 Mutex::Autolock _l(mLock);
7211 for (size_t j = 0; j < mTracks.size(); ++j) {
7212 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08007213 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08007214 if (ids.indexOfKey(sessionId) < 0) {
7215 ids.add(sessionId, true);
7216 }
7217 }
7218 return ids;
7219}
7220
7221AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7222{
7223 Mutex::Autolock _l(mLock);
7224 AudioStreamIn *input = mInput;
7225 mInput = NULL;
7226 return input;
7227}
7228
7229// this method must always be called either with ThreadBase mLock held or inside the thread loop
7230audio_stream_t* AudioFlinger::RecordThread::stream() const
7231{
7232 if (mInput == NULL) {
7233 return NULL;
7234 }
7235 return &mInput->stream->common;
7236}
7237
7238status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7239{
7240 // only one chain per input thread
7241 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07007242 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08007243 return INVALID_OPERATION;
7244 }
7245 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07007246 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08007247 chain->setInBuffer(NULL);
7248 chain->setOutBuffer(NULL);
7249
7250 checkSuspendOnAddEffectChain_l(chain);
7251
Eric Laurent1b928682014-10-02 19:41:47 -07007252 // make sure enabled pre processing effects state is communicated to the HAL as we
7253 // just moved them to a new input stream.
7254 chain->syncHalEffectsState();
7255
Eric Laurent81784c32012-11-19 14:55:58 -08007256 mEffectChains.add(chain);
7257
7258 return NO_ERROR;
7259}
7260
7261size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7262{
7263 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7264 ALOGW_IF(mEffectChains.size() != 1,
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007265 "removeEffectChain_l() %p invalid chain size %zu on thread %p",
Eric Laurent81784c32012-11-19 14:55:58 -08007266 chain.get(), mEffectChains.size(), this);
7267 if (mEffectChains.size() == 1) {
7268 mEffectChains.removeAt(0);
7269 }
7270 return 0;
7271}
7272
Eric Laurent1c333e22014-05-20 10:48:17 -07007273status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7274 audio_patch_handle_t *handle)
7275{
7276 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007277
7278 // store new device and send to effects
7279 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07007280 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07007281 for (size_t i = 0; i < mEffectChains.size(); i++) {
7282 mEffectChains[i]->setDevice_l(mInDevice);
7283 }
7284
7285 // disable AEC and NS if the device is a BT SCO headset supporting those
7286 // pre processings
7287 if (mTracks.size() > 0) {
7288 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7289 mAudioFlinger->btNrecIsOff();
7290 for (size_t i = 0; i < mTracks.size(); i++) {
7291 sp<RecordTrack> track = mTracks[i];
7292 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7293 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
7294 }
7295 }
7296
7297 // store new source and send to effects
7298 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7299 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07007300 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07007301 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07007302 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007303 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007304
Eric Laurent054d9d32015-04-24 08:48:48 -07007305 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007306 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
7307 status = hwDevice->create_audio_patch(hwDevice,
7308 patch->num_sources,
7309 patch->sources,
7310 patch->num_sinks,
7311 patch->sinks,
7312 handle);
7313 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007314 char *address;
7315 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7316 address = audio_device_address_to_parameter(
7317 patch->sources[0].ext.device.type,
7318 patch->sources[0].ext.device.address);
7319 } else {
7320 address = (char *)calloc(1, 1);
7321 }
7322 AudioParameter param = AudioParameter(String8(address));
7323 free(address);
7324 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING),
7325 (int)patch->sources[0].ext.device.type);
7326 param.addInt(String8(AUDIO_PARAMETER_STREAM_INPUT_SOURCE),
7327 (int)patch->sinks[0].ext.mix.usecase.source);
7328 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7329 param.toString().string());
7330 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07007331 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007332
Eric Laurente8726fe2015-06-26 09:39:24 -07007333 if (mInDevice != mPrevInDevice) {
7334 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7335 mPrevInDevice = mInDevice;
7336 }
Eric Laurent296fb132015-05-01 11:38:42 -07007337
Eric Laurent1c333e22014-05-20 10:48:17 -07007338 return status;
7339}
7340
7341status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7342{
7343 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007344
7345 mInDevice = AUDIO_DEVICE_NONE;
7346
Eric Laurent1c333e22014-05-20 10:48:17 -07007347 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
7348 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
7349 status = hwDevice->release_audio_patch(hwDevice, handle);
7350 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007351 AudioParameter param;
7352 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
7353 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7354 param.toString().string());
Eric Laurent1c333e22014-05-20 10:48:17 -07007355 }
7356 return status;
7357}
7358
Eric Laurent83b88082014-06-20 18:31:16 -07007359void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
7360{
7361 Mutex::Autolock _l(mLock);
7362 mTracks.add(record);
7363}
7364
7365void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
7366{
7367 Mutex::Autolock _l(mLock);
7368 destroyTrack_l(record);
7369}
7370
7371void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
7372{
7373 ThreadBase::getAudioPortConfig(config);
7374 config->role = AUDIO_PORT_ROLE_SINK;
7375 config->ext.mix.hw_module = mInput->audioHwDev->handle();
7376 config->ext.mix.usecase.source = mAudioSource;
7377}
Eric Laurent1c333e22014-05-20 10:48:17 -07007378
Glenn Kasten63238ef2015-03-02 15:50:29 -08007379} // namespace android