blob: ff67fb2a383190a40c29d2ed2b1da31e9d97daf4 [file] [log] [blame]
Eric Laurent81784c32012-11-19 14:55:58 -08001/*
2**
3** Copyright 2012, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
Alex Ray371eb972012-11-30 11:11:54 -080021#define ATRACE_TAG ATRACE_TAG_AUDIO
Eric Laurent81784c32012-11-19 14:55:58 -080022
Glenn Kasten153b9fe2013-07-15 11:23:36 -070023#include "Configuration.h"
Eric Laurent81784c32012-11-19 14:55:58 -080024#include <math.h>
25#include <fcntl.h>
Glenn Kastenad8510a2015-02-17 16:24:07 -080026#include <linux/futex.h>
Eric Laurent81784c32012-11-19 14:55:58 -080027#include <sys/stat.h>
Glenn Kastenad8510a2015-02-17 16:24:07 -080028#include <sys/syscall.h>
Eric Laurent81784c32012-11-19 14:55:58 -080029#include <cutils/properties.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070030#include <media/AudioParameter.h>
Andy Hungcd044842014-08-07 11:04:34 -070031#include <media/AudioResamplerPublic.h>
Eric Laurent81784c32012-11-19 14:55:58 -080032#include <utils/Log.h>
Alex Ray371eb972012-11-30 11:11:54 -080033#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080034
35#include <private/media/AudioTrackShared.h>
36#include <hardware/audio.h>
37#include <audio_effects/effect_ns.h>
38#include <audio_effects/effect_aec.h>
Andy Hung2ddee192015-12-18 17:34:44 -080039#include <audio_utils/conversion.h>
Eric Laurent81784c32012-11-19 14:55:58 -080040#include <audio_utils/primitives.h>
Andy Hung98ef9782014-03-04 14:46:50 -080041#include <audio_utils/format.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070042#include <audio_utils/minifloat.h>
Eric Laurent81784c32012-11-19 14:55:58 -080043
44// NBAIO implementations
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070045#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080046#include <media/nbaio/AudioStreamOutSink.h>
47#include <media/nbaio/MonoPipe.h>
48#include <media/nbaio/MonoPipeReader.h>
49#include <media/nbaio/Pipe.h>
50#include <media/nbaio/PipeReader.h>
51#include <media/nbaio/SourceAudioBufferProvider.h>
Wei Jia3f273d12015-11-24 09:06:49 -080052#include <mediautils/BatteryNotifier.h>
Eric Laurent81784c32012-11-19 14:55:58 -080053
54#include <powermanager/PowerManager.h>
55
Eric Laurent81784c32012-11-19 14:55:58 -080056#include "AudioFlinger.h"
57#include "AudioMixer.h"
Andy Hungd330ee42015-04-20 13:23:41 -070058#include "BufferProviders.h"
Eric Laurent81784c32012-11-19 14:55:58 -080059#include "FastMixer.h"
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070060#include "FastCapture.h"
Eric Laurent81784c32012-11-19 14:55:58 -080061#include "ServiceUtilities.h"
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -070062#include "mediautils/SchedulingPolicyService.h"
Eric Laurent81784c32012-11-19 14:55:58 -080063
Eric Laurent81784c32012-11-19 14:55:58 -080064#ifdef ADD_BATTERY_DATA
65#include <media/IMediaPlayerService.h>
66#include <media/IMediaDeathNotifier.h>
67#endif
68
Eric Laurent81784c32012-11-19 14:55:58 -080069#ifdef DEBUG_CPU_USAGE
70#include <cpustats/CentralTendencyStatistics.h>
71#include <cpustats/ThreadCpuUsage.h>
72#endif
73
Glenn Kastenc05b8d72016-03-24 09:48:17 -070074#include "AutoPark.h"
75
Eric Laurent81784c32012-11-19 14:55:58 -080076// ----------------------------------------------------------------------------
77
78// Note: the following macro is used for extremely verbose logging message. In
79// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
80// 0; but one side effect of this is to turn all LOGV's as well. Some messages
81// are so verbose that we want to suppress them even when we have ALOG_ASSERT
82// turned on. Do not uncomment the #def below unless you really know what you
83// are doing and want to see all of the extremely verbose messages.
84//#define VERY_VERY_VERBOSE_LOGGING
85#ifdef VERY_VERY_VERBOSE_LOGGING
86#define ALOGVV ALOGV
87#else
88#define ALOGVV(a...) do { } while(0)
89#endif
90
Andy Hung6770c6f2015-04-07 13:43:36 -070091// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -070092#define max(a, b) ((a) > (b) ? (a) : (b))
Andy Hung6770c6f2015-04-07 13:43:36 -070093template <typename T>
94static inline T min(const T& a, const T& b)
95{
96 return a < b ? a : b;
97}
Glenn Kasten49d00ad2014-07-21 11:22:03 -070098
Andy Hungd330ee42015-04-20 13:23:41 -070099#ifndef ARRAY_SIZE
100#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
101#endif
102
Eric Laurent81784c32012-11-19 14:55:58 -0800103namespace android {
104
105// retry counts for buffer fill timeout
106// 50 * ~20msecs = 1 second
107static const int8_t kMaxTrackRetries = 50;
108static const int8_t kMaxTrackStartupRetries = 50;
109// allow less retry attempts on direct output thread.
110// direct outputs can be a scarce resource in audio hardware and should
111// be released as quickly as possible.
112static const int8_t kMaxTrackRetriesDirect = 2;
Eric Laurent51716182016-02-29 18:00:56 -0800113// retry count before removing active track in case of underrun on offloaded thread:
114// we need to make sure that AudioTrack client has enough time to send large buffers
115//FIXME may be more appropriate if expressed in time units. Need to revise how underrun is handled
116// for offloaded tracks
117static const int8_t kMaxTrackRetriesOffload = 10;
118static const int8_t kMaxTrackStartupRetriesOffload = 100;
119
Eric Laurent81784c32012-11-19 14:55:58 -0800120
121// don't warn about blocked writes or record buffer overflows more often than this
122static const nsecs_t kWarningThrottleNs = seconds(5);
123
124// RecordThread loop sleep time upon application overrun or audio HAL read error
125static const int kRecordThreadSleepUs = 5000;
126
Eric Laurent10351942014-05-08 18:49:52 -0700127// maximum time to wait in sendConfigEvent_l() for a status to be received
128static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800129
130// minimum sleep time for the mixer thread loop when tracks are active but in underrun
131static const uint32_t kMinThreadSleepTimeUs = 5000;
132// maximum divider applied to the active sleep time in the mixer thread loop
133static const uint32_t kMaxThreadSleepTimeShift = 2;
134
Andy Hung09a50072014-02-27 14:30:47 -0800135// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700136// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800137static const uint32_t kMinNormalSinkBufferSizeMs = 20;
138// maximum normal sink buffer size
139static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800140
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700141// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
142// FIXME This should be based on experimentally observed scheduling jitter
143static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
144
Eric Laurent972a1732013-09-04 09:42:59 -0700145// Offloaded output thread standby delay: allows track transition without going to standby
146static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
147
Eric Laurent51716182016-02-29 18:00:56 -0800148// Direct output thread minimum sleep time in idle or active(underrun) state
149static const nsecs_t kDirectMinSleepTimeUs = 10000;
150
151// Offloaded output bit rate in bits per second when unknown.
152// Used for sleep time calculation, so use a high default bitrate to be conservative on sleep time.
153static const uint32_t kOffloadDefaultBitRateBps = 1500000;
154
155
Eric Laurent81784c32012-11-19 14:55:58 -0800156// Whether to use fast mixer
157static const enum {
158 FastMixer_Never, // never initialize or use: for debugging only
159 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
160 // normal mixer multiplier is 1
161 FastMixer_Static, // initialize if needed, then use all the time if initialized,
162 // multiplier is calculated based on min & max normal mixer buffer size
163 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
164 // multiplier is calculated based on min & max normal mixer buffer size
165 // FIXME for FastMixer_Dynamic:
166 // Supporting this option will require fixing HALs that can't handle large writes.
167 // For example, one HAL implementation returns an error from a large write,
168 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
169 // We could either fix the HAL implementations, or provide a wrapper that breaks
170 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
171} kUseFastMixer = FastMixer_Static;
172
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700173// Whether to use fast capture
174static const enum {
175 FastCapture_Never, // never initialize or use: for debugging only
176 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
177 FastCapture_Static, // initialize if needed, then use all the time if initialized
178} kUseFastCapture = FastCapture_Static;
179
Eric Laurent81784c32012-11-19 14:55:58 -0800180// Priorities for requestPriority
181static const int kPriorityAudioApp = 2;
182static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700183static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800184
185// IAudioFlinger::createTrack() reports back to client the total size of shared memory area
186// for the track. The client then sub-divides this into smaller buffers for its use.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800187// Currently the client uses N-buffering by default, but doesn't tell us about the value of N.
188// So for now we just assume that client is double-buffered for fast tracks.
189// FIXME It would be better for client to tell AudioFlinger the value of N,
190// so AudioFlinger could allocate the right amount of memory.
Eric Laurent81784c32012-11-19 14:55:58 -0800191// See the client's minBufCount and mNotificationFramesAct calculations for details.
Glenn Kasten03490092014-05-27 12:30:54 -0700192
193// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800194static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800195
Glenn Kasten03490092014-05-27 12:30:54 -0700196// The minimum and maximum allowed values
197static const int kFastTrackMultiplierMin = 1;
198static const int kFastTrackMultiplierMax = 2;
199
200// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
201static int sFastTrackMultiplier = kFastTrackMultiplier;
202
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700203// See Thread::readOnlyHeap().
204// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
205// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
206// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Glenn Kasten9f81de32014-07-27 15:02:23 -0700207static const size_t kRecordThreadReadOnlyHeapSize = 0x2000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700208
Eric Laurent81784c32012-11-19 14:55:58 -0800209// ----------------------------------------------------------------------------
210
Glenn Kasten03490092014-05-27 12:30:54 -0700211static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
212
213static void sFastTrackMultiplierInit()
214{
215 char value[PROPERTY_VALUE_MAX];
216 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
217 char *endptr;
218 unsigned long ul = strtoul(value, &endptr, 0);
219 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
220 sFastTrackMultiplier = (int) ul;
221 }
222 }
223}
224
225// ----------------------------------------------------------------------------
226
Eric Laurent81784c32012-11-19 14:55:58 -0800227#ifdef ADD_BATTERY_DATA
228// To collect the amplifier usage
229static void addBatteryData(uint32_t params) {
230 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
231 if (service == NULL) {
232 // it already logged
233 return;
234 }
235
236 service->addBatteryData(params);
237}
238#endif
239
Andy Hung3f0c9022016-01-15 17:49:46 -0800240// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
241struct {
242 // call when you acquire a partial wakelock
243 void acquire(const sp<IBinder> &wakeLockToken) {
244 pthread_mutex_lock(&mLock);
245 if (wakeLockToken.get() == nullptr) {
246 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
247 } else {
248 if (mCount == 0) {
249 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
250 }
251 ++mCount;
252 }
253 pthread_mutex_unlock(&mLock);
254 }
255
256 // call when you release a partial wakelock.
257 void release(const sp<IBinder> &wakeLockToken) {
258 if (wakeLockToken.get() == nullptr) {
259 return;
260 }
261 pthread_mutex_lock(&mLock);
262 if (--mCount < 0) {
263 ALOGE("negative wakelock count");
264 mCount = 0;
265 }
266 pthread_mutex_unlock(&mLock);
267 }
268
269 // retrieves the boottime timebase offset from monotonic.
270 int64_t getBoottimeOffset() {
271 pthread_mutex_lock(&mLock);
272 int64_t boottimeOffset = mBoottimeOffset;
273 pthread_mutex_unlock(&mLock);
274 return boottimeOffset;
275 }
276
277 // Adjusts the timebase offset between TIMEBASE_MONOTONIC
278 // and the selected timebase.
279 // Currently only TIMEBASE_BOOTTIME is allowed.
280 //
281 // This only needs to be called upon acquiring the first partial wakelock
282 // after all other partial wakelocks are released.
283 //
284 // We do an empirical measurement of the offset rather than parsing
285 // /proc/timer_list since the latter is not a formal kernel ABI.
286 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
287 int clockbase;
288 switch (timebase) {
289 case ExtendedTimestamp::TIMEBASE_BOOTTIME:
290 clockbase = SYSTEM_TIME_BOOTTIME;
291 break;
292 default:
293 LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
294 break;
295 }
296 // try three times to get the clock offset, choose the one
297 // with the minimum gap in measurements.
298 const int tries = 3;
299 nsecs_t bestGap, measured;
300 for (int i = 0; i < tries; ++i) {
301 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
302 const nsecs_t tbase = systemTime(clockbase);
303 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
304 const nsecs_t gap = tmono2 - tmono;
305 if (i == 0 || gap < bestGap) {
306 bestGap = gap;
307 measured = tbase - ((tmono + tmono2) >> 1);
308 }
309 }
310
311 // to avoid micro-adjusting, we don't change the timebase
312 // unless it is significantly different.
313 //
314 // Assumption: It probably takes more than toleranceNs to
315 // suspend and resume the device.
316 static int64_t toleranceNs = 10000; // 10 us
317 if (llabs(*offset - measured) > toleranceNs) {
318 ALOGV("Adjusting timebase offset old: %lld new: %lld",
319 (long long)*offset, (long long)measured);
320 *offset = measured;
321 }
322 }
323
324 pthread_mutex_t mLock;
325 int32_t mCount;
326 int64_t mBoottimeOffset;
327} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
Eric Laurent81784c32012-11-19 14:55:58 -0800328
329// ----------------------------------------------------------------------------
330// CPU Stats
331// ----------------------------------------------------------------------------
332
333class CpuStats {
334public:
335 CpuStats();
336 void sample(const String8 &title);
337#ifdef DEBUG_CPU_USAGE
338private:
339 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
340 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
341
342 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
343
344 int mCpuNum; // thread's current CPU number
345 int mCpukHz; // frequency of thread's current CPU in kHz
346#endif
347};
348
349CpuStats::CpuStats()
350#ifdef DEBUG_CPU_USAGE
351 : mCpuNum(-1), mCpukHz(-1)
352#endif
353{
354}
355
Glenn Kasten0f11b512014-01-31 16:18:54 -0800356void CpuStats::sample(const String8 &title
357#ifndef DEBUG_CPU_USAGE
358 __unused
359#endif
360 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800361#ifdef DEBUG_CPU_USAGE
362 // get current thread's delta CPU time in wall clock ns
363 double wcNs;
364 bool valid = mCpuUsage.sampleAndEnable(wcNs);
365
366 // record sample for wall clock statistics
367 if (valid) {
368 mWcStats.sample(wcNs);
369 }
370
371 // get the current CPU number
372 int cpuNum = sched_getcpu();
373
374 // get the current CPU frequency in kHz
375 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
376
377 // check if either CPU number or frequency changed
378 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
379 mCpuNum = cpuNum;
380 mCpukHz = cpukHz;
381 // ignore sample for purposes of cycles
382 valid = false;
383 }
384
385 // if no change in CPU number or frequency, then record sample for cycle statistics
386 if (valid && mCpukHz > 0) {
387 double cycles = wcNs * cpukHz * 0.000001;
388 mHzStats.sample(cycles);
389 }
390
391 unsigned n = mWcStats.n();
392 // mCpuUsage.elapsed() is expensive, so don't call it every loop
393 if ((n & 127) == 1) {
394 long long elapsed = mCpuUsage.elapsed();
395 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
396 double perLoop = elapsed / (double) n;
397 double perLoop100 = perLoop * 0.01;
398 double perLoop1k = perLoop * 0.001;
399 double mean = mWcStats.mean();
400 double stddev = mWcStats.stddev();
401 double minimum = mWcStats.minimum();
402 double maximum = mWcStats.maximum();
403 double meanCycles = mHzStats.mean();
404 double stddevCycles = mHzStats.stddev();
405 double minCycles = mHzStats.minimum();
406 double maxCycles = mHzStats.maximum();
407 mCpuUsage.resetElapsed();
408 mWcStats.reset();
409 mHzStats.reset();
410 ALOGD("CPU usage for %s over past %.1f secs\n"
411 " (%u mixer loops at %.1f mean ms per loop):\n"
412 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
413 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
414 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
415 title.string(),
416 elapsed * .000000001, n, perLoop * .000001,
417 mean * .001,
418 stddev * .001,
419 minimum * .001,
420 maximum * .001,
421 mean / perLoop100,
422 stddev / perLoop100,
423 minimum / perLoop100,
424 maximum / perLoop100,
425 meanCycles / perLoop1k,
426 stddevCycles / perLoop1k,
427 minCycles / perLoop1k,
428 maxCycles / perLoop1k);
429
430 }
431 }
432#endif
433};
434
435// ----------------------------------------------------------------------------
436// ThreadBase
437// ----------------------------------------------------------------------------
438
Glenn Kasten97b7b752014-09-28 13:04:24 -0700439// static
440const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
441{
442 switch (type) {
443 case MIXER:
444 return "MIXER";
445 case DIRECT:
446 return "DIRECT";
447 case DUPLICATING:
448 return "DUPLICATING";
449 case RECORD:
450 return "RECORD";
451 case OFFLOAD:
452 return "OFFLOAD";
453 default:
454 return "unknown";
455 }
456}
457
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800458String8 devicesToString(audio_devices_t devices)
459{
460 static const struct mapping {
461 audio_devices_t mDevices;
462 const char * mString;
463 } mappingsOut[] = {
Glenn Kasten818da522015-12-02 13:53:26 -0800464 {AUDIO_DEVICE_OUT_EARPIECE, "EARPIECE"},
465 {AUDIO_DEVICE_OUT_SPEAKER, "SPEAKER"},
466 {AUDIO_DEVICE_OUT_WIRED_HEADSET, "WIRED_HEADSET"},
467 {AUDIO_DEVICE_OUT_WIRED_HEADPHONE, "WIRED_HEADPHONE"},
468 {AUDIO_DEVICE_OUT_BLUETOOTH_SCO, "BLUETOOTH_SCO"},
469 {AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET, "BLUETOOTH_SCO_HEADSET"},
470 {AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT, "BLUETOOTH_SCO_CARKIT"},
471 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, "BLUETOOTH_A2DP"},
472 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,"BLUETOOTH_A2DP_HEADPHONES"},
473 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER, "BLUETOOTH_A2DP_SPEAKER"},
474 {AUDIO_DEVICE_OUT_AUX_DIGITAL, "AUX_DIGITAL"},
475 {AUDIO_DEVICE_OUT_HDMI, "HDMI"},
476 {AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET,"ANLG_DOCK_HEADSET"},
477 {AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET,"DGTL_DOCK_HEADSET"},
478 {AUDIO_DEVICE_OUT_USB_ACCESSORY, "USB_ACCESSORY"},
479 {AUDIO_DEVICE_OUT_USB_DEVICE, "USB_DEVICE"},
480 {AUDIO_DEVICE_OUT_TELEPHONY_TX, "TELEPHONY_TX"},
481 {AUDIO_DEVICE_OUT_LINE, "LINE"},
482 {AUDIO_DEVICE_OUT_HDMI_ARC, "HDMI_ARC"},
483 {AUDIO_DEVICE_OUT_SPDIF, "SPDIF"},
484 {AUDIO_DEVICE_OUT_FM, "FM"},
485 {AUDIO_DEVICE_OUT_AUX_LINE, "AUX_LINE"},
486 {AUDIO_DEVICE_OUT_SPEAKER_SAFE, "SPEAKER_SAFE"},
487 {AUDIO_DEVICE_OUT_IP, "IP"},
Eric Laurent58545be2016-02-22 18:54:20 -0800488 {AUDIO_DEVICE_OUT_BUS, "BUS"},
Glenn Kasten818da522015-12-02 13:53:26 -0800489 {AUDIO_DEVICE_NONE, "NONE"}, // must be last
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800490 }, mappingsIn[] = {
Glenn Kasten818da522015-12-02 13:53:26 -0800491 {AUDIO_DEVICE_IN_COMMUNICATION, "COMMUNICATION"},
492 {AUDIO_DEVICE_IN_AMBIENT, "AMBIENT"},
493 {AUDIO_DEVICE_IN_BUILTIN_MIC, "BUILTIN_MIC"},
494 {AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET, "BLUETOOTH_SCO_HEADSET"},
495 {AUDIO_DEVICE_IN_WIRED_HEADSET, "WIRED_HEADSET"},
496 {AUDIO_DEVICE_IN_AUX_DIGITAL, "AUX_DIGITAL"},
497 {AUDIO_DEVICE_IN_VOICE_CALL, "VOICE_CALL"},
498 {AUDIO_DEVICE_IN_TELEPHONY_RX, "TELEPHONY_RX"},
499 {AUDIO_DEVICE_IN_BACK_MIC, "BACK_MIC"},
500 {AUDIO_DEVICE_IN_REMOTE_SUBMIX, "REMOTE_SUBMIX"},
501 {AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET, "ANLG_DOCK_HEADSET"},
502 {AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET, "DGTL_DOCK_HEADSET"},
503 {AUDIO_DEVICE_IN_USB_ACCESSORY, "USB_ACCESSORY"},
504 {AUDIO_DEVICE_IN_USB_DEVICE, "USB_DEVICE"},
505 {AUDIO_DEVICE_IN_FM_TUNER, "FM_TUNER"},
506 {AUDIO_DEVICE_IN_TV_TUNER, "TV_TUNER"},
507 {AUDIO_DEVICE_IN_LINE, "LINE"},
508 {AUDIO_DEVICE_IN_SPDIF, "SPDIF"},
509 {AUDIO_DEVICE_IN_BLUETOOTH_A2DP, "BLUETOOTH_A2DP"},
510 {AUDIO_DEVICE_IN_LOOPBACK, "LOOPBACK"},
511 {AUDIO_DEVICE_IN_IP, "IP"},
Eric Laurent58545be2016-02-22 18:54:20 -0800512 {AUDIO_DEVICE_IN_BUS, "BUS"},
Glenn Kasten818da522015-12-02 13:53:26 -0800513 {AUDIO_DEVICE_NONE, "NONE"}, // must be last
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800514 };
515 String8 result;
516 audio_devices_t allDevices = AUDIO_DEVICE_NONE;
517 const mapping *entry;
518 if (devices & AUDIO_DEVICE_BIT_IN) {
519 devices &= ~AUDIO_DEVICE_BIT_IN;
520 entry = mappingsIn;
521 } else {
522 entry = mappingsOut;
523 }
524 for ( ; entry->mDevices != AUDIO_DEVICE_NONE; entry++) {
525 allDevices = (audio_devices_t) (allDevices | entry->mDevices);
526 if (devices & entry->mDevices) {
527 if (!result.isEmpty()) {
528 result.append("|");
529 }
530 result.append(entry->mString);
531 }
532 }
533 if (devices & ~allDevices) {
534 if (!result.isEmpty()) {
535 result.append("|");
536 }
537 result.appendFormat("0x%X", devices & ~allDevices);
538 }
539 if (result.isEmpty()) {
540 result.append(entry->mString);
541 }
542 return result;
543}
544
545String8 inputFlagsToString(audio_input_flags_t flags)
546{
547 static const struct mapping {
548 audio_input_flags_t mFlag;
549 const char * mString;
550 } mappings[] = {
Glenn Kasten818da522015-12-02 13:53:26 -0800551 {AUDIO_INPUT_FLAG_FAST, "FAST"},
552 {AUDIO_INPUT_FLAG_HW_HOTWORD, "HW_HOTWORD"},
553 {AUDIO_INPUT_FLAG_RAW, "RAW"},
554 {AUDIO_INPUT_FLAG_SYNC, "SYNC"},
555 {AUDIO_INPUT_FLAG_NONE, "NONE"}, // must be last
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800556 };
557 String8 result;
558 audio_input_flags_t allFlags = AUDIO_INPUT_FLAG_NONE;
559 const mapping *entry;
560 for (entry = mappings; entry->mFlag != AUDIO_INPUT_FLAG_NONE; entry++) {
561 allFlags = (audio_input_flags_t) (allFlags | entry->mFlag);
562 if (flags & entry->mFlag) {
563 if (!result.isEmpty()) {
564 result.append("|");
565 }
566 result.append(entry->mString);
567 }
568 }
569 if (flags & ~allFlags) {
570 if (!result.isEmpty()) {
571 result.append("|");
572 }
573 result.appendFormat("0x%X", flags & ~allFlags);
574 }
575 if (result.isEmpty()) {
576 result.append(entry->mString);
577 }
578 return result;
579}
580
581String8 outputFlagsToString(audio_output_flags_t flags)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700582{
583 static const struct mapping {
584 audio_output_flags_t mFlag;
585 const char * mString;
586 } mappings[] = {
Glenn Kasten818da522015-12-02 13:53:26 -0800587 {AUDIO_OUTPUT_FLAG_DIRECT, "DIRECT"},
588 {AUDIO_OUTPUT_FLAG_PRIMARY, "PRIMARY"},
589 {AUDIO_OUTPUT_FLAG_FAST, "FAST"},
590 {AUDIO_OUTPUT_FLAG_DEEP_BUFFER, "DEEP_BUFFER"},
591 {AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,"COMPRESS_OFFLOAD"},
592 {AUDIO_OUTPUT_FLAG_NON_BLOCKING, "NON_BLOCKING"},
593 {AUDIO_OUTPUT_FLAG_HW_AV_SYNC, "HW_AV_SYNC"},
594 {AUDIO_OUTPUT_FLAG_RAW, "RAW"},
595 {AUDIO_OUTPUT_FLAG_SYNC, "SYNC"},
596 {AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO, "IEC958_NONAUDIO"},
597 {AUDIO_OUTPUT_FLAG_NONE, "NONE"}, // must be last
Glenn Kasten97b7b752014-09-28 13:04:24 -0700598 };
599 String8 result;
600 audio_output_flags_t allFlags = AUDIO_OUTPUT_FLAG_NONE;
601 const mapping *entry;
602 for (entry = mappings; entry->mFlag != AUDIO_OUTPUT_FLAG_NONE; entry++) {
603 allFlags = (audio_output_flags_t) (allFlags | entry->mFlag);
604 if (flags & entry->mFlag) {
605 if (!result.isEmpty()) {
606 result.append("|");
607 }
608 result.append(entry->mString);
609 }
610 }
611 if (flags & ~allFlags) {
612 if (!result.isEmpty()) {
613 result.append("|");
614 }
615 result.appendFormat("0x%X", flags & ~allFlags);
616 }
617 if (result.isEmpty()) {
618 result.append(entry->mString);
619 }
620 return result;
621}
622
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800623const char *sourceToString(audio_source_t source)
624{
625 switch (source) {
626 case AUDIO_SOURCE_DEFAULT: return "default";
627 case AUDIO_SOURCE_MIC: return "mic";
628 case AUDIO_SOURCE_VOICE_UPLINK: return "voice uplink";
629 case AUDIO_SOURCE_VOICE_DOWNLINK: return "voice downlink";
630 case AUDIO_SOURCE_VOICE_CALL: return "voice call";
631 case AUDIO_SOURCE_CAMCORDER: return "camcorder";
632 case AUDIO_SOURCE_VOICE_RECOGNITION: return "voice recognition";
633 case AUDIO_SOURCE_VOICE_COMMUNICATION: return "voice communication";
634 case AUDIO_SOURCE_REMOTE_SUBMIX: return "remote submix";
rago8a397d52015-12-02 11:27:57 -0800635 case AUDIO_SOURCE_UNPROCESSED: return "unprocessed";
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800636 case AUDIO_SOURCE_FM_TUNER: return "FM tuner";
637 case AUDIO_SOURCE_HOTWORD: return "hotword";
638 default: return "unknown";
639 }
640}
641
Eric Laurent81784c32012-11-19 14:55:58 -0800642AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -0700643 audio_devices_t outDevice, audio_devices_t inDevice, type_t type, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -0800644 : Thread(false /*canCallJava*/),
645 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700646 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700647 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800648 // are set by PlaybackThread::readOutputParameters_l() or
649 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700650 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800651 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700652 mPrevOutDevice(AUDIO_DEVICE_NONE), mPrevInDevice(AUDIO_DEVICE_NONE),
653 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800654 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700655 mDeathRecipient(new PMDeathRecipient(this)),
Wei Jia3f273d12015-11-24 09:06:49 -0800656 mSystemReady(systemReady),
657 mNotifiedBatteryStart(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800658{
Eric Laurent296fb132015-05-01 11:38:42 -0700659 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800660}
661
662AudioFlinger::ThreadBase::~ThreadBase()
663{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700664 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700665 mConfigEvents.clear();
666
Eric Laurent81784c32012-11-19 14:55:58 -0800667 // do not lock the mutex in destructor
668 releaseWakeLock_l();
669 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800670 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800671 binder->unlinkToDeath(mDeathRecipient);
672 }
673}
674
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700675status_t AudioFlinger::ThreadBase::readyToRun()
676{
677 status_t status = initCheck();
678 if (status == NO_ERROR) {
679 ALOGI("AudioFlinger's thread %p ready to run", this);
680 } else {
681 ALOGE("No working audio driver found.");
682 }
683 return status;
684}
685
Eric Laurent81784c32012-11-19 14:55:58 -0800686void AudioFlinger::ThreadBase::exit()
687{
688 ALOGV("ThreadBase::exit");
689 // do any cleanup required for exit to succeed
690 preExit();
691 {
692 // This lock prevents the following race in thread (uniprocessor for illustration):
693 // if (!exitPending()) {
694 // // context switch from here to exit()
695 // // exit() calls requestExit(), what exitPending() observes
696 // // exit() calls signal(), which is dropped since no waiters
697 // // context switch back from exit() to here
698 // mWaitWorkCV.wait(...);
699 // // now thread is hung
700 // }
701 AutoMutex lock(mLock);
702 requestExit();
703 mWaitWorkCV.broadcast();
704 }
705 // When Thread::requestExitAndWait is made virtual and this method is renamed to
706 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
707 requestExitAndWait();
708}
709
710status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
711{
Eric Laurent81784c32012-11-19 14:55:58 -0800712 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
713 Mutex::Autolock _l(mLock);
714
Eric Laurent10351942014-05-08 18:49:52 -0700715 return sendSetParameterConfigEvent_l(keyValuePairs);
716}
717
718// sendConfigEvent_l() must be called with ThreadBase::mLock held
719// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
720status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
721{
722 status_t status = NO_ERROR;
723
Eric Laurent72e3f392015-05-20 14:43:50 -0700724 if (event->mRequiresSystemReady && !mSystemReady) {
725 event->mWaitStatus = false;
726 mPendingConfigEvents.add(event);
727 return status;
728 }
Eric Laurent10351942014-05-08 18:49:52 -0700729 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700730 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800731 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700732 mLock.unlock();
733 {
734 Mutex::Autolock _l(event->mLock);
735 while (event->mWaitStatus) {
736 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
737 event->mStatus = TIMED_OUT;
738 event->mWaitStatus = false;
739 }
740 }
741 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800742 }
Eric Laurent10351942014-05-08 18:49:52 -0700743 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800744 return status;
745}
746
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700747void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800748{
749 Mutex::Autolock _l(mLock);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700750 sendIoConfigEvent_l(event, pid);
Eric Laurent81784c32012-11-19 14:55:58 -0800751}
752
753// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700754void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800755{
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700756 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid);
Eric Laurent10351942014-05-08 18:49:52 -0700757 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800758}
759
Eric Laurent72e3f392015-05-20 14:43:50 -0700760void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio)
761{
762 Mutex::Autolock _l(mLock);
763 sendPrioConfigEvent_l(pid, tid, prio);
764}
765
Eric Laurent81784c32012-11-19 14:55:58 -0800766// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
767void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
768{
Eric Laurent10351942014-05-08 18:49:52 -0700769 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio);
770 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800771}
772
Eric Laurent10351942014-05-08 18:49:52 -0700773// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
774status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800775{
Andy Hung2ddee192015-12-18 17:34:44 -0800776 sp<ConfigEvent> configEvent;
777 AudioParameter param(keyValuePair);
778 int value;
779 if (param.getInt(String8(AUDIO_PARAMETER_MONO_OUTPUT), value) == NO_ERROR) {
780 setMasterMono_l(value != 0);
781 if (param.size() == 1) {
782 return NO_ERROR; // should be a solo parameter - we don't pass down
783 }
784 param.remove(String8(AUDIO_PARAMETER_MONO_OUTPUT));
785 configEvent = new SetParameterConfigEvent(param.toString());
786 } else {
787 configEvent = new SetParameterConfigEvent(keyValuePair);
788 }
Eric Laurent10351942014-05-08 18:49:52 -0700789 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700790}
791
Eric Laurent1c333e22014-05-20 10:48:17 -0700792status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
793 const struct audio_patch *patch,
794 audio_patch_handle_t *handle)
795{
796 Mutex::Autolock _l(mLock);
797 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
798 status_t status = sendConfigEvent_l(configEvent);
799 if (status == NO_ERROR) {
800 CreateAudioPatchConfigEventData *data =
801 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
802 *handle = data->mHandle;
803 }
804 return status;
805}
806
807status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
808 const audio_patch_handle_t handle)
809{
810 Mutex::Autolock _l(mLock);
811 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
812 return sendConfigEvent_l(configEvent);
813}
814
815
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700816// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700817void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700818{
Eric Laurent10351942014-05-08 18:49:52 -0700819 bool configChanged = false;
820
Eric Laurent81784c32012-11-19 14:55:58 -0800821 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700822 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700823 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800824 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700825 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700826 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700827 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
828 // FIXME Need to understand why this has to be done asynchronously
829 int err = requestPriority(data->mPid, data->mTid, data->mPrio,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700830 true /*asynchronous*/);
831 if (err != 0) {
832 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700833 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700834 }
835 } break;
836 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700837 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700838 ioConfigChanged(data->mEvent, data->mPid);
Eric Laurent10351942014-05-08 18:49:52 -0700839 } break;
840 case CFG_EVENT_SET_PARAMETER: {
841 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
842 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
843 configChanged = true;
Glenn Kastend5418eb2013-08-14 13:11:06 -0700844 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700845 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700846 case CFG_EVENT_CREATE_AUDIO_PATCH: {
847 CreateAudioPatchConfigEventData *data =
848 (CreateAudioPatchConfigEventData *)event->mData.get();
849 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
850 } break;
851 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
852 ReleaseAudioPatchConfigEventData *data =
853 (ReleaseAudioPatchConfigEventData *)event->mData.get();
854 event->mStatus = releaseAudioPatch_l(data->mHandle);
855 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700856 default:
Eric Laurent10351942014-05-08 18:49:52 -0700857 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700858 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800859 }
Eric Laurent10351942014-05-08 18:49:52 -0700860 {
861 Mutex::Autolock _l(event->mLock);
862 if (event->mWaitStatus) {
863 event->mWaitStatus = false;
864 event->mCond.signal();
865 }
866 }
867 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
868 }
869
870 if (configChanged) {
871 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800872 }
Eric Laurent81784c32012-11-19 14:55:58 -0800873}
874
Marco Nelissenb2208842014-02-07 14:00:50 -0800875String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
876 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700877 const audio_channel_representation_t representation =
878 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700879
880 switch (representation) {
881 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
882 if (output) {
883 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
884 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
885 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
886 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
887 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
888 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
889 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
890 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
891 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
892 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
893 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
894 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
895 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
896 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
897 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
898 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
899 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
900 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
901 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
902 } else {
903 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
904 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
905 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
906 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
907 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
908 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
909 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
910 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
911 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
912 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
913 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
914 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
915 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
916 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
917 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
918 }
919 const int len = s.length();
920 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -0700921 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -0700922 s.unlockBuffer(len - 2); // remove trailing ", "
923 }
924 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800925 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700926 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
927 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
928 return s;
929 default:
930 s.appendFormat("unknown mask, representation:%d bits:%#x",
931 representation, audio_channel_mask_get_bits(mask));
932 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800933 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800934}
935
Glenn Kasten0f11b512014-01-31 16:18:54 -0800936void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800937{
938 const size_t SIZE = 256;
939 char buffer[SIZE];
940 String8 result;
941
942 bool locked = AudioFlinger::dumpTryLock(mLock);
943 if (!locked) {
Glenn Kasten97b7b752014-09-28 13:04:24 -0700944 dprintf(fd, "thread %p may be deadlocked\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -0800945 }
946
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800947 dprintf(fd, " Thread name: %s\n", mThreadName);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700948 dprintf(fd, " I/O handle: %d\n", mId);
949 dprintf(fd, " TID: %d\n", getTid());
950 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700951 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700952 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700953 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat));
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700954 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700955 dprintf(fd, " Channel count: %u\n", mChannelCount);
956 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800957 channelMaskToString(mChannelMask, mType != RECORD).string());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700958 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat));
959 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700960 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800961 size_t numConfig = mConfigEvents.size();
962 if (numConfig) {
963 for (size_t i = 0; i < numConfig; i++) {
964 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700965 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800966 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700967 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800968 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700969 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800970 }
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800971 dprintf(fd, " Output device: %#x (%s)\n", mOutDevice, devicesToString(mOutDevice).string());
972 dprintf(fd, " Input device: %#x (%s)\n", mInDevice, devicesToString(mInDevice).string());
973 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, sourceToString(mAudioSource));
Eric Laurent81784c32012-11-19 14:55:58 -0800974
975 if (locked) {
976 mLock.unlock();
977 }
978}
979
980void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
981{
982 const size_t SIZE = 256;
983 char buffer[SIZE];
984 String8 result;
985
Marco Nelissenb2208842014-02-07 14:00:50 -0800986 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000987 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800988 write(fd, buffer, strlen(buffer));
989
Marco Nelissenb2208842014-02-07 14:00:50 -0800990 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800991 sp<EffectChain> chain = mEffectChains[i];
992 if (chain != 0) {
993 chain->dump(fd, args);
994 }
995 }
996}
997
Marco Nelissene14a5d62013-10-03 08:51:24 -0700998void AudioFlinger::ThreadBase::acquireWakeLock(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800999{
1000 Mutex::Autolock _l(mLock);
Marco Nelissene14a5d62013-10-03 08:51:24 -07001001 acquireWakeLock_l(uid);
Eric Laurent81784c32012-11-19 14:55:58 -08001002}
1003
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001004String16 AudioFlinger::ThreadBase::getWakeLockTag()
1005{
1006 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -08001007 case MIXER:
1008 return String16("AudioMix");
1009 case DIRECT:
1010 return String16("AudioDirectOut");
1011 case DUPLICATING:
1012 return String16("AudioDup");
1013 case RECORD:
1014 return String16("AudioIn");
1015 case OFFLOAD:
1016 return String16("AudioOffload");
1017 default:
1018 ALOG_ASSERT(false);
1019 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001020 }
1021}
1022
Marco Nelissene14a5d62013-10-03 08:51:24 -07001023void AudioFlinger::ThreadBase::acquireWakeLock_l(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -08001024{
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001025 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001026 if (mPowerManager != 0) {
1027 sp<IBinder> binder = new BBinder();
Marco Nelissene14a5d62013-10-03 08:51:24 -07001028 status_t status;
1029 if (uid >= 0) {
Eric Laurent547789d2013-10-04 11:46:55 -07001030 status = mPowerManager->acquireWakeLockWithUid(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -07001031 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001032 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -07001033 String16("audioserver"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -07001034 uid,
1035 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -07001036 } else {
Eric Laurent547789d2013-10-04 11:46:55 -07001037 status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -07001038 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001039 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -07001040 String16("audioserver"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -07001041 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -07001042 }
Eric Laurent81784c32012-11-19 14:55:58 -08001043 if (status == NO_ERROR) {
1044 mWakeLockToken = binder;
1045 }
Glenn Kastend7dca052015-03-05 16:05:54 -08001046 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -08001047 }
Wei Jia3f273d12015-11-24 09:06:49 -08001048
1049 if (!mNotifiedBatteryStart) {
1050 BatteryNotifier::getInstance().noteStartAudio();
1051 mNotifiedBatteryStart = true;
1052 }
Andy Hung3f0c9022016-01-15 17:49:46 -08001053 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -08001054 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
1055 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -08001056}
1057
1058void AudioFlinger::ThreadBase::releaseWakeLock()
1059{
1060 Mutex::Autolock _l(mLock);
1061 releaseWakeLock_l();
1062}
1063
1064void AudioFlinger::ThreadBase::releaseWakeLock_l()
1065{
Andy Hung3f0c9022016-01-15 17:49:46 -08001066 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -08001067 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001068 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001069 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -07001070 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
1071 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -08001072 }
1073 mWakeLockToken.clear();
1074 }
Wei Jia3f273d12015-11-24 09:06:49 -08001075
1076 if (mNotifiedBatteryStart) {
1077 BatteryNotifier::getInstance().noteStopAudio();
1078 mNotifiedBatteryStart = false;
1079 }
Eric Laurent81784c32012-11-19 14:55:58 -08001080}
1081
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001082void AudioFlinger::ThreadBase::updateWakeLockUids(const SortedVector<int> &uids) {
1083 Mutex::Autolock _l(mLock);
1084 updateWakeLockUids_l(uids);
1085}
1086
1087void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -07001088 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001089 // use checkService() to avoid blocking if power service is not up yet
1090 sp<IBinder> binder =
1091 defaultServiceManager()->checkService(String16("power"));
1092 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001093 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001094 } else {
1095 mPowerManager = interface_cast<IPowerManager>(binder);
1096 binder->linkToDeath(mDeathRecipient);
1097 }
1098 }
1099}
1100
1101void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<int> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001102 getPowerManager_l();
Andy Hung438e7572015-12-14 15:51:17 -08001103 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
1104 if (mSystemReady) {
1105 ALOGE("no wake lock to update, but system ready!");
1106 } else {
1107 ALOGW("no wake lock to update, system not ready yet");
1108 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001109 return;
1110 }
1111 if (mPowerManager != 0) {
1112 sp<IBinder> binder = new BBinder();
1113 status_t status;
Glenn Kasten3abc2de2014-09-05 16:45:52 -07001114 status = mPowerManager->updateWakeLockUids(mWakeLockToken, uids.size(), uids.array(),
1115 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent4d231dc2016-03-11 18:38:23 -08001116 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001117 }
1118}
1119
Eric Laurent81784c32012-11-19 14:55:58 -08001120void AudioFlinger::ThreadBase::clearPowerManager()
1121{
1122 Mutex::Autolock _l(mLock);
1123 releaseWakeLock_l();
1124 mPowerManager.clear();
1125}
1126
Glenn Kasten0f11b512014-01-31 16:18:54 -08001127void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001128{
1129 sp<ThreadBase> thread = mThread.promote();
1130 if (thread != 0) {
1131 thread->clearPowerManager();
1132 }
1133 ALOGW("power manager service died !!!");
1134}
1135
1136void AudioFlinger::ThreadBase::setEffectSuspended(
Glenn Kastend848eb42016-03-08 13:42:11 -08001137 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001138{
1139 Mutex::Autolock _l(mLock);
1140 setEffectSuspended_l(type, suspend, sessionId);
1141}
1142
1143void AudioFlinger::ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001144 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001145{
1146 sp<EffectChain> chain = getEffectChain_l(sessionId);
1147 if (chain != 0) {
1148 if (type != NULL) {
1149 chain->setEffectSuspended_l(type, suspend);
1150 } else {
1151 chain->setEffectSuspendedAll_l(suspend);
1152 }
1153 }
1154
1155 updateSuspendedSessions_l(type, suspend, sessionId);
1156}
1157
1158void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1159{
1160 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1161 if (index < 0) {
1162 return;
1163 }
1164
1165 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1166 mSuspendedSessions.valueAt(index);
1167
1168 for (size_t i = 0; i < sessionEffects.size(); i++) {
1169 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1170 for (int j = 0; j < desc->mRefCount; j++) {
1171 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1172 chain->setEffectSuspendedAll_l(true);
1173 } else {
1174 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1175 desc->mType.timeLow);
1176 chain->setEffectSuspended_l(&desc->mType, true);
1177 }
1178 }
1179 }
1180}
1181
1182void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1183 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001184 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001185{
1186 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1187
1188 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1189
1190 if (suspend) {
1191 if (index >= 0) {
1192 sessionEffects = mSuspendedSessions.valueAt(index);
1193 } else {
1194 mSuspendedSessions.add(sessionId, sessionEffects);
1195 }
1196 } else {
1197 if (index < 0) {
1198 return;
1199 }
1200 sessionEffects = mSuspendedSessions.valueAt(index);
1201 }
1202
1203
1204 int key = EffectChain::kKeyForSuspendAll;
1205 if (type != NULL) {
1206 key = type->timeLow;
1207 }
1208 index = sessionEffects.indexOfKey(key);
1209
1210 sp<SuspendedSessionDesc> desc;
1211 if (suspend) {
1212 if (index >= 0) {
1213 desc = sessionEffects.valueAt(index);
1214 } else {
1215 desc = new SuspendedSessionDesc();
1216 if (type != NULL) {
1217 desc->mType = *type;
1218 }
1219 sessionEffects.add(key, desc);
1220 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1221 }
1222 desc->mRefCount++;
1223 } else {
1224 if (index < 0) {
1225 return;
1226 }
1227 desc = sessionEffects.valueAt(index);
1228 if (--desc->mRefCount == 0) {
1229 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1230 sessionEffects.removeItemsAt(index);
1231 if (sessionEffects.isEmpty()) {
1232 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1233 sessionId);
1234 mSuspendedSessions.removeItem(sessionId);
1235 }
1236 }
1237 }
1238 if (!sessionEffects.isEmpty()) {
1239 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1240 }
1241}
1242
1243void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1244 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001245 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001246{
1247 Mutex::Autolock _l(mLock);
1248 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1249}
1250
1251void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1252 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001253 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001254{
1255 if (mType != RECORD) {
1256 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1257 // another session. This gives the priority to well behaved effect control panels
1258 // and applications not using global effects.
1259 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1260 // global effects
1261 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1262 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1263 }
1264 }
1265
1266 sp<EffectChain> chain = getEffectChain_l(sessionId);
1267 if (chain != 0) {
1268 chain->checkSuspendOnEffectEnabled(effect, enabled);
1269 }
1270}
1271
1272// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1273sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1274 const sp<AudioFlinger::Client>& client,
1275 const sp<IEffectClient>& effectClient,
1276 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001277 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001278 effect_descriptor_t *desc,
1279 int *enabled,
Glenn Kasten9156ef32013-08-06 15:39:08 -07001280 status_t *status)
Eric Laurent81784c32012-11-19 14:55:58 -08001281{
1282 sp<EffectModule> effect;
1283 sp<EffectHandle> handle;
1284 status_t lStatus;
1285 sp<EffectChain> chain;
1286 bool chainCreated = false;
1287 bool effectCreated = false;
1288 bool effectRegistered = false;
1289
1290 lStatus = initCheck();
1291 if (lStatus != NO_ERROR) {
1292 ALOGW("createEffect_l() Audio driver not initialized.");
1293 goto Exit;
1294 }
1295
Andy Hung98ef9782014-03-04 14:46:50 -08001296 // Reject any effect on Direct output threads for now, since the format of
1297 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1298 if (mType == DIRECT) {
1299 ALOGW("createEffect_l() Cannot add effect %s on Direct output type thread %s",
Glenn Kastend7dca052015-03-05 16:05:54 -08001300 desc->name, mThreadName);
Andy Hung98ef9782014-03-04 14:46:50 -08001301 lStatus = BAD_VALUE;
1302 goto Exit;
1303 }
1304
Andy Hung389cfdb2014-08-07 17:49:53 -07001305 // Reject any effect on mixer or duplicating multichannel sinks.
Andy Hung9a592762014-07-21 21:56:01 -07001306 // TODO: fix both format and multichannel issues with effects.
Andy Hung389cfdb2014-08-07 17:49:53 -07001307 if ((mType == MIXER || mType == DUPLICATING) && mChannelCount != FCC_2) {
1308 ALOGW("createEffect_l() Cannot add effect %s for multichannel(%d) %s threads",
1309 desc->name, mChannelCount, mType == MIXER ? "MIXER" : "DUPLICATING");
Andy Hung9a592762014-07-21 21:56:01 -07001310 lStatus = BAD_VALUE;
1311 goto Exit;
1312 }
1313
Eric Laurent5baf2af2013-09-12 17:37:00 -07001314 // Allow global effects only on offloaded and mixer threads
1315 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1316 switch (mType) {
1317 case MIXER:
1318 case OFFLOAD:
1319 break;
1320 case DIRECT:
1321 case DUPLICATING:
1322 case RECORD:
1323 default:
Glenn Kastend7dca052015-03-05 16:05:54 -08001324 ALOGW("createEffect_l() Cannot add global effect %s on thread %s",
1325 desc->name, mThreadName);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001326 lStatus = BAD_VALUE;
1327 goto Exit;
1328 }
Eric Laurent81784c32012-11-19 14:55:58 -08001329 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001330
Eric Laurent81784c32012-11-19 14:55:58 -08001331 // Only Pre processor effects are allowed on input threads and only on input threads
1332 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
1333 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
1334 desc->name, desc->flags, mType);
1335 lStatus = BAD_VALUE;
1336 goto Exit;
1337 }
1338
1339 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1340
1341 { // scope for mLock
1342 Mutex::Autolock _l(mLock);
1343
1344 // check for existing effect chain with the requested audio session
1345 chain = getEffectChain_l(sessionId);
1346 if (chain == 0) {
1347 // create a new chain for this session
1348 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1349 chain = new EffectChain(this, sessionId);
1350 addEffectChain_l(chain);
1351 chain->setStrategy(getStrategyForSession_l(sessionId));
1352 chainCreated = true;
1353 } else {
1354 effect = chain->getEffectFromDesc_l(desc);
1355 }
1356
1357 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1358
1359 if (effect == 0) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08001360 audio_unique_id_t id = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001361 // Check CPU and memory usage
1362 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
1363 if (lStatus != NO_ERROR) {
1364 goto Exit;
1365 }
1366 effectRegistered = true;
1367 // create a new effect module if none present in the chain
1368 effect = new EffectModule(this, chain, desc, id, sessionId);
1369 lStatus = effect->status();
1370 if (lStatus != NO_ERROR) {
1371 goto Exit;
1372 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001373 effect->setOffloaded(mType == OFFLOAD, mId);
1374
Eric Laurent81784c32012-11-19 14:55:58 -08001375 lStatus = chain->addEffect_l(effect);
1376 if (lStatus != NO_ERROR) {
1377 goto Exit;
1378 }
1379 effectCreated = true;
1380
1381 effect->setDevice(mOutDevice);
1382 effect->setDevice(mInDevice);
1383 effect->setMode(mAudioFlinger->getMode());
1384 effect->setAudioSource(mAudioSource);
1385 }
1386 // create effect handle and connect it to effect module
1387 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001388 lStatus = handle->initCheck();
1389 if (lStatus == OK) {
1390 lStatus = effect->addHandle(handle.get());
1391 }
Eric Laurent81784c32012-11-19 14:55:58 -08001392 if (enabled != NULL) {
1393 *enabled = (int)effect->isEnabled();
1394 }
1395 }
1396
1397Exit:
1398 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1399 Mutex::Autolock _l(mLock);
1400 if (effectCreated) {
1401 chain->removeEffect_l(effect);
1402 }
1403 if (effectRegistered) {
1404 AudioSystem::unregisterEffect(effect->id());
1405 }
1406 if (chainCreated) {
1407 removeEffectChain_l(chain);
1408 }
1409 handle.clear();
1410 }
1411
Glenn Kasten9156ef32013-08-06 15:39:08 -07001412 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001413 return handle;
1414}
1415
Glenn Kastend848eb42016-03-08 13:42:11 -08001416sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1417 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001418{
1419 Mutex::Autolock _l(mLock);
1420 return getEffect_l(sessionId, effectId);
1421}
1422
Glenn Kastend848eb42016-03-08 13:42:11 -08001423sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1424 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001425{
1426 sp<EffectChain> chain = getEffectChain_l(sessionId);
1427 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1428}
1429
1430// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1431// PlaybackThread::mLock held
1432status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1433{
1434 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001435 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001436 sp<EffectChain> chain = getEffectChain_l(sessionId);
1437 bool chainCreated = false;
1438
Eric Laurent5baf2af2013-09-12 17:37:00 -07001439 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1440 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1441 this, effect->desc().name, effect->desc().flags);
1442
Eric Laurent81784c32012-11-19 14:55:58 -08001443 if (chain == 0) {
1444 // create a new chain for this session
1445 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1446 chain = new EffectChain(this, sessionId);
1447 addEffectChain_l(chain);
1448 chain->setStrategy(getStrategyForSession_l(sessionId));
1449 chainCreated = true;
1450 }
1451 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1452
1453 if (chain->getEffectFromId_l(effect->id()) != 0) {
1454 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1455 this, effect->desc().name, chain.get());
1456 return BAD_VALUE;
1457 }
1458
Eric Laurent5baf2af2013-09-12 17:37:00 -07001459 effect->setOffloaded(mType == OFFLOAD, mId);
1460
Eric Laurent81784c32012-11-19 14:55:58 -08001461 status_t status = chain->addEffect_l(effect);
1462 if (status != NO_ERROR) {
1463 if (chainCreated) {
1464 removeEffectChain_l(chain);
1465 }
1466 return status;
1467 }
1468
1469 effect->setDevice(mOutDevice);
1470 effect->setDevice(mInDevice);
1471 effect->setMode(mAudioFlinger->getMode());
1472 effect->setAudioSource(mAudioSource);
1473 return NO_ERROR;
1474}
1475
1476void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
1477
1478 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
1479 effect_descriptor_t desc = effect->desc();
1480 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1481 detachAuxEffect_l(effect->id());
1482 }
1483
1484 sp<EffectChain> chain = effect->chain().promote();
1485 if (chain != 0) {
1486 // remove effect chain if removing last effect
1487 if (chain->removeEffect_l(effect) == 0) {
1488 removeEffectChain_l(chain);
1489 }
1490 } else {
1491 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1492 }
1493}
1494
1495void AudioFlinger::ThreadBase::lockEffectChains_l(
1496 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1497{
1498 effectChains = mEffectChains;
1499 for (size_t i = 0; i < mEffectChains.size(); i++) {
1500 mEffectChains[i]->lock();
1501 }
1502}
1503
1504void AudioFlinger::ThreadBase::unlockEffectChains(
1505 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1506{
1507 for (size_t i = 0; i < effectChains.size(); i++) {
1508 effectChains[i]->unlock();
1509 }
1510}
1511
Glenn Kastend848eb42016-03-08 13:42:11 -08001512sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001513{
1514 Mutex::Autolock _l(mLock);
1515 return getEffectChain_l(sessionId);
1516}
1517
Glenn Kastend848eb42016-03-08 13:42:11 -08001518sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1519 const
Eric Laurent81784c32012-11-19 14:55:58 -08001520{
1521 size_t size = mEffectChains.size();
1522 for (size_t i = 0; i < size; i++) {
1523 if (mEffectChains[i]->sessionId() == sessionId) {
1524 return mEffectChains[i];
1525 }
1526 }
1527 return 0;
1528}
1529
1530void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1531{
1532 Mutex::Autolock _l(mLock);
1533 size_t size = mEffectChains.size();
1534 for (size_t i = 0; i < size; i++) {
1535 mEffectChains[i]->setMode_l(mode);
1536 }
1537}
1538
Eric Laurent83b88082014-06-20 18:31:16 -07001539void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1540{
1541 config->type = AUDIO_PORT_TYPE_MIX;
1542 config->ext.mix.handle = mId;
1543 config->sample_rate = mSampleRate;
1544 config->format = mFormat;
1545 config->channel_mask = mChannelMask;
1546 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1547 AUDIO_PORT_CONFIG_FORMAT;
1548}
1549
Eric Laurent72e3f392015-05-20 14:43:50 -07001550void AudioFlinger::ThreadBase::systemReady()
1551{
1552 Mutex::Autolock _l(mLock);
1553 if (mSystemReady) {
1554 return;
1555 }
1556 mSystemReady = true;
1557
1558 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1559 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1560 }
1561 mPendingConfigEvents.clear();
1562}
1563
Eric Laurent83b88082014-06-20 18:31:16 -07001564
Eric Laurent81784c32012-11-19 14:55:58 -08001565// ----------------------------------------------------------------------------
1566// Playback
1567// ----------------------------------------------------------------------------
1568
1569AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1570 AudioStreamOut* output,
1571 audio_io_handle_t id,
1572 audio_devices_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07001573 type_t type,
Eric Laurent51716182016-02-29 18:00:56 -08001574 bool systemReady,
1575 uint32_t bitRate)
Eric Laurent72e3f392015-05-20 14:43:50 -07001576 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001577 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001578 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001579 mMixerBuffer(NULL),
1580 mMixerBufferSize(0),
1581 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1582 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001583 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001584 mEffectBuffer(NULL),
1585 mEffectBufferSize(0),
1586 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1587 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001588 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001589 mFramesWritten(0),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001590 mActiveTracksGeneration(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001591 // mStreamTypes[] initialized in constructor body
1592 mOutput(output),
1593 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
1594 mMixerStatus(MIXER_IDLE),
1595 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001596 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001597 mBytesRemaining(0),
1598 mCurrentWriteLength(0),
1599 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001600 mWriteAckSequence(0),
1601 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001602 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001603 mScreenState(AudioFlinger::mScreenState),
1604 // index 0 is reserved for normal mixer's submix
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001605 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1),
Andy Hunge10393e2015-06-12 13:59:33 -07001606 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001607{
Glenn Kastend7dca052015-03-05 16:05:54 -08001608 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1609 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001610
1611 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1612 // it would be safer to explicitly pass initial masterVolume/masterMute as
1613 // parameter.
1614 //
1615 // If the HAL we are using has support for master volume or master mute,
1616 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1617 // and the mute set to false).
1618 mMasterVolume = audioFlinger->masterVolume_l();
1619 mMasterMute = audioFlinger->masterMute_l();
1620 if (mOutput && mOutput->audioHwDev) {
1621 if (mOutput->audioHwDev->canSetMasterVolume()) {
1622 mMasterVolume = 1.0;
1623 }
1624
1625 if (mOutput->audioHwDev->canSetMasterMute()) {
1626 mMasterMute = false;
1627 }
1628 }
1629
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001630 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001631
Eric Laurent223fd5c2014-11-11 13:43:36 -08001632 // ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001633 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001634 stream = (audio_stream_type_t) (stream + 1)) {
1635 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1636 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1637 }
Eric Laurent51716182016-02-29 18:00:56 -08001638
1639 if (audio_has_proportional_frames(mFormat)) {
1640 mBufferDurationUs = (uint32_t)((mNormalFrameCount * 1000000LL) / mSampleRate);
1641 } else {
1642 bitRate = bitRate != 0 ? bitRate : kOffloadDefaultBitRateBps;
1643 mBufferDurationUs = (uint32_t)((mBufferSize * 8 * 1000000LL) / bitRate);
1644 }
Eric Laurent81784c32012-11-19 14:55:58 -08001645}
1646
1647AudioFlinger::PlaybackThread::~PlaybackThread()
1648{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001649 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001650 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001651 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001652 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001653}
1654
1655void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1656{
1657 dumpInternals(fd, args);
1658 dumpTracks(fd, args);
1659 dumpEffectChains(fd, args);
1660}
1661
Glenn Kasten0f11b512014-01-31 16:18:54 -08001662void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001663{
1664 const size_t SIZE = 256;
1665 char buffer[SIZE];
1666 String8 result;
1667
Marco Nelissenb2208842014-02-07 14:00:50 -08001668 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001669 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1670 const stream_type_t *st = &mStreamTypes[i];
1671 if (i > 0) {
1672 result.appendFormat(", ");
1673 }
1674 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1675 if (st->mute) {
1676 result.append("M");
1677 }
1678 }
1679 result.append("\n");
1680 write(fd, result.string(), result.length());
1681 result.clear();
1682
Eric Laurent81784c32012-11-19 14:55:58 -08001683 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1684 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001685 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001686 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001687
1688 size_t numtracks = mTracks.size();
1689 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001690 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001691 size_t numactiveseen = 0;
1692 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001693 dprintf(fd, " of which %zu are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001694 Track::appendDumpHeader(result);
1695 for (size_t i = 0; i < numtracks; ++i) {
1696 sp<Track> track = mTracks[i];
1697 if (track != 0) {
1698 bool active = mActiveTracks.indexOf(track) >= 0;
1699 if (active) {
1700 numactiveseen++;
1701 }
1702 track->dump(buffer, SIZE, active);
1703 result.append(buffer);
1704 }
1705 }
1706 } else {
1707 result.append("\n");
1708 }
1709 if (numactiveseen != numactive) {
1710 // some tracks in the active list were not in the tracks list
1711 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1712 " not in the track list\n");
1713 result.append(buffer);
1714 Track::appendDumpHeader(result);
1715 for (size_t i = 0; i < numactive; ++i) {
1716 sp<Track> track = mActiveTracks[i].promote();
1717 if (track != 0 && mTracks.indexOf(track) < 0) {
1718 track->dump(buffer, SIZE, true);
1719 result.append(buffer);
1720 }
1721 }
1722 }
1723
1724 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001725}
1726
1727void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1728{
Glenn Kasten97b7b752014-09-28 13:04:24 -07001729 dprintf(fd, "\nOutput thread %p type %d (%s):\n", this, type(), threadTypeToString(type()));
Glenn Kasten44182c22015-03-05 17:12:23 -08001730
1731 dumpBase(fd, args);
1732
Elliott Hughes87cebad2014-05-22 10:14:43 -07001733 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001734 dprintf(fd, " Last write occurred (msecs): %llu\n",
1735 (unsigned long long) ns2ms(systemTime() - mLastWriteTime));
Elliott Hughes87cebad2014-05-22 10:14:43 -07001736 dprintf(fd, " Total writes: %d\n", mNumWrites);
1737 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1738 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1739 dprintf(fd, " Suspend count: %d\n", mSuspended);
1740 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1741 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1742 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1743 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08001744 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001745 AudioStreamOut *output = mOutput;
1746 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
1747 String8 flagsAsString = outputFlagsToString(flags);
1748 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n", output, flags, flagsAsString.string());
Eric Laurent81784c32012-11-19 14:55:58 -08001749}
1750
1751// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001752
1753void AudioFlinger::PlaybackThread::onFirstRef()
1754{
Glenn Kastend7dca052015-03-05 16:05:54 -08001755 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001756}
1757
1758// ThreadBase virtuals
1759void AudioFlinger::PlaybackThread::preExit()
1760{
1761 ALOGV(" preExit()");
1762 // FIXME this is using hard-coded strings but in the future, this functionality will be
1763 // converted to use audio HAL extensions required to support tunneling
1764 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1765}
1766
1767// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1768sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1769 const sp<AudioFlinger::Client>& client,
1770 audio_stream_type_t streamType,
1771 uint32_t sampleRate,
1772 audio_format_t format,
1773 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001774 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001775 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08001776 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001777 IAudioFlinger::track_flags_t *flags,
1778 pid_t tid,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001779 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -08001780 status_t *status)
1781{
Glenn Kasten74935e42013-12-19 08:56:45 -08001782 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001783 sp<Track> track;
1784 status_t lStatus;
1785
Eric Laurent81784c32012-11-19 14:55:58 -08001786 // client expresses a preference for FAST, but we get the final say
1787 if (*flags & IAudioFlinger::TRACK_FAST) {
1788 if (
Eric Laurent81784c32012-11-19 14:55:58 -08001789 // PCM data
1790 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001791 // TODO: extract as a data library function that checks that a computationally
1792 // expensive downmixer is not required: isFastOutputChannelConversion()
Andy Hung9a592762014-07-21 21:56:01 -07001793 (channelMask == mChannelMask ||
Andy Hung1f439e12015-05-19 12:57:41 -07001794 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1795 (channelMask == AUDIO_CHANNEL_OUT_MONO
1796 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001797 // hardware sample rate
1798 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001799 // normal mixer has an associated fast mixer
1800 hasFastMixer() &&
1801 // there are sufficient fast track slots available
1802 (mFastTrackAvailMask != 0)
1803 // FIXME test that MixerThread for this fast track has a capable output HAL
1804 // FIXME add a permission test also?
1805 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07001806 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
1807 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001808 // read the fast track multiplier property the first time it is needed
1809 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1810 if (ok != 0) {
1811 ALOGE("%s pthread_once failed: %d", __func__, ok);
1812 }
Andy Hunge0a269a2016-03-23 15:13:42 -07001813 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08001814 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001815 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08001816 frameCount, mFrameCount);
1817 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001818 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
1819 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07001820 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001821 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08001822 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001823 audio_is_linear_pcm(format),
1824 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1825 *flags &= ~IAudioFlinger::TRACK_FAST;
Andy Hung0e48d252015-01-26 11:43:15 -08001826 }
1827 }
1828 // For normal PCM streaming tracks, update minimum frame count.
1829 // For compatibility with AudioTrack calculation, buffer depth is forced
1830 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1831 // This is probably too conservative, but legacy application code may depend on it.
1832 // If you change this calculation, also review the start threshold which is related.
1833 if (!(*flags & IAudioFlinger::TRACK_FAST)
Phil Burkfdb3c072016-02-09 10:47:02 -08001834 && audio_has_proportional_frames(format) && sharedBuffer == 0) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001835 // this must match AudioTrack.cpp calculateMinFrameCount().
1836 // TODO: Move to a common library
Eric Laurent81784c32012-11-19 14:55:58 -08001837 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1838 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1839 if (minBufCount < 2) {
1840 minBufCount = 2;
1841 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07001842 // For normal mixing tracks, if speed is > 1.0f (normal), AudioTrack
1843 // or the client should compute and pass in a larger buffer request.
Andy Hung0e48d252015-01-26 11:43:15 -08001844 size_t minFrameCount =
Andy Hung8edb8dc2015-03-26 19:13:55 -07001845 minBufCount * sourceFramesNeededWithTimestretch(
1846 sampleRate, mNormalFrameCount,
1847 mSampleRate, AUDIO_TIMESTRETCH_SPEED_NORMAL /*speed*/);
Andy Hung0e48d252015-01-26 11:43:15 -08001848 if (frameCount < minFrameCount) { // including frameCount == 0
Eric Laurent81784c32012-11-19 14:55:58 -08001849 frameCount = minFrameCount;
1850 }
Eric Laurent81784c32012-11-19 14:55:58 -08001851 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001852 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001853
Glenn Kastenc3df8382014-03-13 15:05:25 -07001854 switch (mType) {
1855
1856 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08001857 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08001858 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001859 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1860 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001861 sampleRate, format, channelMask, mOutput, mFormat);
1862 lStatus = BAD_VALUE;
1863 goto Exit;
1864 }
1865 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001866 break;
1867
1868 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001869 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001870 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1871 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001872 sampleRate, format, channelMask, mOutput, mFormat);
1873 lStatus = BAD_VALUE;
1874 goto Exit;
1875 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001876 break;
1877
1878 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001879 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001880 ALOGE("createTrack_l() Bad parameter: format %#x \""
1881 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001882 format, mOutput, mFormat);
1883 lStatus = BAD_VALUE;
1884 goto Exit;
1885 }
Andy Hungcd044842014-08-07 11:04:34 -07001886 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08001887 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1888 lStatus = BAD_VALUE;
1889 goto Exit;
1890 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001891 break;
1892
Eric Laurent81784c32012-11-19 14:55:58 -08001893 }
1894
1895 lStatus = initCheck();
1896 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001897 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08001898 goto Exit;
1899 }
1900
1901 { // scope for mLock
1902 Mutex::Autolock _l(mLock);
1903
1904 // all tracks in same audio session must share the same routing strategy otherwise
1905 // conflicts will happen when tracks are moved from one output to another by audio policy
1906 // manager
1907 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1908 for (size_t i = 0; i < mTracks.size(); ++i) {
1909 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07001910 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001911 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1912 if (sessionId == t->sessionId() && strategy != actual) {
1913 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1914 strategy, actual);
1915 lStatus = BAD_VALUE;
1916 goto Exit;
1917 }
1918 }
1919 }
1920
Glenn Kastend79072e2016-01-06 08:41:20 -08001921 track = new Track(this, client, streamType, sampleRate, format,
1922 channelMask, frameCount, NULL, sharedBuffer,
1923 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT);
Glenn Kasten03003332013-08-06 15:40:54 -07001924
Glenn Kasten03003332013-08-06 15:40:54 -07001925 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1926 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08001927 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001928 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08001929 goto Exit;
1930 }
1931 mTracks.add(track);
1932
1933 sp<EffectChain> chain = getEffectChain_l(sessionId);
1934 if (chain != 0) {
1935 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1936 track->setMainBuffer(chain->inBuffer());
1937 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1938 chain->incTrackCnt();
1939 }
1940
1941 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1942 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1943 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1944 // so ask activity manager to do this on our behalf
1945 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1946 }
1947 }
1948
1949 lStatus = NO_ERROR;
1950
1951Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001952 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001953 return track;
1954}
1955
1956uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1957{
1958 return latency;
1959}
1960
1961uint32_t AudioFlinger::PlaybackThread::latency() const
1962{
1963 Mutex::Autolock _l(mLock);
1964 return latency_l();
1965}
1966uint32_t AudioFlinger::PlaybackThread::latency_l() const
1967{
1968 if (initCheck() == NO_ERROR) {
1969 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1970 } else {
1971 return 0;
1972 }
1973}
1974
1975void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1976{
1977 Mutex::Autolock _l(mLock);
1978 // Don't apply master volume in SW if our HAL can do it for us.
1979 if (mOutput && mOutput->audioHwDev &&
1980 mOutput->audioHwDev->canSetMasterVolume()) {
1981 mMasterVolume = 1.0;
1982 } else {
1983 mMasterVolume = value;
1984 }
1985}
1986
1987void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1988{
1989 Mutex::Autolock _l(mLock);
1990 // Don't apply master mute in SW if our HAL can do it for us.
1991 if (mOutput && mOutput->audioHwDev &&
1992 mOutput->audioHwDev->canSetMasterMute()) {
1993 mMasterMute = false;
1994 } else {
1995 mMasterMute = muted;
1996 }
1997}
1998
1999void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2000{
2001 Mutex::Autolock _l(mLock);
2002 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002003 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002004}
2005
2006void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2007{
2008 Mutex::Autolock _l(mLock);
2009 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002010 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002011}
2012
2013float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2014{
2015 Mutex::Autolock _l(mLock);
2016 return mStreamTypes[stream].volume;
2017}
2018
2019// addTrack_l() must be called with ThreadBase::mLock held
2020status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2021{
2022 status_t status = ALREADY_EXISTS;
2023
Eric Laurent81784c32012-11-19 14:55:58 -08002024 if (mActiveTracks.indexOf(track) < 0) {
2025 // the track is newly added, make sure it fills up all its
2026 // buffers before playing. This is to ensure the client will
2027 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002028 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002029 TrackBase::track_state state = track->mState;
2030 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002031 status = AudioSystem::startOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002032 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002033 mLock.lock();
2034 // abort track was stopped/paused while we released the lock
2035 if (state != track->mState) {
2036 if (status == NO_ERROR) {
2037 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002038 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002039 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002040 mLock.lock();
2041 }
2042 return INVALID_OPERATION;
2043 }
2044 // abort if start is rejected by audio policy manager
2045 if (status != NO_ERROR) {
2046 return PERMISSION_DENIED;
2047 }
2048#ifdef ADD_BATTERY_DATA
2049 // to track the speaker usage
2050 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2051#endif
2052 }
2053
Eric Laurent51716182016-02-29 18:00:56 -08002054 // set retry count for buffer fill
2055 if (track->isOffloaded()) {
2056 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2057 } else {
2058 track->mRetryCount = kMaxTrackStartupRetries;
2059 }
2060
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002061 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08002062 track->mResetDone = false;
2063 track->mPresentationCompleteFrames = 0;
2064 mActiveTracks.add(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002065 mWakeLockUids.add(track->uid());
2066 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07002067 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07002068 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2069 if (chain != 0) {
2070 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2071 track->sessionId());
2072 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002073 }
2074
2075 status = NO_ERROR;
2076 }
2077
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002078 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002079 return status;
2080}
2081
Eric Laurentbfb1b832013-01-07 09:53:42 -08002082bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002083{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002084 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002085 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002086 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2087 track->mState = TrackBase::STOPPED;
2088 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002089 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002090 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002091 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002092 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002093
2094 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002095}
2096
2097void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2098{
2099 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
2100 mTracks.remove(track);
2101 deleteTrackName_l(track->name());
2102 // redundant as track is about to be destroyed, for dumpsys only
2103 track->mName = -1;
2104 if (track->isFastTrack()) {
2105 int index = track->mFastIndex;
2106 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
2107 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2108 mFastTrackAvailMask |= 1 << index;
2109 // redundant as track is about to be destroyed, for dumpsys only
2110 track->mFastIndex = -1;
2111 }
2112 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2113 if (chain != 0) {
2114 chain->decTrackCnt();
2115 }
2116}
2117
Eric Laurentede6c3b2013-09-19 14:37:46 -07002118void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002119{
2120 // Thread could be blocked waiting for async
2121 // so signal it to handle state changes immediately
2122 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
2123 // be lost so we also flag to prevent it blocking on mWaitWorkCV
2124 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002125 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002126}
2127
Eric Laurent81784c32012-11-19 14:55:58 -08002128String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2129{
Eric Laurent81784c32012-11-19 14:55:58 -08002130 Mutex::Autolock _l(mLock);
2131 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07002132 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002133 }
2134
Glenn Kastend8ea6992013-07-16 14:17:15 -07002135 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
2136 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08002137 free(s);
2138 return out_s8;
2139}
2140
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002141void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002142 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2143 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002144
Eric Laurent73e26b62015-04-27 16:55:58 -07002145 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002146
2147 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002148 case AUDIO_OUTPUT_OPENED:
2149 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002150 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002151 desc->mChannelMask = mChannelMask;
2152 desc->mSamplingRate = mSampleRate;
2153 desc->mFormat = mFormat;
2154 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002155 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002156 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002157 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002158 break;
2159
Eric Laurent73e26b62015-04-27 16:55:58 -07002160 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002161 default:
2162 break;
2163 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002164 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002165}
2166
Eric Laurentbfb1b832013-01-07 09:53:42 -08002167void AudioFlinger::PlaybackThread::writeCallback()
2168{
2169 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002170 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002171}
2172
2173void AudioFlinger::PlaybackThread::drainCallback()
2174{
2175 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002176 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002177}
2178
Eric Laurent3b4529e2013-09-05 18:09:19 -07002179void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002180{
2181 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002182 // reject out of sequence requests
2183 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2184 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002185 mWaitWorkCV.signal();
2186 }
2187}
2188
Eric Laurent3b4529e2013-09-05 18:09:19 -07002189void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002190{
2191 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002192 // reject out of sequence requests
2193 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
2194 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002195 mWaitWorkCV.signal();
2196 }
2197}
2198
2199// static
2200int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
Glenn Kasten0f11b512014-01-31 16:18:54 -08002201 void *param __unused,
Eric Laurentbfb1b832013-01-07 09:53:42 -08002202 void *cookie)
2203{
2204 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
2205 ALOGV("asyncCallback() event %d", event);
2206 switch (event) {
2207 case STREAM_CBK_EVENT_WRITE_READY:
2208 me->writeCallback();
2209 break;
2210 case STREAM_CBK_EVENT_DRAIN_READY:
2211 me->drainCallback();
2212 break;
2213 default:
2214 ALOGW("asyncCallback() unknown event %d", event);
2215 break;
2216 }
2217 return 0;
2218}
2219
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002220void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002221{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002222 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002223 mSampleRate = mOutput->getSampleRate();
2224 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002225 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002226 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002227 }
Andy Hung9a592762014-07-21 21:56:01 -07002228 if ((mType == MIXER || mType == DUPLICATING)
2229 && !isValidPcmSinkChannelMask(mChannelMask)) {
2230 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2231 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002232 }
Andy Hunge5412692014-05-16 11:25:07 -07002233 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002234
2235 // Get actual HAL format.
Andy Hung463be252014-07-10 16:56:07 -07002236 mHALFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Phil Burkca5e6142015-07-14 09:42:29 -07002237 // Get format from the shim, which will be different than the HAL format
2238 // if playing compressed audio over HDMI passthrough.
2239 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002240 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002241 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002242 }
Andy Hung6146c082014-03-18 11:56:15 -07002243 if ((mType == MIXER || mType == DUPLICATING)
2244 && !isValidPcmSinkFormat(mFormat)) {
2245 LOG_FATAL("HAL format %#x not supported for mixed output",
2246 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002247 }
Phil Burk062e67a2015-02-11 13:40:50 -08002248 mFrameSize = mOutput->getFrameSize();
Glenn Kasten70949c42013-08-06 07:40:12 -07002249 mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
2250 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002251 if (mFrameCount & 15) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002252 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002253 mFrameCount);
2254 }
2255
Eric Laurentbfb1b832013-01-07 09:53:42 -08002256 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
2257 (mOutput->stream->set_callback != NULL)) {
2258 if (mOutput->stream->set_callback(mOutput->stream,
2259 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
2260 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002261 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002262 }
2263 }
2264
Eric Laurentd1f69b02014-12-15 14:33:13 -08002265 mHwSupportsPause = false;
2266 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
2267 if (mOutput->stream->pause != NULL) {
2268 if (mOutput->stream->resume != NULL) {
2269 mHwSupportsPause = true;
2270 } else {
2271 ALOGW("direct output implements pause but not resume");
2272 }
2273 } else if (mOutput->stream->resume != NULL) {
2274 ALOGW("direct output implements resume but not pause");
2275 }
2276 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002277 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2278 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2279 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002280
Andy Hungfbfc3952015-01-15 13:33:51 -08002281 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2282 // For best precision, we use float instead of the associated output
2283 // device format (typically PCM 16 bit).
2284
2285 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2286 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2287 mBufferSize = mFrameSize * mFrameCount;
2288
2289 // TODO: We currently use the associated output device channel mask and sample rate.
2290 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2291 // (if a valid mask) to avoid premature downmix.
2292 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2293 // instead of the output device sample rate to avoid loss of high frequency information.
2294 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2295 }
2296
Andy Hung09a50072014-02-27 14:30:47 -08002297 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002298 double multiplier = 1.0;
2299 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2300 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002301 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2302 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Eric Laurent81784c32012-11-19 14:55:58 -08002303 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2304 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2305 maxNormalFrameCount = maxNormalFrameCount & ~15;
2306 if (maxNormalFrameCount < minNormalFrameCount) {
2307 maxNormalFrameCount = minNormalFrameCount;
2308 }
2309 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2310 if (multiplier <= 1.0) {
2311 multiplier = 1.0;
2312 } else if (multiplier <= 2.0) {
2313 if (2 * mFrameCount <= maxNormalFrameCount) {
2314 multiplier = 2.0;
2315 } else {
2316 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2317 }
2318 } else {
2319 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
Andy Hung09a50072014-02-27 14:30:47 -08002320 // 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 -08002321 // track, but we sometimes have to do this to satisfy the maximum frame count
2322 // constraint)
2323 // FIXME this rounding up should not be done if no HAL SRC
2324 uint32_t truncMult = (uint32_t) multiplier;
2325 if ((truncMult & 1)) {
2326 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2327 ++truncMult;
2328 }
2329 }
2330 multiplier = (double) truncMult;
2331 }
2332 }
2333 mNormalFrameCount = multiplier * mFrameCount;
2334 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002335 if (mType == MIXER || mType == DUPLICATING) {
2336 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2337 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002338 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002339 mNormalFrameCount);
2340
Andy Hung08fb1742015-05-31 23:22:10 -07002341 // Check if we want to throttle the processing to no more than 2x normal rate
2342 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002343 mThreadThrottleTimeMs = 0;
2344 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002345 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2346
Andy Hung010a1a12014-03-13 13:57:33 -07002347 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2348 // Originally this was int16_t[] array, need to remove legacy implications.
2349 free(mSinkBuffer);
2350 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002351 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2352 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2353 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002354 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002355
Andy Hung69aed5f2014-02-25 17:24:40 -08002356 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2357 // drives the output.
2358 free(mMixerBuffer);
2359 mMixerBuffer = NULL;
2360 if (mMixerBufferEnabled) {
2361 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2362 mMixerBufferSize = mNormalFrameCount * mChannelCount
2363 * audio_bytes_per_sample(mMixerBufferFormat);
2364 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2365 }
Andy Hung98ef9782014-03-04 14:46:50 -08002366 free(mEffectBuffer);
2367 mEffectBuffer = NULL;
2368 if (mEffectBufferEnabled) {
2369 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2370 mEffectBufferSize = mNormalFrameCount * mChannelCount
2371 * audio_bytes_per_sample(mEffectBufferFormat);
2372 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2373 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002374
Eric Laurent81784c32012-11-19 14:55:58 -08002375 // force reconfiguration of effect chains and engines to take new buffer size and audio
2376 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002377 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002378 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2379 // matter.
2380 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2381 Vector< sp<EffectChain> > effectChains = mEffectChains;
2382 for (size_t i = 0; i < effectChains.size(); i ++) {
2383 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2384 }
2385}
2386
2387
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002388status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002389{
2390 if (halFrames == NULL || dspFrames == NULL) {
2391 return BAD_VALUE;
2392 }
2393 Mutex::Autolock _l(mLock);
2394 if (initCheck() != NO_ERROR) {
2395 return INVALID_OPERATION;
2396 }
Andy Hung818e7a32016-02-16 18:08:07 -08002397 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002398 *halFrames = framesWritten;
2399
2400 if (isSuspended()) {
2401 // return an estimation of rendered frames when the output is suspended
2402 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002403 *dspFrames = (uint32_t)
2404 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002405 return NO_ERROR;
2406 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002407 status_t status;
2408 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002409 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002410 *dspFrames = (size_t)frames;
2411 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002412 }
2413}
2414
Glenn Kastend848eb42016-03-08 13:42:11 -08002415uint32_t AudioFlinger::PlaybackThread::hasAudioSession(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08002416{
2417 Mutex::Autolock _l(mLock);
2418 uint32_t result = 0;
2419 if (getEffectChain_l(sessionId) != 0) {
2420 result = EFFECT_SESSION;
2421 }
2422
2423 for (size_t i = 0; i < mTracks.size(); ++i) {
2424 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002425 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002426 result |= TRACK_SESSION;
2427 break;
2428 }
2429 }
2430
2431 return result;
2432}
2433
Glenn Kastend848eb42016-03-08 13:42:11 -08002434uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08002435{
2436 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2437 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2438 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2439 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2440 }
2441 for (size_t i = 0; i < mTracks.size(); i++) {
2442 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002443 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002444 return AudioSystem::getStrategyForStream(track->streamType());
2445 }
2446 }
2447 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2448}
2449
2450
Phil Burk062e67a2015-02-11 13:40:50 -08002451AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002452{
2453 Mutex::Autolock _l(mLock);
2454 return mOutput;
2455}
2456
Phil Burk062e67a2015-02-11 13:40:50 -08002457AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002458{
2459 Mutex::Autolock _l(mLock);
2460 AudioStreamOut *output = mOutput;
2461 mOutput = NULL;
2462 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2463 // must push a NULL and wait for ack
2464 mOutputSink.clear();
2465 mPipeSink.clear();
2466 mNormalSink.clear();
2467 return output;
2468}
2469
2470// this method must always be called either with ThreadBase mLock held or inside the thread loop
2471audio_stream_t* AudioFlinger::PlaybackThread::stream() const
2472{
2473 if (mOutput == NULL) {
2474 return NULL;
2475 }
2476 return &mOutput->stream->common;
2477}
2478
2479uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2480{
2481 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2482}
2483
2484status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2485{
2486 if (!isValidSyncEvent(event)) {
2487 return BAD_VALUE;
2488 }
2489
2490 Mutex::Autolock _l(mLock);
2491
2492 for (size_t i = 0; i < mTracks.size(); ++i) {
2493 sp<Track> track = mTracks[i];
2494 if (event->triggerSession() == track->sessionId()) {
2495 (void) track->setSyncEvent(event);
2496 return NO_ERROR;
2497 }
2498 }
2499
2500 return NAME_NOT_FOUND;
2501}
2502
2503bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2504{
2505 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2506}
2507
2508void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2509 const Vector< sp<Track> >& tracksToRemove)
2510{
2511 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002512 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002513 for (size_t i = 0 ; i < count ; i++) {
2514 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002515 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002516 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002517 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002518#ifdef ADD_BATTERY_DATA
2519 // to track the speaker usage
2520 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2521#endif
2522 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002523 AudioSystem::releaseOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002524 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002525 }
Eric Laurent81784c32012-11-19 14:55:58 -08002526 }
2527 }
2528 }
Eric Laurent81784c32012-11-19 14:55:58 -08002529}
2530
2531void AudioFlinger::PlaybackThread::checkSilentMode_l()
2532{
2533 if (!mMasterMute) {
2534 char value[PROPERTY_VALUE_MAX];
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07002535 if (mOutDevice == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) {
2536 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
2537 return;
2538 }
Eric Laurent81784c32012-11-19 14:55:58 -08002539 if (property_get("ro.audio.silent", value, "0") > 0) {
2540 char *endptr;
2541 unsigned long ul = strtoul(value, &endptr, 0);
2542 if (*endptr == '\0' && ul != 0) {
2543 ALOGD("Silence is golden");
2544 // The setprop command will not allow a property to be changed after
2545 // the first time it is set, so we don't have to worry about un-muting.
2546 setMasterMute_l(true);
2547 }
2548 }
2549 }
2550}
2551
2552// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002553ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002554{
2555 // FIXME rewrite to reduce number of system calls
2556 mLastWriteTime = systemTime();
2557 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002558 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002559 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002560
2561 // If an NBAIO sink is present, use it to write the normal mixer's submix
2562 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002563
Andy Hung010a1a12014-03-13 13:57:33 -07002564 const size_t count = mBytesRemaining / mFrameSize;
2565
Simon Wilson2d590962012-11-29 15:18:50 -08002566 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002567 // update the setpoint when AudioFlinger::mScreenState changes
2568 uint32_t screenState = AudioFlinger::mScreenState;
2569 if (screenState != mScreenState) {
2570 mScreenState = screenState;
2571 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2572 if (pipe != NULL) {
2573 pipe->setAvgFrames((mScreenState & 1) ?
2574 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2575 }
2576 }
Andy Hung010a1a12014-03-13 13:57:33 -07002577 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002578 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002579 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002580 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002581 } else {
2582 bytesWritten = framesWritten;
2583 }
2584 // otherwise use the HAL / AudioStreamOut directly
2585 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002586 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002587
Eric Laurentbfb1b832013-01-07 09:53:42 -08002588 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002589 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2590 mWriteAckSequence += 2;
2591 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002592 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002593 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002594 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002595 // FIXME We should have an implementation of timestamps for direct output threads.
2596 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002597 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurent51716182016-02-29 18:00:56 -08002598
Eric Laurentbfb1b832013-01-07 09:53:42 -08002599 if (mUseAsyncWrite &&
2600 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2601 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002602 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002603 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002604 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002605 }
Eric Laurent81784c32012-11-19 14:55:58 -08002606 }
2607
Eric Laurent81784c32012-11-19 14:55:58 -08002608 mNumWrites++;
2609 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002610 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002611 return bytesWritten;
2612}
2613
2614void AudioFlinger::PlaybackThread::threadLoop_drain()
2615{
2616 if (mOutput->stream->drain) {
2617 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2618 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002619 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2620 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002621 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002622 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002623 }
2624 mOutput->stream->drain(mOutput->stream,
2625 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2626 : AUDIO_DRAIN_ALL);
2627 }
2628}
2629
2630void AudioFlinger::PlaybackThread::threadLoop_exit()
2631{
Eric Laurent275e8e92014-11-30 15:14:47 -08002632 {
2633 Mutex::Autolock _l(mLock);
2634 for (size_t i = 0; i < mTracks.size(); i++) {
2635 sp<Track> track = mTracks[i];
2636 track->invalidate();
2637 }
2638 }
Eric Laurent81784c32012-11-19 14:55:58 -08002639}
2640
2641/*
2642The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002643 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002644 - mActiveSleepTimeUs from activeSleepTimeUs()
2645 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08002646 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
2647 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08002648 - maxPeriod from frame count and sample rate (MIXER only)
2649
2650The parameters that affect these derived values are:
2651 - frame count
2652 - frame size
2653 - sample rate
2654 - device type: A2DP or not
2655 - device latency
2656 - format: PCM or not
2657 - active sleep time
2658 - idle sleep time
2659*/
2660
2661void AudioFlinger::PlaybackThread::cacheParameters_l()
2662{
Andy Hung25c2dac2014-02-27 14:56:00 -08002663 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002664 mActiveSleepTimeUs = activeSleepTimeUs();
2665 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08002666
2667 // make sure standby delay is not too short when connected to an A2DP sink to avoid
2668 // truncating audio when going to standby.
2669 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
2670 if ((mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != 0) {
2671 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
2672 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
2673 }
2674 }
Eric Laurent81784c32012-11-19 14:55:58 -08002675}
2676
2677void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2678{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002679 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08002680 this, streamType, mTracks.size());
2681 Mutex::Autolock _l(mLock);
2682
2683 size_t size = mTracks.size();
2684 for (size_t i = 0; i < size; i++) {
2685 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07002686 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002687 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08002688 }
2689 }
2690}
2691
2692status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2693{
Glenn Kastend848eb42016-03-08 13:42:11 -08002694 audio_session_t session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002695 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2696 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002697 bool ownsBuffer = false;
2698
2699 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Glenn Kastend848eb42016-03-08 13:42:11 -08002700 if (session > AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002701 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002702 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002703 if (mType != DIRECT) {
2704 size_t numSamples = mNormalFrameCount * mChannelCount;
2705 buffer = new int16_t[numSamples];
2706 memset(buffer, 0, numSamples * sizeof(int16_t));
2707 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2708 ownsBuffer = true;
2709 }
2710
2711 // Attach all tracks with same session ID to this chain.
2712 for (size_t i = 0; i < mTracks.size(); ++i) {
2713 sp<Track> track = mTracks[i];
2714 if (session == track->sessionId()) {
2715 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2716 buffer);
2717 track->setMainBuffer(buffer);
2718 chain->incTrackCnt();
2719 }
2720 }
2721
2722 // indicate all active tracks in the chain
2723 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2724 sp<Track> track = mActiveTracks[i].promote();
2725 if (track == 0) {
2726 continue;
2727 }
2728 if (session == track->sessionId()) {
2729 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2730 chain->incActiveTrackCnt();
2731 }
2732 }
2733 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002734 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08002735 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002736 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2737 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002738 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Glenn Kastend848eb42016-03-08 13:42:11 -08002739 // chains list in order to be processed last as it contains output stage effects.
Eric Laurent81784c32012-11-19 14:55:58 -08002740 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2741 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08002742 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08002743 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08002744 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08002745 // Effect chain for other sessions are inserted at beginning of effect
2746 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08002747 // sessions is not important.
2748 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
2749 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX,
2750 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08002751 size_t size = mEffectChains.size();
2752 size_t i = 0;
2753 for (i = 0; i < size; i++) {
2754 if (mEffectChains[i]->sessionId() < session) {
2755 break;
2756 }
2757 }
2758 mEffectChains.insertAt(chain, i);
2759 checkSuspendOnAddEffectChain_l(chain);
2760
2761 return NO_ERROR;
2762}
2763
2764size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2765{
Glenn Kastend848eb42016-03-08 13:42:11 -08002766 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08002767
2768 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2769
2770 for (size_t i = 0; i < mEffectChains.size(); i++) {
2771 if (chain == mEffectChains[i]) {
2772 mEffectChains.removeAt(i);
2773 // detach all active tracks from the chain
2774 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2775 sp<Track> track = mActiveTracks[i].promote();
2776 if (track == 0) {
2777 continue;
2778 }
2779 if (session == track->sessionId()) {
2780 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2781 chain.get(), session);
2782 chain->decActiveTrackCnt();
2783 }
2784 }
2785
2786 // detach all tracks with same session ID from this chain
2787 for (size_t i = 0; i < mTracks.size(); ++i) {
2788 sp<Track> track = mTracks[i];
2789 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002790 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002791 chain->decTrackCnt();
2792 }
2793 }
2794 break;
2795 }
2796 }
2797 return mEffectChains.size();
2798}
2799
2800status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2801 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2802{
2803 Mutex::Autolock _l(mLock);
2804 return attachAuxEffect_l(track, EffectId);
2805}
2806
2807status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2808 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2809{
2810 status_t status = NO_ERROR;
2811
2812 if (EffectId == 0) {
2813 track->setAuxBuffer(0, NULL);
2814 } else {
2815 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2816 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2817 if (effect != 0) {
2818 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2819 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2820 } else {
2821 status = INVALID_OPERATION;
2822 }
2823 } else {
2824 status = BAD_VALUE;
2825 }
2826 }
2827 return status;
2828}
2829
2830void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2831{
2832 for (size_t i = 0; i < mTracks.size(); ++i) {
2833 sp<Track> track = mTracks[i];
2834 if (track->auxEffectId() == effectId) {
2835 attachAuxEffect_l(track, 0);
2836 }
2837 }
2838}
2839
2840bool AudioFlinger::PlaybackThread::threadLoop()
2841{
2842 Vector< sp<Track> > tracksToRemove;
2843
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002844 mStandbyTimeNs = systemTime();
Eric Laurent81784c32012-11-19 14:55:58 -08002845
2846 // MIXER
2847 nsecs_t lastWarning = 0;
2848
2849 // DUPLICATING
2850 // FIXME could this be made local to while loop?
2851 writeFrames = 0;
2852
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002853 int lastGeneration = 0;
2854
Eric Laurent81784c32012-11-19 14:55:58 -08002855 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002856 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002857
2858 if (mType == MIXER) {
2859 sleepTimeShift = 0;
2860 }
2861
2862 CpuStats cpuStats;
2863 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2864
2865 acquireWakeLock();
2866
Glenn Kasten9e58b552013-01-18 15:09:48 -08002867 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2868 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2869 // and then that string will be logged at the next convenient opportunity.
2870 const char *logString = NULL;
2871
Eric Laurent664539d2013-09-23 18:24:31 -07002872 checkSilentMode_l();
2873
Eric Laurent81784c32012-11-19 14:55:58 -08002874 while (!exitPending())
2875 {
2876 cpuStats.sample(myName);
2877
2878 Vector< sp<EffectChain> > effectChains;
2879
Eric Laurent81784c32012-11-19 14:55:58 -08002880 { // scope for mLock
2881
2882 Mutex::Autolock _l(mLock);
2883
Eric Laurent021cf962014-05-13 10:18:14 -07002884 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002885
Glenn Kasten9e58b552013-01-18 15:09:48 -08002886 if (logString != NULL) {
2887 mNBLogWriter->logTimestamp();
2888 mNBLogWriter->log(logString);
2889 logString = NULL;
2890 }
2891
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002892 // Gather the framesReleased counters for all active tracks,
Andy Hunge10393e2015-06-12 13:59:33 -07002893 // and associate with the sink frames written out. We need
2894 // this to convert the sink timestamp to the track timestamp.
2895 if (mNormalSink != 0) {
Andy Hungc54b1ff2016-02-23 14:07:07 -08002896 // Note: The DuplicatingThread may not have a mNormalSink.
Andy Hung818e7a32016-02-16 18:08:07 -08002897 // We always fetch the timestamp here because often the downstream
2898 // sink will block whie writing.
2899 ExtendedTimestamp timestamp; // use private copy to fetch
2900 (void) mNormalSink->getTimestamp(timestamp);
2901 // copy over kernel info
2902 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
2903 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
2904 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
2905 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hungc54b1ff2016-02-23 14:07:07 -08002906 }
2907 // mFramesWritten for non-offloaded tracks are contiguous
2908 // even after standby() is called. This is useful for the track frame
2909 // to sink frame mapping.
2910 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
2911 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
2912 const size_t size = mActiveTracks.size();
2913 for (size_t i = 0; i < size; ++i) {
2914 sp<Track> t = mActiveTracks[i].promote();
2915 if (t != 0 && !t->isFastTrack()) {
2916 t->updateTrackFrameInfo(
2917 t->mAudioTrackServerProxy->framesReleased(),
2918 mFramesWritten,
2919 mTimestamp);
Andy Hunge10393e2015-06-12 13:59:33 -07002920 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002921 }
2922
Eric Laurent81784c32012-11-19 14:55:58 -08002923 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002924 if (mSignalPending) {
2925 // A signal was raised while we were unlocked
2926 mSignalPending = false;
2927 } else if (waitingAsyncCallback_l()) {
2928 if (exitPending()) {
2929 break;
2930 }
Marco Nelissen078538c2015-05-12 09:17:57 -07002931 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07002932 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07002933 releaseWakeLock_l();
2934 released = true;
2935 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002936 mWakeLockUids.clear();
2937 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002938 ALOGV("wait async completion");
2939 mWaitWorkCV.wait(mLock);
2940 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07002941 if (released) {
2942 acquireWakeLock_l();
2943 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002944 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
2945 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002946
2947 continue;
2948 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002949 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002950 isSuspended()) {
2951 // put audio hardware into standby after short delay
2952 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002953
2954 threadLoop_standby();
2955
2956 mStandby = true;
2957 }
2958
2959 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2960 // we're about to wait, flush the binder command buffer
2961 IPCThreadState::self()->flushCommands();
2962
2963 clearOutputTracks();
2964
2965 if (exitPending()) {
2966 break;
2967 }
2968
2969 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002970 mWakeLockUids.clear();
2971 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002972 // wait until we have something to do...
2973 ALOGV("%s going to sleep", myName.string());
2974 mWaitWorkCV.wait(mLock);
2975 ALOGV("%s waking up", myName.string());
2976 acquireWakeLock_l();
2977
2978 mMixerStatus = MIXER_IDLE;
2979 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2980 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002981 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002982 checkSilentMode_l();
2983
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002984 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
2985 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002986 if (mType == MIXER) {
2987 sleepTimeShift = 0;
2988 }
2989
2990 continue;
2991 }
2992 }
Eric Laurent81784c32012-11-19 14:55:58 -08002993 // mMixerStatusIgnoringFastTracks is also updated internally
2994 mMixerStatus = prepareTracks_l(&tracksToRemove);
2995
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002996 // compare with previously applied list
2997 if (lastGeneration != mActiveTracksGeneration) {
2998 // update wakelock
2999 updateWakeLockUids_l(mWakeLockUids);
3000 lastGeneration = mActiveTracksGeneration;
3001 }
3002
Eric Laurent81784c32012-11-19 14:55:58 -08003003 // prevent any changes in effect chain list and in each effect chain
3004 // during mixing and effect process as the audio buffers could be deleted
3005 // or modified if an effect is created or deleted
3006 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003007 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003008
Eric Laurentbfb1b832013-01-07 09:53:42 -08003009 if (mBytesRemaining == 0) {
3010 mCurrentWriteLength = 0;
3011 if (mMixerStatus == MIXER_TRACKS_READY) {
3012 // threadLoop_mix() sets mCurrentWriteLength
3013 threadLoop_mix();
3014 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3015 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003016 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003017 // must be written to HAL
3018 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003019 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003020 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003021 }
3022 }
Andy Hung98ef9782014-03-04 14:46:50 -08003023 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003024 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003025 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3026 // or mSinkBuffer (if there are no effects).
3027 //
3028 // This is done pre-effects computation; if effects change to
3029 // support higher precision, this needs to move.
3030 //
3031 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003032 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003033 if (mMixerBufferValid) {
3034 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3035 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3036
Andy Hung2ddee192015-12-18 17:34:44 -08003037 // mono blend occurs for mixer threads only (not direct or offloaded)
3038 // and is handled here if we're going directly to the sink.
3039 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003040 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3041 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003042 }
3043
Andy Hung98ef9782014-03-04 14:46:50 -08003044 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
3045 mNormalFrameCount * mChannelCount);
3046 }
3047
Eric Laurentbfb1b832013-01-07 09:53:42 -08003048 mBytesRemaining = mCurrentWriteLength;
3049 if (isSuspended()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003050 mSleepTimeUs = suspendSleepTimeUs();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003051 // simulate write to HAL when suspended
Andy Hung25c2dac2014-02-27 14:56:00 -08003052 mBytesWritten += mSinkBufferSize;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003053 mFramesWritten += mSinkBufferSize / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003054 mBytesRemaining = 0;
3055 }
Eric Laurent81784c32012-11-19 14:55:58 -08003056
Eric Laurentbfb1b832013-01-07 09:53:42 -08003057 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003058 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003059 for (size_t i = 0; i < effectChains.size(); i ++) {
3060 effectChains[i]->process_l();
3061 }
Eric Laurent81784c32012-11-19 14:55:58 -08003062 }
3063 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003064 // Process effect chains for offloaded thread even if no audio
3065 // was read from audio track: process only updates effect state
3066 // and thus does have to be synchronized with audio writes but may have
3067 // to be called while waiting for async write callback
3068 if (mType == OFFLOAD) {
3069 for (size_t i = 0; i < effectChains.size(); i ++) {
3070 effectChains[i]->process_l();
3071 }
3072 }
Eric Laurent81784c32012-11-19 14:55:58 -08003073
Andy Hung98ef9782014-03-04 14:46:50 -08003074 // Only if the Effects buffer is enabled and there is data in the
3075 // Effects buffer (buffer valid), we need to
3076 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003077 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003078 if (mEffectBufferValid) {
3079 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003080
3081 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003082 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3083 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003084 }
3085
Andy Hung98ef9782014-03-04 14:46:50 -08003086 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
3087 mNormalFrameCount * mChannelCount);
3088 }
3089
Eric Laurent81784c32012-11-19 14:55:58 -08003090 // enable changes in effect chain
3091 unlockEffectChains(effectChains);
3092
Eric Laurentbfb1b832013-01-07 09:53:42 -08003093 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003094 // mSleepTimeUs == 0 means we must write to audio hardware
3095 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003096 ssize_t ret = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003097 if (mBytesRemaining) {
Andy Hung08fb1742015-05-31 23:22:10 -07003098 ret = threadLoop_write();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003099 if (ret < 0) {
3100 mBytesRemaining = 0;
3101 } else {
3102 mBytesWritten += ret;
3103 mBytesRemaining -= ret;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003104 mFramesWritten += ret / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003105 }
3106 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3107 (mMixerStatus == MIXER_DRAIN_ALL)) {
3108 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003109 }
Andy Hung08fb1742015-05-31 23:22:10 -07003110 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003111 // write blocked detection
3112 nsecs_t now = systemTime();
3113 nsecs_t delta = now - mLastWriteTime;
Andy Hung08fb1742015-05-31 23:22:10 -07003114 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003115 mNumDelayedWrites++;
3116 if ((now - lastWarning) > kWarningThrottleNs) {
3117 ATRACE_NAME("underrun");
3118 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003119 (unsigned long long) ns2ms(delta), mNumDelayedWrites, this);
Glenn Kasten4944acb2013-08-19 08:39:20 -07003120 lastWarning = now;
3121 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003122 }
Andy Hung08fb1742015-05-31 23:22:10 -07003123
3124 if (mThreadThrottle
3125 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
3126 && ret > 0) { // we wrote something
3127 // Limit MixerThread data processing to no more than twice the
3128 // expected processing rate.
3129 //
3130 // This helps prevent underruns with NuPlayer and other applications
3131 // which may set up buffers that are close to the minimum size, or use
3132 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3133 //
3134 // The throttle smooths out sudden large data drains from the device,
3135 // e.g. when it comes out of standby, which often causes problems with
3136 // (1) mixer threads without a fast mixer (which has its own warm-up)
3137 // (2) minimum buffer sized tracks (even if the track is full,
3138 // the app won't fill fast enough to handle the sudden draw).
3139
3140 const int32_t deltaMs = delta / 1000000;
3141 const int32_t throttleMs = mHalfBufferMs - deltaMs;
3142 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3143 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003144 // notify of throttle start on verbose log
3145 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3146 "mixer(%p) throttle begin:"
3147 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003148 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003149 mThreadThrottleTimeMs += throttleMs;
3150 } else {
3151 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3152 if (diff > 0) {
3153 // notify of throttle end on debug log
3154 ALOGD("mixer(%p) throttle end: throttle time(%u)", this, diff);
3155 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3156 }
Andy Hung08fb1742015-05-31 23:22:10 -07003157 }
3158 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003159 }
Eric Laurent81784c32012-11-19 14:55:58 -08003160
Eric Laurentbfb1b832013-01-07 09:53:42 -08003161 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003162 ATRACE_BEGIN("sleep");
Eric Laurent51716182016-02-29 18:00:56 -08003163 if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
3164 Mutex::Autolock _l(mLock);
3165 if (!mSignalPending && !exitPending()) {
Eric Laurent3eaf66b2016-04-01 14:44:17 -07003166 // If more than one buffer has been written to the audio HAL since exiting
3167 // standby or last flush, do not sleep more than one buffer duration
3168 // since last write and not less than kDirectMinSleepTimeUs.
Eric Laurent51716182016-02-29 18:00:56 -08003169 // Wake up if a command is received
Eric Laurent51716182016-02-29 18:00:56 -08003170 uint32_t timeoutUs = mSleepTimeUs;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07003171 if (mBytesWritten >= (int64_t) mBufferSize) {
3172 nsecs_t now = systemTime();
3173 uint32_t deltaUs = (uint32_t)((now - mLastWriteTime) / 1000);
3174 if (timeoutUs + deltaUs > mBufferDurationUs) {
3175 if (mBufferDurationUs > deltaUs) {
3176 timeoutUs = mBufferDurationUs - deltaUs;
3177 if (timeoutUs < kDirectMinSleepTimeUs) {
3178 timeoutUs = kDirectMinSleepTimeUs;
3179 }
3180 } else {
Eric Laurent51716182016-02-29 18:00:56 -08003181 timeoutUs = kDirectMinSleepTimeUs;
3182 }
Eric Laurent51716182016-02-29 18:00:56 -08003183 }
3184 }
3185 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)timeoutUs));
3186 }
3187 } else {
3188 usleep(mSleepTimeUs);
3189 }
Glenn Kastene7754022014-10-31 12:11:26 -07003190 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003191 }
Eric Laurent81784c32012-11-19 14:55:58 -08003192 }
3193
3194 // Finally let go of removed track(s), without the lock held
3195 // since we can't guarantee the destructors won't acquire that
3196 // same lock. This will also mutate and push a new fast mixer state.
3197 threadLoop_removeTracks(tracksToRemove);
3198 tracksToRemove.clear();
3199
3200 // FIXME I don't understand the need for this here;
3201 // it was in the original code but maybe the
3202 // assignment in saveOutputTracks() makes this unnecessary?
3203 clearOutputTracks();
3204
3205 // Effect chains will be actually deleted here if they were removed from
3206 // mEffectChains list during mixing or effects processing
3207 effectChains.clear();
3208
3209 // FIXME Note that the above .clear() is no longer necessary since effectChains
3210 // is now local to this block, but will keep it for now (at least until merge done).
3211 }
3212
Eric Laurentbfb1b832013-01-07 09:53:42 -08003213 threadLoop_exit();
3214
Eric Laurentcf817a22014-08-04 20:36:31 -07003215 if (!mStandby) {
3216 threadLoop_standby();
3217 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003218 }
3219
3220 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003221 mWakeLockUids.clear();
3222 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08003223
3224 ALOGV("Thread %p type %d exiting", this, mType);
3225 return false;
3226}
3227
Eric Laurentbfb1b832013-01-07 09:53:42 -08003228// removeTracks_l() must be called with ThreadBase::mLock held
3229void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3230{
3231 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003232 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003233 for (size_t i=0 ; i<count ; i++) {
3234 const sp<Track>& track = tracksToRemove.itemAt(i);
3235 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003236 mWakeLockUids.remove(track->uid());
3237 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003238 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3239 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3240 if (chain != 0) {
3241 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3242 track->sessionId());
3243 chain->decActiveTrackCnt();
3244 }
3245 if (track->isTerminated()) {
3246 removeTrack_l(track);
3247 }
3248 }
3249 }
3250
3251}
Eric Laurent81784c32012-11-19 14:55:58 -08003252
Eric Laurentaccc1472013-09-20 09:36:34 -07003253status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3254{
3255 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08003256 ExtendedTimestamp ets;
3257 status_t status = mNormalSink->getTimestamp(ets);
3258 if (status == NO_ERROR) {
3259 status = ets.getBestTimestamp(&timestamp);
3260 }
3261 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07003262 }
Andy Hung9a1c8892014-12-03 11:37:42 -08003263 if ((mType == OFFLOAD || mType == DIRECT)
3264 && mOutput != NULL && mOutput->stream->get_presentation_position) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003265 uint64_t position64;
Phil Burk062e67a2015-02-11 13:40:50 -08003266 int ret = mOutput->getPresentationPosition(&position64, &timestamp.mTime);
Eric Laurentaccc1472013-09-20 09:36:34 -07003267 if (ret == 0) {
3268 timestamp.mPosition = (uint32_t)position64;
3269 return NO_ERROR;
3270 }
3271 }
3272 return INVALID_OPERATION;
3273}
Eric Laurent1c333e22014-05-20 10:48:17 -07003274
Eric Laurent054d9d32015-04-24 08:48:48 -07003275status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3276 audio_patch_handle_t *handle)
3277{
Glenn Kastenc05b8d72016-03-24 09:48:17 -07003278 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent054d9d32015-04-24 08:48:48 -07003279
Glenn Kastenc05b8d72016-03-24 09:48:17 -07003280 status_t status = PlaybackThread::createAudioPatch_l(patch, handle);
Eric Laurent054d9d32015-04-24 08:48:48 -07003281
3282 return status;
3283}
3284
Eric Laurent1c333e22014-05-20 10:48:17 -07003285status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3286 audio_patch_handle_t *handle)
3287{
3288 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003289
3290 // store new device and send to effects
3291 audio_devices_t type = AUDIO_DEVICE_NONE;
3292 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3293 type |= patch->sinks[i].ext.device.type;
3294 }
3295
3296#ifdef ADD_BATTERY_DATA
3297 // when changing the audio output device, call addBatteryData to notify
3298 // the change
3299 if (mOutDevice != type) {
3300 uint32_t params = 0;
3301 // check whether speaker is on
3302 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3303 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003304 }
3305
Eric Laurent054d9d32015-04-24 08:48:48 -07003306 audio_devices_t deviceWithoutSpeaker
3307 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3308 // check if any other device (except speaker) is on
3309 if (type & deviceWithoutSpeaker) {
3310 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3311 }
3312
3313 if (params != 0) {
3314 addBatteryData(params);
3315 }
3316 }
3317#endif
3318
3319 for (size_t i = 0; i < mEffectChains.size(); i++) {
3320 mEffectChains[i]->setDevice_l(type);
3321 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003322
3323 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3324 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3325 bool configChanged = mPrevOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003326 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003327 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003328
3329 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003330 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3331 status = hwDevice->create_audio_patch(hwDevice,
3332 patch->num_sources,
3333 patch->sources,
3334 patch->num_sinks,
3335 patch->sinks,
3336 handle);
3337 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003338 char *address;
3339 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3340 //FIXME: we only support address on first sink with HAL version < 3.0
3341 address = audio_device_address_to_parameter(
3342 patch->sinks[0].ext.device.type,
3343 patch->sinks[0].ext.device.address);
3344 } else {
3345 address = (char *)calloc(1, 1);
3346 }
3347 AudioParameter param = AudioParameter(String8(address));
3348 free(address);
3349 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), (int)type);
3350 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3351 param.toString().string());
3352 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003353 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003354 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003355 mPrevOutDevice = type;
Eric Laurente8726fe2015-06-26 09:39:24 -07003356 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3357 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003358 return status;
3359}
3360
Eric Laurent054d9d32015-04-24 08:48:48 -07003361status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3362{
Glenn Kastenc05b8d72016-03-24 09:48:17 -07003363 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent054d9d32015-04-24 08:48:48 -07003364
3365 status_t status = PlaybackThread::releaseAudioPatch_l(handle);
3366
Eric Laurent054d9d32015-04-24 08:48:48 -07003367 return status;
3368}
3369
Eric Laurent1c333e22014-05-20 10:48:17 -07003370status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3371{
3372 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003373
3374 mOutDevice = AUDIO_DEVICE_NONE;
3375
Eric Laurent1c333e22014-05-20 10:48:17 -07003376 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
3377 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3378 status = hwDevice->release_audio_patch(hwDevice, handle);
3379 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003380 AudioParameter param;
3381 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
3382 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3383 param.toString().string());
Eric Laurent1c333e22014-05-20 10:48:17 -07003384 }
3385 return status;
3386}
3387
Eric Laurent83b88082014-06-20 18:31:16 -07003388void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3389{
3390 Mutex::Autolock _l(mLock);
3391 mTracks.add(track);
3392}
3393
3394void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3395{
3396 Mutex::Autolock _l(mLock);
3397 destroyTrack_l(track);
3398}
3399
3400void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3401{
3402 ThreadBase::getAudioPortConfig(config);
3403 config->role = AUDIO_PORT_ROLE_SOURCE;
3404 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3405 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3406}
3407
Eric Laurent81784c32012-11-19 14:55:58 -08003408// ----------------------------------------------------------------------------
3409
3410AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003411 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3412 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003413 // mAudioMixer below
3414 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08003415 mFastMixerFutex(0),
3416 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08003417 // mOutputSink below
3418 // mPipeSink below
3419 // mNormalSink below
3420{
3421 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003422 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%zu, "
3423 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003424 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3425 mNormalFrameCount);
3426 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3427
Andy Hungfbfc3952015-01-15 13:33:51 -08003428 if (type == DUPLICATING) {
3429 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3430 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3431 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3432 return;
3433 }
Eric Laurent81784c32012-11-19 14:55:58 -08003434 // create an NBAIO sink for the HAL output stream, and negotiate
3435 mOutputSink = new AudioStreamOutSink(output->stream);
3436 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003437 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003438#if !LOG_NDEBUG
3439 ssize_t index =
3440#else
3441 (void)
3442#endif
3443 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003444 ALOG_ASSERT(index == 0);
3445
3446 // initialize fast mixer depending on configuration
3447 bool initFastMixer;
3448 switch (kUseFastMixer) {
3449 case FastMixer_Never:
3450 initFastMixer = false;
3451 break;
3452 case FastMixer_Always:
3453 initFastMixer = true;
3454 break;
3455 case FastMixer_Static:
3456 case FastMixer_Dynamic:
3457 initFastMixer = mFrameCount < mNormalFrameCount;
3458 break;
3459 }
3460 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003461 audio_format_t fastMixerFormat;
3462 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3463 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3464 } else {
3465 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3466 }
3467 if (mFormat != fastMixerFormat) {
3468 // change our Sink format to accept our intermediate precision
3469 mFormat = fastMixerFormat;
3470 free(mSinkBuffer);
3471 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3472 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3473 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3474 }
Eric Laurent81784c32012-11-19 14:55:58 -08003475
3476 // create a MonoPipe to connect our submix to FastMixer
3477 NBAIO_Format format = mOutputSink->format();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003478#ifdef TEE_SINK
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003479 NBAIO_Format origformat = format;
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003480#endif
Andy Hung1258c1a2014-05-23 21:22:17 -07003481 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07003482 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003483 format.mFormat = fastMixerFormat;
3484 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3485
Eric Laurent81784c32012-11-19 14:55:58 -08003486 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3487 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3488 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3489 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3490 const NBAIO_Format offers[1] = {format};
3491 size_t numCounterOffers = 0;
Glenn Kastenfc302fd2016-04-11 14:11:26 -07003492#if !LOG_NDEBUG || defined(TEE_SINK)
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003493 ssize_t index =
3494#else
3495 (void)
3496#endif
3497 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003498 ALOG_ASSERT(index == 0);
3499 monoPipe->setAvgFrames((mScreenState & 1) ?
3500 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3501 mPipeSink = monoPipe;
3502
Glenn Kasten46909e72013-02-26 09:20:22 -08003503#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003504 if (mTeeSinkOutputEnabled) {
3505 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003506 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3507 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003508 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003509 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003510 ALOG_ASSERT(index == 0);
3511 mTeeSink = teeSink;
3512 PipeReader *teeSource = new PipeReader(*teeSink);
3513 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003514 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003515 ALOG_ASSERT(index == 0);
3516 mTeeSource = teeSource;
3517 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003518#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003519
3520 // create fast mixer and configure it initially with just one fast track for our submix
3521 mFastMixer = new FastMixer();
3522 FastMixerStateQueue *sq = mFastMixer->sq();
3523#ifdef STATE_QUEUE_DUMP
3524 sq->setObserverDump(&mStateQueueObserverDump);
3525 sq->setMutatorDump(&mStateQueueMutatorDump);
3526#endif
3527 FastMixerState *state = sq->begin();
3528 FastTrack *fastTrack = &state->mFastTracks[0];
3529 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3530 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3531 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003532 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3533 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003534 fastTrack->mGeneration++;
3535 state->mFastTracksGen++;
3536 state->mTrackMask = 1;
3537 // fast mixer will use the HAL output sink
3538 state->mOutputSink = mOutputSink.get();
3539 state->mOutputSinkGen++;
3540 state->mFrameCount = mFrameCount;
3541 state->mCommand = FastMixerState::COLD_IDLE;
3542 // already done in constructor initialization list
3543 //mFastMixerFutex = 0;
3544 state->mColdFutexAddr = &mFastMixerFutex;
3545 state->mColdGen++;
3546 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003547#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003548 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003549#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003550 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3551 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003552 sq->end();
3553 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3554
3555 // start the fast mixer
3556 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3557 pid_t tid = mFastMixer->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003558 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003559
3560#ifdef AUDIO_WATCHDOG
3561 // create and start the watchdog
3562 mAudioWatchdog = new AudioWatchdog();
3563 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3564 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3565 tid = mAudioWatchdog->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003566 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003567#endif
3568
Eric Laurent81784c32012-11-19 14:55:58 -08003569 }
3570
3571 switch (kUseFastMixer) {
3572 case FastMixer_Never:
3573 case FastMixer_Dynamic:
3574 mNormalSink = mOutputSink;
3575 break;
3576 case FastMixer_Always:
3577 mNormalSink = mPipeSink;
3578 break;
3579 case FastMixer_Static:
3580 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3581 break;
3582 }
3583}
3584
3585AudioFlinger::MixerThread::~MixerThread()
3586{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003587 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003588 FastMixerStateQueue *sq = mFastMixer->sq();
3589 FastMixerState *state = sq->begin();
3590 if (state->mCommand == FastMixerState::COLD_IDLE) {
3591 int32_t old = android_atomic_inc(&mFastMixerFutex);
3592 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003593 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003594 }
3595 }
3596 state->mCommand = FastMixerState::EXIT;
3597 sq->end();
3598 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3599 mFastMixer->join();
3600 // Though the fast mixer thread has exited, it's state queue is still valid.
3601 // We'll use that extract the final state which contains one remaining fast track
3602 // corresponding to our sub-mix.
3603 state = sq->begin();
3604 ALOG_ASSERT(state->mTrackMask == 1);
3605 FastTrack *fastTrack = &state->mFastTracks[0];
3606 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3607 delete fastTrack->mBufferProvider;
3608 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003609 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003610#ifdef AUDIO_WATCHDOG
3611 if (mAudioWatchdog != 0) {
3612 mAudioWatchdog->requestExit();
3613 mAudioWatchdog->requestExitAndWait();
3614 mAudioWatchdog.clear();
3615 }
3616#endif
3617 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003618 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003619 delete mAudioMixer;
3620}
3621
3622
3623uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3624{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003625 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003626 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3627 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3628 }
3629 return latency;
3630}
3631
3632
3633void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3634{
3635 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3636}
3637
Eric Laurentbfb1b832013-01-07 09:53:42 -08003638ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003639{
3640 // FIXME we should only do one push per cycle; confirm this is true
3641 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003642 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003643 FastMixerStateQueue *sq = mFastMixer->sq();
3644 FastMixerState *state = sq->begin();
3645 if (state->mCommand != FastMixerState::MIX_WRITE &&
3646 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3647 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07003648
3649 // FIXME workaround for first HAL write being CPU bound on some devices
3650 ATRACE_BEGIN("write");
3651 mOutput->write((char *)mSinkBuffer, 0);
3652 ATRACE_END();
3653
Eric Laurent81784c32012-11-19 14:55:58 -08003654 int32_t old = android_atomic_inc(&mFastMixerFutex);
3655 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003656 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003657 }
3658#ifdef AUDIO_WATCHDOG
3659 if (mAudioWatchdog != 0) {
3660 mAudioWatchdog->resume();
3661 }
3662#endif
3663 }
3664 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003665#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003666 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003667 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003668#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003669 sq->end();
3670 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3671 if (kUseFastMixer == FastMixer_Dynamic) {
3672 mNormalSink = mPipeSink;
3673 }
3674 } else {
3675 sq->end(false /*didModify*/);
3676 }
3677 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003678 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003679}
3680
3681void AudioFlinger::MixerThread::threadLoop_standby()
3682{
3683 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003684 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003685 FastMixerStateQueue *sq = mFastMixer->sq();
3686 FastMixerState *state = sq->begin();
3687 if (!(state->mCommand & FastMixerState::IDLE)) {
3688 state->mCommand = FastMixerState::COLD_IDLE;
3689 state->mColdFutexAddr = &mFastMixerFutex;
3690 state->mColdGen++;
3691 mFastMixerFutex = 0;
3692 sq->end();
3693 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3694 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3695 if (kUseFastMixer == FastMixer_Dynamic) {
3696 mNormalSink = mOutputSink;
3697 }
3698#ifdef AUDIO_WATCHDOG
3699 if (mAudioWatchdog != 0) {
3700 mAudioWatchdog->pause();
3701 }
3702#endif
3703 } else {
3704 sq->end(false /*didModify*/);
3705 }
3706 }
3707 PlaybackThread::threadLoop_standby();
3708}
3709
Eric Laurentbfb1b832013-01-07 09:53:42 -08003710bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3711{
3712 return false;
3713}
3714
3715bool AudioFlinger::PlaybackThread::shouldStandby_l()
3716{
3717 return !mStandby;
3718}
3719
3720bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3721{
3722 Mutex::Autolock _l(mLock);
3723 return waitingAsyncCallback_l();
3724}
3725
Eric Laurent81784c32012-11-19 14:55:58 -08003726// shared by MIXER and DIRECT, overridden by DUPLICATING
3727void AudioFlinger::PlaybackThread::threadLoop_standby()
3728{
3729 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08003730 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003731 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003732 // discard any pending drain or write ack by incrementing sequence
3733 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3734 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003735 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003736 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3737 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003738 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003739 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003740}
3741
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003742void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3743{
3744 ALOGV("signal playback thread");
3745 broadcast_l();
3746}
3747
Eric Laurent81784c32012-11-19 14:55:58 -08003748void AudioFlinger::MixerThread::threadLoop_mix()
3749{
Eric Laurent81784c32012-11-19 14:55:58 -08003750 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08003751 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08003752 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003753 // increase sleep time progressively when application underrun condition clears.
3754 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3755 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3756 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003757 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003758 sleepTimeShift--;
3759 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003760 mSleepTimeUs = 0;
3761 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08003762 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003763
Eric Laurent81784c32012-11-19 14:55:58 -08003764}
3765
3766void AudioFlinger::MixerThread::threadLoop_sleepTime()
3767{
3768 // If no tracks are ready, sleep once for the duration of an output
3769 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003770 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003771 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003772 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
3773 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
3774 mSleepTimeUs = kMinThreadSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003775 }
3776 // reduce sleep time in case of consecutive application underruns to avoid
3777 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3778 // duration we would end up writing less data than needed by the audio HAL if
3779 // the condition persists.
3780 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3781 sleepTimeShift++;
3782 }
3783 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003784 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003785 }
3786 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003787 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3788 // before effects processing or output.
3789 if (mMixerBufferValid) {
3790 memset(mMixerBuffer, 0, mMixerBufferSize);
3791 } else {
3792 memset(mSinkBuffer, 0, mSinkBufferSize);
3793 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003794 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003795 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3796 "anticipated start");
3797 }
3798 // TODO add standby time extension fct of effect tail
3799}
3800
3801// prepareTracks_l() must be called with ThreadBase::mLock held
3802AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3803 Vector< sp<Track> > *tracksToRemove)
3804{
3805
3806 mixer_state mixerStatus = MIXER_IDLE;
3807 // find out which tracks need to be processed
3808 size_t count = mActiveTracks.size();
3809 size_t mixedTracks = 0;
3810 size_t tracksWithEffect = 0;
3811 // counts only _active_ fast tracks
3812 size_t fastTracks = 0;
3813 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3814
3815 float masterVolume = mMasterVolume;
3816 bool masterMute = mMasterMute;
3817
3818 if (masterMute) {
3819 masterVolume = 0;
3820 }
3821 // Delegate master volume control to effect in output mix effect chain if needed
3822 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3823 if (chain != 0) {
3824 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3825 chain->setVolume_l(&v, &v);
3826 masterVolume = (float)((v + (1 << 23)) >> 24);
3827 chain.clear();
3828 }
3829
3830 // prepare a new state to push
3831 FastMixerStateQueue *sq = NULL;
3832 FastMixerState *state = NULL;
3833 bool didModify = false;
3834 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003835 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003836 sq = mFastMixer->sq();
3837 state = sq->begin();
3838 }
3839
Andy Hung69aed5f2014-02-25 17:24:40 -08003840 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003841 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003842
Eric Laurent81784c32012-11-19 14:55:58 -08003843 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003844 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003845 if (t == 0) {
3846 continue;
3847 }
3848
3849 // this const just means the local variable doesn't change
3850 Track* const track = t.get();
3851
3852 // process fast tracks
3853 if (track->isFastTrack()) {
3854
3855 // It's theoretically possible (though unlikely) for a fast track to be created
3856 // and then removed within the same normal mix cycle. This is not a problem, as
3857 // the track never becomes active so it's fast mixer slot is never touched.
3858 // The converse, of removing an (active) track and then creating a new track
3859 // at the identical fast mixer slot within the same normal mix cycle,
3860 // is impossible because the slot isn't marked available until the end of each cycle.
3861 int j = track->mFastIndex;
3862 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
3863 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3864 FastTrack *fastTrack = &state->mFastTracks[j];
3865
3866 // Determine whether the track is currently in underrun condition,
3867 // and whether it had a recent underrun.
3868 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3869 FastTrackUnderruns underruns = ftDump->mUnderruns;
3870 uint32_t recentFull = (underruns.mBitFields.mFull -
3871 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3872 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3873 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3874 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3875 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3876 uint32_t recentUnderruns = recentPartial + recentEmpty;
3877 track->mObservedUnderruns = underruns;
3878 // don't count underruns that occur while stopping or pausing
3879 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07003880 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3881 recentUnderruns > 0) {
3882 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3883 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Phil Burk2812d9e2016-01-04 10:34:30 -08003884 } else {
3885 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Eric Laurent81784c32012-11-19 14:55:58 -08003886 }
3887
3888 // This is similar to the state machine for normal tracks,
3889 // with a few modifications for fast tracks.
3890 bool isActive = true;
3891 switch (track->mState) {
3892 case TrackBase::STOPPING_1:
3893 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08003894 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003895 track->mState = TrackBase::STOPPING_2;
3896 }
3897 break;
3898 case TrackBase::PAUSING:
3899 // ramp down is not yet implemented
3900 track->setPaused();
3901 break;
3902 case TrackBase::RESUMING:
3903 // ramp up is not yet implemented
3904 track->mState = TrackBase::ACTIVE;
3905 break;
3906 case TrackBase::ACTIVE:
3907 if (recentFull > 0 || recentPartial > 0) {
3908 // track has provided at least some frames recently: reset retry count
3909 track->mRetryCount = kMaxTrackRetries;
3910 }
3911 if (recentUnderruns == 0) {
3912 // no recent underruns: stay active
3913 break;
3914 }
3915 // there has recently been an underrun of some kind
3916 if (track->sharedBuffer() == 0) {
3917 // were any of the recent underruns "empty" (no frames available)?
3918 if (recentEmpty == 0) {
3919 // no, then ignore the partial underruns as they are allowed indefinitely
3920 break;
3921 }
3922 // there has recently been an "empty" underrun: decrement the retry counter
3923 if (--(track->mRetryCount) > 0) {
3924 break;
3925 }
3926 // indicate to client process that the track was disabled because of underrun;
3927 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08003928 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08003929 // remove from active list, but state remains ACTIVE [confusing but true]
3930 isActive = false;
3931 break;
3932 }
3933 // fall through
3934 case TrackBase::STOPPING_2:
3935 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003936 case TrackBase::STOPPED:
3937 case TrackBase::FLUSHED: // flush() while active
3938 // Check for presentation complete if track is inactive
3939 // We have consumed all the buffers of this track.
3940 // This would be incomplete if we auto-paused on underrun
3941 {
3942 size_t audioHALFrames =
3943 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08003944 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003945 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
3946 // track stays in active list until presentation is complete
3947 break;
3948 }
3949 }
3950 if (track->isStopping_2()) {
3951 track->mState = TrackBase::STOPPED;
3952 }
3953 if (track->isStopped()) {
3954 // Can't reset directly, as fast mixer is still polling this track
3955 // track->reset();
3956 // So instead mark this track as needing to be reset after push with ack
3957 resetMask |= 1 << i;
3958 }
3959 isActive = false;
3960 break;
3961 case TrackBase::IDLE:
3962 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08003963 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08003964 }
3965
3966 if (isActive) {
3967 // was it previously inactive?
3968 if (!(state->mTrackMask & (1 << j))) {
3969 ExtendedAudioBufferProvider *eabp = track;
3970 VolumeProvider *vp = track;
3971 fastTrack->mBufferProvider = eabp;
3972 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08003973 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003974 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08003975 fastTrack->mGeneration++;
3976 state->mTrackMask |= 1 << j;
3977 didModify = true;
3978 // no acknowledgement required for newly active tracks
3979 }
3980 // cache the combined master volume and stream type volume for fast mixer; this
3981 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08003982 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08003983 ++fastTracks;
3984 } else {
3985 // was it previously active?
3986 if (state->mTrackMask & (1 << j)) {
3987 fastTrack->mBufferProvider = NULL;
3988 fastTrack->mGeneration++;
3989 state->mTrackMask &= ~(1 << j);
3990 didModify = true;
3991 // If any fast tracks were removed, we must wait for acknowledgement
3992 // because we're about to decrement the last sp<> on those tracks.
3993 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3994 } else {
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08003995 LOG_ALWAYS_FATAL("fast track %d should have been active; "
3996 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
3997 j, track->mState, state->mTrackMask, recentUnderruns,
3998 track->sharedBuffer() != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003999 }
4000 tracksToRemove->add(track);
4001 // Avoids a misleading display in dumpsys
4002 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
4003 }
4004 continue;
4005 }
4006
4007 { // local variable scope to avoid goto warning
4008
4009 audio_track_cblk_t* cblk = track->cblk();
4010
4011 // The first time a track is added we wait
4012 // for all its buffers to be filled before processing it
4013 int name = track->name();
4014 // make sure that we have enough frames to mix one full buffer.
4015 // enforce this condition only once to enable draining the buffer in case the client
4016 // app does not call stop() and relies on underrun to stop:
4017 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
4018 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004019 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07004020 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004021 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004022
4023 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004024 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004025 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
4026 // add frames already consumed but not yet released by the resampler
4027 // because mAudioTrackServerProxy->framesReady() will include these frames
4028 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
4029
Eric Laurent81784c32012-11-19 14:55:58 -08004030 uint32_t minFrames = 1;
4031 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
4032 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004033 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08004034 }
Eric Laurent13e4c962013-12-20 17:36:01 -08004035
4036 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07004037 if (ATRACE_ENABLED()) {
4038 // I wish we had formatted trace names
4039 char traceName[16];
4040 strcpy(traceName, "nRdy");
4041 int name = track->name();
4042 if (AudioMixer::TRACK0 <= name &&
4043 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
4044 name -= AudioMixer::TRACK0;
4045 traceName[4] = (name / 10) + '0';
4046 traceName[5] = (name % 10) + '0';
4047 } else {
4048 traceName[4] = '?';
4049 traceName[5] = '?';
4050 }
4051 traceName[6] = '\0';
4052 ATRACE_INT(traceName, framesReady);
4053 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004054 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08004055 !track->isPaused() && !track->isTerminated())
4056 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004057 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004058
4059 mixedTracks++;
4060
Andy Hung69aed5f2014-02-25 17:24:40 -08004061 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
4062 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08004063 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08004064 if (track->mainBuffer() != mSinkBuffer &&
4065 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004066 if (mEffectBufferEnabled) {
4067 mEffectBufferValid = true; // Later can set directly.
4068 }
Eric Laurent81784c32012-11-19 14:55:58 -08004069 chain = getEffectChain_l(track->sessionId());
4070 // Delegate volume control to effect in track effect chain if needed
4071 if (chain != 0) {
4072 tracksWithEffect++;
4073 } else {
4074 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
4075 "session %d",
4076 name, track->sessionId());
4077 }
4078 }
4079
4080
4081 int param = AudioMixer::VOLUME;
4082 if (track->mFillingUpStatus == Track::FS_FILLED) {
4083 // no ramp for the first volume setting
4084 track->mFillingUpStatus = Track::FS_ACTIVE;
4085 if (track->mState == TrackBase::RESUMING) {
4086 track->mState = TrackBase::ACTIVE;
4087 param = AudioMixer::RAMP_VOLUME;
4088 }
4089 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004090 // FIXME should not make a decision based on mServer
4091 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004092 // If the track is stopped before the first frame was mixed,
4093 // do not apply ramp
4094 param = AudioMixer::RAMP_VOLUME;
4095 }
4096
4097 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07004098 uint32_t vl, vr; // in U8.24 integer format
4099 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08004100 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07004101 vl = vr = 0;
4102 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08004103 if (track->isPausing()) {
4104 track->setPaused();
4105 }
4106 } else {
4107
4108 // read original volumes with volume control
4109 float typeVolume = mStreamTypes[track->streamType()].volume;
4110 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004111 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004112 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07004113 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
4114 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08004115 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07004116 if (vlf > GAIN_FLOAT_UNITY) {
4117 ALOGV("Track left volume out of range: %.3g", vlf);
4118 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004119 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07004120 if (vrf > GAIN_FLOAT_UNITY) {
4121 ALOGV("Track right volume out of range: %.3g", vrf);
4122 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004123 }
4124 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07004125 vlf *= v;
4126 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08004127 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07004128 // then derive vl and vr as U8.24 versions for the effect chain
4129 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
4130 vl = (uint32_t) (scaleto8_24 * vlf);
4131 vr = (uint32_t) (scaleto8_24 * vrf);
4132 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08004133 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08004134 // send level comes from shared memory and so may be corrupt
4135 if (sendLevel > MAX_GAIN_INT) {
4136 ALOGV("Track send level out of range: %04X", sendLevel);
4137 sendLevel = MAX_GAIN_INT;
4138 }
Andy Hung6be49402014-05-30 10:42:03 -07004139 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4140 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08004141 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004142
Eric Laurent81784c32012-11-19 14:55:58 -08004143 // Delegate volume control to effect in track effect chain if needed
4144 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4145 // Do not ramp volume if volume is controlled by effect
4146 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08004147 // Update remaining floating point volume levels
4148 vlf = (float)vl / (1 << 24);
4149 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004150 track->mHasVolumeController = true;
4151 } else {
4152 // force no volume ramp when volume controller was just disabled or removed
4153 // from effect chain to avoid volume spike
4154 if (track->mHasVolumeController) {
4155 param = AudioMixer::VOLUME;
4156 }
4157 track->mHasVolumeController = false;
4158 }
4159
Eric Laurent81784c32012-11-19 14:55:58 -08004160 // XXX: these things DON'T need to be done each time
4161 mAudioMixer->setBufferProvider(name, track);
4162 mAudioMixer->enable(name);
4163
Andy Hung6be49402014-05-30 10:42:03 -07004164 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
4165 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
4166 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004167 mAudioMixer->setParameter(
4168 name,
4169 AudioMixer::TRACK,
4170 AudioMixer::FORMAT, (void *)track->format());
4171 mAudioMixer->setParameter(
4172 name,
4173 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004174 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004175 mAudioMixer->setParameter(
4176 name,
4177 AudioMixer::TRACK,
4178 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004179 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004180 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004181 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004182 if (reqSampleRate == 0) {
4183 reqSampleRate = mSampleRate;
4184 } else if (reqSampleRate > maxSampleRate) {
4185 reqSampleRate = maxSampleRate;
4186 }
Eric Laurent81784c32012-11-19 14:55:58 -08004187 mAudioMixer->setParameter(
4188 name,
4189 AudioMixer::RESAMPLE,
4190 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004191 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004192
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004193 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004194 mAudioMixer->setParameter(
4195 name,
4196 AudioMixer::TIMESTRETCH,
4197 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004198 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004199
Andy Hung69aed5f2014-02-25 17:24:40 -08004200 /*
4201 * Select the appropriate output buffer for the track.
4202 *
Andy Hung98ef9782014-03-04 14:46:50 -08004203 * Tracks with effects go into their own effects chain buffer
4204 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004205 *
4206 * Other tracks can use mMixerBuffer for higher precision
4207 * channel accumulation. If this buffer is enabled
4208 * (mMixerBufferEnabled true), then selected tracks will accumulate
4209 * into it.
4210 *
4211 */
4212 if (mMixerBufferEnabled
4213 && (track->mainBuffer() == mSinkBuffer
4214 || track->mainBuffer() == mMixerBuffer)) {
4215 mAudioMixer->setParameter(
4216 name,
4217 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004218 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004219 mAudioMixer->setParameter(
4220 name,
4221 AudioMixer::TRACK,
4222 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4223 // TODO: override track->mainBuffer()?
4224 mMixerBufferValid = true;
4225 } else {
4226 mAudioMixer->setParameter(
4227 name,
4228 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004229 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004230 mAudioMixer->setParameter(
4231 name,
4232 AudioMixer::TRACK,
4233 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4234 }
Eric Laurent81784c32012-11-19 14:55:58 -08004235 mAudioMixer->setParameter(
4236 name,
4237 AudioMixer::TRACK,
4238 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4239
4240 // reset retry count
4241 track->mRetryCount = kMaxTrackRetries;
4242
4243 // If one track is ready, set the mixer ready if:
4244 // - the mixer was not ready during previous round OR
4245 // - no other track is not ready
4246 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4247 mixerStatus != MIXER_TRACKS_ENABLED) {
4248 mixerStatus = MIXER_TRACKS_READY;
4249 }
4250 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004251 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hung08fb1742015-05-31 23:22:10 -07004252 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)",
4253 track, framesReady, desiredFrames);
Glenn Kasten82aaf942013-07-17 16:05:07 -07004254 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08004255 } else {
4256 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004257 }
Phil Burk2812d9e2016-01-04 10:34:30 -08004258
Eric Laurent81784c32012-11-19 14:55:58 -08004259 // clear effect chain input buffer if an active track underruns to avoid sending
4260 // previous audio buffer again to effects
4261 chain = getEffectChain_l(track->sessionId());
4262 if (chain != 0) {
4263 chain->clearInputBuffer();
4264 }
4265
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004266 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004267 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4268 track->isStopped() || track->isPaused()) {
4269 // We have consumed all the buffers of this track.
4270 // Remove it from the list of active tracks.
4271 // TODO: use actual buffer filling status instead of latency when available from
4272 // audio HAL
4273 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004274 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004275 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4276 if (track->isStopped()) {
4277 track->reset();
4278 }
4279 tracksToRemove->add(track);
4280 }
4281 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004282 // No buffers for this track. Give it a few chances to
4283 // fill a buffer, then remove it from active list.
4284 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004285 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004286 tracksToRemove->add(track);
4287 // indicate to client process that the track was disabled because of underrun;
4288 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004289 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004290 // If one track is not ready, mark the mixer also not ready if:
4291 // - the mixer was ready during previous round OR
4292 // - no other track is ready
4293 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4294 mixerStatus != MIXER_TRACKS_READY) {
4295 mixerStatus = MIXER_TRACKS_ENABLED;
4296 }
4297 }
4298 mAudioMixer->disable(name);
4299 }
4300
4301 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08004302
4303 }
4304
4305 // Push the new FastMixer state if necessary
4306 bool pauseAudioWatchdog = false;
4307 if (didModify) {
4308 state->mFastTracksGen++;
4309 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4310 if (kUseFastMixer == FastMixer_Dynamic &&
4311 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4312 state->mCommand = FastMixerState::COLD_IDLE;
4313 state->mColdFutexAddr = &mFastMixerFutex;
4314 state->mColdGen++;
4315 mFastMixerFutex = 0;
4316 if (kUseFastMixer == FastMixer_Dynamic) {
4317 mNormalSink = mOutputSink;
4318 }
4319 // If we go into cold idle, need to wait for acknowledgement
4320 // so that fast mixer stops doing I/O.
4321 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4322 pauseAudioWatchdog = true;
4323 }
Eric Laurent81784c32012-11-19 14:55:58 -08004324 }
4325 if (sq != NULL) {
4326 sq->end(didModify);
4327 sq->push(block);
4328 }
4329#ifdef AUDIO_WATCHDOG
4330 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4331 mAudioWatchdog->pause();
4332 }
4333#endif
4334
4335 // Now perform the deferred reset on fast tracks that have stopped
4336 while (resetMask != 0) {
4337 size_t i = __builtin_ctz(resetMask);
4338 ALOG_ASSERT(i < count);
4339 resetMask &= ~(1 << i);
4340 sp<Track> t = mActiveTracks[i].promote();
4341 if (t == 0) {
4342 continue;
4343 }
4344 Track* track = t.get();
4345 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4346 track->reset();
4347 }
4348
4349 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004350 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004351
Eric Laurent97d547d2014-09-02 14:45:53 -07004352 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4353 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004354 }
4355
4356 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004357 // as long as there are effects we should clear the effects buffer, to avoid
4358 // passing a non-clean buffer to the effect chain
4359 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004360 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004361 // sink or mix buffer must be cleared if all tracks are connected to an
4362 // effect chain as in this case the mixer will not write to the sink or mix buffer
4363 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004364 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4365 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004366 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004367 if (mMixerBufferValid) {
4368 memset(mMixerBuffer, 0, mMixerBufferSize);
4369 // TODO: In testing, mSinkBuffer below need not be cleared because
4370 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4371 // after mixing.
4372 //
4373 // To enforce this guarantee:
4374 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4375 // (mixedTracks == 0 && fastTracks > 0))
4376 // must imply MIXER_TRACKS_READY.
4377 // Later, we may clear buffers regardless, and skip much of this logic.
4378 }
Andy Hung98ef9782014-03-04 14:46:50 -08004379 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004380 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004381 }
4382
4383 // if any fast tracks, then status is ready
4384 mMixerStatusIgnoringFastTracks = mixerStatus;
4385 if (fastTracks > 0) {
4386 mixerStatus = MIXER_TRACKS_READY;
4387 }
4388 return mixerStatus;
4389}
4390
4391// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07004392int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
Glenn Kastend848eb42016-03-08 13:42:11 -08004393 audio_format_t format, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08004394{
Andy Hunge8a1ced2014-05-09 15:02:21 -07004395 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08004396}
4397
4398// deleteTrackName_l() must be called with ThreadBase::mLock held
4399void AudioFlinger::MixerThread::deleteTrackName_l(int name)
4400{
4401 ALOGV("remove track (%d) and delete from mixer", name);
4402 mAudioMixer->deleteTrackName(name);
4403}
4404
Eric Laurent10351942014-05-08 18:49:52 -07004405// checkForNewParameter_l() must be called with ThreadBase::mLock held
4406bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4407 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004408{
Eric Laurent81784c32012-11-19 14:55:58 -08004409 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08004410 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004411
Eric Laurent10351942014-05-08 18:49:52 -07004412 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004413
Glenn Kastenc05b8d72016-03-24 09:48:17 -07004414 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004415
Eric Laurent10351942014-05-08 18:49:52 -07004416 AudioParameter param = AudioParameter(keyValuePair);
4417 int value;
4418 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4419 reconfig = true;
4420 }
4421 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004422 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004423 status = BAD_VALUE;
4424 } else {
4425 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004426 reconfig = true;
4427 }
Eric Laurent10351942014-05-08 18:49:52 -07004428 }
4429 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004430 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004431 status = BAD_VALUE;
4432 } else {
4433 // no need to save value, since it's constant
4434 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004435 }
Eric Laurent10351942014-05-08 18:49:52 -07004436 }
4437 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4438 // do not accept frame count changes if tracks are open as the track buffer
4439 // size depends on frame count and correct behavior would not be guaranteed
4440 // if frame count is changed after track creation
4441 if (!mTracks.isEmpty()) {
4442 status = INVALID_OPERATION;
4443 } else {
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::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004448#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004449 // when changing the audio output device, call addBatteryData to notify
4450 // the change
4451 if (mOutDevice != value) {
4452 uint32_t params = 0;
4453 // check whether speaker is on
4454 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4455 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004456 }
Eric Laurent10351942014-05-08 18:49:52 -07004457
4458 audio_devices_t deviceWithoutSpeaker
4459 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4460 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07004461 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07004462 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4463 }
4464
4465 if (params != 0) {
4466 addBatteryData(params);
4467 }
4468 }
Eric Laurent81784c32012-11-19 14:55:58 -08004469#endif
4470
Eric Laurent10351942014-05-08 18:49:52 -07004471 // forward device change to effects that have requested to be
4472 // aware of attached audio device.
4473 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08004474 a2dpDeviceChanged =
4475 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07004476 mOutDevice = value;
4477 for (size_t i = 0; i < mEffectChains.size(); i++) {
4478 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004479 }
4480 }
Eric Laurent10351942014-05-08 18:49:52 -07004481 }
Eric Laurent81784c32012-11-19 14:55:58 -08004482
Eric Laurent10351942014-05-08 18:49:52 -07004483 if (status == NO_ERROR) {
4484 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4485 keyValuePair.string());
4486 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004487 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004488 mStandby = true;
4489 mBytesWritten = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004490 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Eric Laurent10351942014-05-08 18:49:52 -07004491 keyValuePair.string());
Eric Laurent81784c32012-11-19 14:55:58 -08004492 }
Eric Laurent10351942014-05-08 18:49:52 -07004493 if (status == NO_ERROR && reconfig) {
4494 readOutputParameters_l();
4495 delete mAudioMixer;
4496 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4497 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004498 int name = getTrackName_l(mTracks[i]->mChannelMask,
4499 mTracks[i]->mFormat, mTracks[i]->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07004500 if (name < 0) {
4501 break;
4502 }
4503 mTracks[i]->mName = name;
4504 }
Eric Laurent73e26b62015-04-27 16:55:58 -07004505 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004506 }
Eric Laurent81784c32012-11-19 14:55:58 -08004507 }
4508
Eric Laurent42537be2016-01-08 17:16:42 -08004509 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08004510}
4511
4512
4513void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4514{
Eric Laurent81784c32012-11-19 14:55:58 -08004515 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07004516 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Elliott Hughes87cebad2014-05-22 10:14:43 -07004517 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Andy Hung2ddee192015-12-18 17:34:44 -08004518 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent81784c32012-11-19 14:55:58 -08004519
4520 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten2f90c512015-12-02 11:40:09 -08004521 // while we are dumping it. It may be inconsistent, but it won't mutate!
4522 // This is a large object so we place it on the heap.
4523 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
4524 const FastMixerDumpState *copy = new FastMixerDumpState(mFastMixerDumpState);
4525 copy->dump(fd);
4526 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08004527
4528#ifdef STATE_QUEUE_DUMP
4529 // Similar for state queue
4530 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4531 observerCopy.dump(fd);
4532 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4533 mutatorCopy.dump(fd);
4534#endif
4535
Glenn Kasten46909e72013-02-26 09:20:22 -08004536#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004537 // Write the tee output to a .wav file
4538 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08004539#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004540
4541#ifdef AUDIO_WATCHDOG
4542 if (mAudioWatchdog != 0) {
4543 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4544 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4545 wdCopy.dump(fd);
4546 }
4547#endif
4548}
4549
4550uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4551{
4552 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4553}
4554
4555uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4556{
4557 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4558}
4559
4560void AudioFlinger::MixerThread::cacheParameters_l()
4561{
4562 PlaybackThread::cacheParameters_l();
4563
4564 // FIXME: Relaxed timing because of a certain device that can't meet latency
4565 // Should be reduced to 2x after the vendor fixes the driver issue
4566 // increase threshold again due to low power audio mode. The way this warning
4567 // threshold is calculated and its usefulness should be reconsidered anyway.
4568 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4569}
4570
4571// ----------------------------------------------------------------------------
4572
4573AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent51716182016-02-29 18:00:56 -08004574 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady,
4575 uint32_t bitRate)
4576 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady, bitRate)
Eric Laurent81784c32012-11-19 14:55:58 -08004577 // mLeftVolFloat, mRightVolFloat
4578{
4579}
4580
Eric Laurentbfb1b832013-01-07 09:53:42 -08004581AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4582 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurent51716182016-02-29 18:00:56 -08004583 ThreadBase::type_t type, bool systemReady, uint32_t bitRate)
4584 : PlaybackThread(audioFlinger, output, id, device, type, systemReady, bitRate)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004585 // mLeftVolFloat, mRightVolFloat
4586{
4587}
4588
Eric Laurent81784c32012-11-19 14:55:58 -08004589AudioFlinger::DirectOutputThread::~DirectOutputThread()
4590{
4591}
4592
Eric Laurentbfb1b832013-01-07 09:53:42 -08004593void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
4594{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004595 float left, right;
4596
4597 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4598 left = right = 0;
4599 } else {
4600 float typeVolume = mStreamTypes[track->streamType()].volume;
4601 float v = mMasterVolume * typeVolume;
4602 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004603 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4604 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4605 if (left > GAIN_FLOAT_UNITY) {
4606 left = GAIN_FLOAT_UNITY;
4607 }
4608 left *= v;
4609 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4610 if (right > GAIN_FLOAT_UNITY) {
4611 right = GAIN_FLOAT_UNITY;
4612 }
4613 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004614 }
4615
4616 if (lastTrack) {
4617 if (left != mLeftVolFloat || right != mRightVolFloat) {
4618 mLeftVolFloat = left;
4619 mRightVolFloat = right;
4620
4621 // Convert volumes from float to 8.24
4622 uint32_t vl = (uint32_t)(left * (1 << 24));
4623 uint32_t vr = (uint32_t)(right * (1 << 24));
4624
4625 // Delegate volume control to effect in track effect chain if needed
4626 // only one effect chain can be present on DirectOutputThread, so if
4627 // there is one, the track is connected to it
4628 if (!mEffectChains.isEmpty()) {
4629 mEffectChains[0]->setVolume_l(&vl, &vr);
4630 left = (float)vl / (1 << 24);
4631 right = (float)vr / (1 << 24);
4632 }
4633 if (mOutput->stream->set_volume) {
4634 mOutput->stream->set_volume(mOutput->stream, left, right);
4635 }
4636 }
4637 }
4638}
4639
Phil Burk43b4dcc2015-06-09 16:53:44 -07004640void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
4641{
4642 sp<Track> previousTrack = mPreviousTrack.promote();
4643 sp<Track> latestTrack = mLatestActiveTrack.promote();
4644
Eric Laurent0f0631e2015-07-06 18:01:25 -07004645 if (previousTrack != 0 && latestTrack != 0) {
4646 if (mType == DIRECT) {
4647 if (previousTrack.get() != latestTrack.get()) {
4648 mFlushPending = true;
4649 }
4650 } else /* mType == OFFLOAD */ {
4651 if (previousTrack->sessionId() != latestTrack->sessionId()) {
4652 mFlushPending = true;
4653 }
4654 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004655 }
4656 PlaybackThread::onAddNewTrack_l();
4657}
Eric Laurentbfb1b832013-01-07 09:53:42 -08004658
Eric Laurent81784c32012-11-19 14:55:58 -08004659AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4660 Vector< sp<Track> > *tracksToRemove
4661)
4662{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004663 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004664 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004665 bool doHwPause = false;
4666 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004667
4668 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07004669 for (size_t i = 0; i < count; i++) {
4670 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08004671 // The track died recently
4672 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004673 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08004674 }
4675
Phil Burk43b4dcc2015-06-09 16:53:44 -07004676 if (t->isInvalid()) {
4677 ALOGW("An invalidated track shouldn't be in active list");
4678 tracksToRemove->add(t);
4679 continue;
4680 }
4681
Eric Laurent81784c32012-11-19 14:55:58 -08004682 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004683#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08004684 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004685#endif
Eric Laurentfd477972013-10-25 18:10:40 -07004686 // Only consider last track started for volume and mixer state control.
4687 // In theory an older track could underrun and restart after the new one starts
4688 // but as we only care about the transition phase between two tracks on a
4689 // direct output, it is not a problem to ignore the underrun case.
4690 sp<Track> l = mLatestActiveTrack.promote();
4691 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004692
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004693 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004694 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004695 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004696 doHwPause = true;
4697 mHwPaused = true;
4698 }
4699 tracksToRemove->add(track);
4700 } else if (track->isFlushPending()) {
4701 track->flushAck();
4702 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004703 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004704 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004705 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004706 track->resumeAck();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004707 if (last && mHwPaused) {
4708 doHwResume = true;
4709 mHwPaused = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004710 }
4711 }
4712
Eric Laurent81784c32012-11-19 14:55:58 -08004713 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004714 // for all its buffers to be filled before processing it.
4715 // Allow draining the buffer in case the client
4716 // app does not call stop() and relies on underrun to stop:
4717 // hence the test on (track->mRetryCount > 1).
4718 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07004719 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08004720 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004721 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08004722 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004723 minFrames = mNormalFrameCount;
4724 } else {
4725 minFrames = 1;
4726 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004727
Eric Laurentab5cdba2014-06-09 17:22:27 -07004728 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4729 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004730 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004731 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004732
4733 if (track->mFillingUpStatus == Track::FS_FILLED) {
4734 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004735 // make sure processVolume_l() will apply new volume even if 0
4736 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004737 if (!mHwSupportsPause) {
4738 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004739 }
4740 }
4741
4742 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004743 processVolume_l(track, last);
4744 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004745 sp<Track> previousTrack = mPreviousTrack.promote();
4746 if (previousTrack != 0) {
4747 if (track != previousTrack.get()) {
4748 // Flush any data still being written from last track
4749 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07004750 // Invalidate previous track to force a seek when resuming.
4751 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004752 }
4753 }
4754 mPreviousTrack = track;
4755
Eric Laurentd595b7c2013-04-03 17:27:56 -07004756 // reset retry count
4757 track->mRetryCount = kMaxTrackRetriesDirect;
4758 mActiveTrack = t;
4759 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07004760 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004761 doHwResume = true;
4762 mHwPaused = false;
4763 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004764 }
Eric Laurent81784c32012-11-19 14:55:58 -08004765 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004766 // clear effect chain input buffer if the last active track started underruns
4767 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004768 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004769 mEffectChains[0]->clearInputBuffer();
4770 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004771 if (track->isStopping_1()) {
4772 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07004773 if (last && mHwPaused) {
4774 doHwResume = true;
4775 mHwPaused = false;
4776 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004777 }
4778 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4779 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004780 // We have consumed all the buffers of this track.
4781 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004782 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08004783 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004784 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4785 } else {
4786 audioHALFrames = 0;
4787 }
4788
Andy Hung818e7a32016-02-16 18:08:07 -08004789 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004790 if (mStandby || !last ||
4791 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004792 if (track->isStopping_2()) {
4793 track->mState = TrackBase::STOPPED;
4794 }
Eric Laurent81784c32012-11-19 14:55:58 -08004795 if (track->isStopped()) {
4796 track->reset();
4797 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004798 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004799 }
4800 } else {
4801 // No buffers for this track. Give it a few chances to
4802 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004803 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004804 if (--(track->mRetryCount) <= 0) {
4805 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004806 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004807 // indicate to client process that the track was disabled because of underrun;
4808 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004809 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004810 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07004811 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
4812 "minFrames = %u, mFormat = %#x",
4813 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08004814 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07004815 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004816 doHwPause = true;
4817 mHwPaused = true;
4818 }
Eric Laurent81784c32012-11-19 14:55:58 -08004819 }
4820 }
4821 }
4822 }
4823
Eric Laurentd1f69b02014-12-15 14:33:13 -08004824 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07004825 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004826 for (size_t i = 0; i < mTracks.size(); i++) {
4827 if (mTracks[i]->isFlushPending()) {
4828 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004829 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004830 }
4831 }
4832 }
4833
4834 // make sure the pause/flush/resume sequence is executed in the right order.
4835 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4836 // before flush and then resume HW. This can happen in case of pause/flush/resume
4837 // if resume is received before pause is executed.
4838 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07004839 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004840 mOutput->stream->pause(mOutput->stream);
4841 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004842 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004843 flushHw_l();
4844 }
4845 if (mHwSupportsPause && !mStandby && doHwResume) {
4846 mOutput->stream->resume(mOutput->stream);
4847 }
Eric Laurent81784c32012-11-19 14:55:58 -08004848 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004849 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004850
4851 return mixerStatus;
4852}
4853
4854void AudioFlinger::DirectOutputThread::threadLoop_mix()
4855{
Eric Laurent81784c32012-11-19 14:55:58 -08004856 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08004857 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004858 // output audio to hardware
4859 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07004860 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004861 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08004862 status_t status = mActiveTrack->getNextBuffer(&buffer);
4863 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08004864 // no need to pad with 0 for compressed audio
4865 if (audio_has_proportional_frames(mFormat)) {
4866 memset(curBuf, 0, frameCount * mFrameSize);
4867 }
Eric Laurent81784c32012-11-19 14:55:58 -08004868 break;
4869 }
4870 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
4871 frameCount -= buffer.frameCount;
4872 curBuf += buffer.frameCount * mFrameSize;
4873 mActiveTrack->releaseBuffer(&buffer);
4874 }
Andy Hung2098f272014-02-27 14:00:06 -08004875 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004876 mSleepTimeUs = 0;
4877 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004878 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004879}
4880
4881void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
4882{
Eric Laurentd1f69b02014-12-15 14:33:13 -08004883 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004884 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004885 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004886 return;
4887 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004888 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004889 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurent51716182016-02-29 18:00:56 -08004890 // For compressed offload, use faster sleep time when underruning until more than an
4891 // entire buffer was written to the audio HAL
4892 if (!audio_has_proportional_frames(mFormat) &&
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004893 (mType == OFFLOAD) && (mBytesWritten < (int64_t) mBufferSize)) {
Eric Laurent51716182016-02-29 18:00:56 -08004894 mSleepTimeUs = kDirectMinSleepTimeUs;
4895 } else {
4896 mSleepTimeUs = mActiveSleepTimeUs;
4897 }
Eric Laurent81784c32012-11-19 14:55:58 -08004898 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004899 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004900 }
Phil Burkfdb3c072016-02-09 10:47:02 -08004901 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08004902 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004903 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004904 }
4905}
4906
Eric Laurentd1f69b02014-12-15 14:33:13 -08004907void AudioFlinger::DirectOutputThread::threadLoop_exit()
4908{
4909 {
4910 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08004911 for (size_t i = 0; i < mTracks.size(); i++) {
4912 if (mTracks[i]->isFlushPending()) {
4913 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004914 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004915 }
4916 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004917 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004918 flushHw_l();
4919 }
4920 }
4921 PlaybackThread::threadLoop_exit();
4922}
4923
4924// must be called with thread mutex locked
4925bool AudioFlinger::DirectOutputThread::shouldStandby_l()
4926{
4927 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07004928 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004929
vivek mehta9cd7ad12016-03-17 00:18:29 -07004930 if ((mType == DIRECT) && audio_is_linear_pcm(mFormat) && !usesHwAvSync()) {
4931 return !mStandby;
4932 }
4933
Eric Laurentd1f69b02014-12-15 14:33:13 -08004934 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4935 // after a timeout and we will enter standby then.
4936 if (mTracks.size() > 0) {
4937 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07004938 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
4939 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004940 }
4941
Eric Laurent5cff4032015-05-26 13:49:58 -07004942 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08004943}
4944
Eric Laurent81784c32012-11-19 14:55:58 -08004945// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004946int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Glenn Kastend848eb42016-03-08 13:42:11 -08004947 audio_format_t format __unused, audio_session_t sessionId __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004948{
4949 return 0;
4950}
4951
4952// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004953void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004954{
4955}
4956
Eric Laurent10351942014-05-08 18:49:52 -07004957// checkForNewParameter_l() must be called with ThreadBase::mLock held
4958bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
4959 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004960{
4961 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08004962 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004963
Eric Laurent10351942014-05-08 18:49:52 -07004964 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004965
Eric Laurent10351942014-05-08 18:49:52 -07004966 AudioParameter param = AudioParameter(keyValuePair);
4967 int value;
4968 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4969 // forward device change to effects that have requested to be
4970 // aware of attached audio device.
4971 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08004972 a2dpDeviceChanged =
4973 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07004974 mOutDevice = value;
4975 for (size_t i = 0; i < mEffectChains.size(); i++) {
4976 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07004977 }
4978 }
Eric Laurent81784c32012-11-19 14:55:58 -08004979 }
Eric Laurent10351942014-05-08 18:49:52 -07004980 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4981 // do not accept frame count changes if tracks are open as the track buffer
4982 // size depends on frame count and correct behavior would not be garantied
4983 // if frame count is changed after track creation
4984 if (!mTracks.isEmpty()) {
4985 status = INVALID_OPERATION;
4986 } else {
4987 reconfig = true;
4988 }
4989 }
4990 if (status == NO_ERROR) {
4991 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4992 keyValuePair.string());
4993 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004994 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004995 mStandby = true;
4996 mBytesWritten = 0;
4997 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4998 keyValuePair.string());
4999 }
5000 if (status == NO_ERROR && reconfig) {
5001 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07005002 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005003 }
5004 }
5005
Eric Laurent42537be2016-01-08 17:16:42 -08005006 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005007}
5008
5009uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
5010{
5011 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005012 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005013 time = PlaybackThread::activeSleepTimeUs();
5014 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005015 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005016 }
5017 return time;
5018}
5019
5020uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
5021{
5022 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005023 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005024 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
5025 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005026 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005027 }
5028 return time;
5029}
5030
5031uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
5032{
5033 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005034 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005035 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
5036 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005037 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005038 }
5039 return time;
5040}
5041
5042void AudioFlinger::DirectOutputThread::cacheParameters_l()
5043{
5044 PlaybackThread::cacheParameters_l();
5045
5046 // use shorter standby delay as on normal output to release
5047 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07005048 // no delay on outputs with HW A/V sync
5049 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005050 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08005051 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005052 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07005053 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005054 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07005055 }
Eric Laurent81784c32012-11-19 14:55:58 -08005056}
5057
Eric Laurente659ef42014-09-29 13:06:46 -07005058void AudioFlinger::DirectOutputThread::flushHw_l()
5059{
Phil Burk062e67a2015-02-11 13:40:50 -08005060 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08005061 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005062 mFlushPending = false;
Eric Laurente659ef42014-09-29 13:06:46 -07005063}
5064
Eric Laurent81784c32012-11-19 14:55:58 -08005065// ----------------------------------------------------------------------------
5066
Eric Laurentbfb1b832013-01-07 09:53:42 -08005067AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07005068 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005069 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07005070 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07005071 mWriteAckSequence(0),
5072 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005073{
5074}
5075
5076AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
5077{
5078}
5079
5080void AudioFlinger::AsyncCallbackThread::onFirstRef()
5081{
5082 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
5083}
5084
5085bool AudioFlinger::AsyncCallbackThread::threadLoop()
5086{
5087 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005088 uint32_t writeAckSequence;
5089 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005090
5091 {
5092 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005093 while (!((mWriteAckSequence & 1) ||
5094 (mDrainSequence & 1) ||
5095 exitPending())) {
5096 mWaitWorkCV.wait(mLock);
5097 }
5098
Eric Laurentbfb1b832013-01-07 09:53:42 -08005099 if (exitPending()) {
5100 break;
5101 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005102 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
5103 mWriteAckSequence, mDrainSequence);
5104 writeAckSequence = mWriteAckSequence;
5105 mWriteAckSequence &= ~1;
5106 drainSequence = mDrainSequence;
5107 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005108 }
5109 {
Eric Laurent4de95592013-09-26 15:28:21 -07005110 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
5111 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005112 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005113 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005114 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005115 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005116 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005117 }
5118 }
5119 }
5120 }
5121 return false;
5122}
5123
5124void AudioFlinger::AsyncCallbackThread::exit()
5125{
5126 ALOGV("AsyncCallbackThread::exit");
5127 Mutex::Autolock _l(mLock);
5128 requestExit();
5129 mWaitWorkCV.broadcast();
5130}
5131
Eric Laurent3b4529e2013-09-05 18:09:19 -07005132void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005133{
5134 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005135 // bit 0 is cleared
5136 mWriteAckSequence = sequence << 1;
5137}
5138
5139void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5140{
5141 Mutex::Autolock _l(mLock);
5142 // ignore unexpected callbacks
5143 if (mWriteAckSequence & 2) {
5144 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005145 mWaitWorkCV.signal();
5146 }
5147}
5148
Eric Laurent3b4529e2013-09-05 18:09:19 -07005149void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005150{
5151 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005152 // bit 0 is cleared
5153 mDrainSequence = sequence << 1;
5154}
5155
5156void AudioFlinger::AsyncCallbackThread::resetDraining()
5157{
5158 Mutex::Autolock _l(mLock);
5159 // ignore unexpected callbacks
5160 if (mDrainSequence & 2) {
5161 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005162 mWaitWorkCV.signal();
5163 }
5164}
5165
5166
5167// ----------------------------------------------------------------------------
5168AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent51716182016-02-29 18:00:56 -08005169 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady,
5170 uint32_t bitRate)
5171 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady, bitRate),
Eric Laurent64667972016-03-30 18:19:46 -07005172 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005173{
Eric Laurentfd477972013-10-25 18:10:40 -07005174 //FIXME: mStandby should be set to true by ThreadBase constructor
5175 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07005176 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005177}
5178
Eric Laurentbfb1b832013-01-07 09:53:42 -08005179void AudioFlinger::OffloadThread::threadLoop_exit()
5180{
5181 if (mFlushPending || mHwPaused) {
5182 // If a flush is pending or track was paused, just discard buffered data
5183 flushHw_l();
5184 } else {
5185 mMixerStatus = MIXER_DRAIN_ALL;
5186 threadLoop_drain();
5187 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005188 if (mUseAsyncWrite) {
5189 ALOG_ASSERT(mCallbackThread != 0);
5190 mCallbackThread->exit();
5191 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005192 PlaybackThread::threadLoop_exit();
5193}
5194
5195AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5196 Vector< sp<Track> > *tracksToRemove
5197)
5198{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005199 size_t count = mActiveTracks.size();
5200
5201 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005202 bool doHwPause = false;
5203 bool doHwResume = false;
5204
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005205 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07005206
Eric Laurentbfb1b832013-01-07 09:53:42 -08005207 // find out which tracks need to be processed
5208 for (size_t i = 0; i < count; i++) {
5209 sp<Track> t = mActiveTracks[i].promote();
5210 // The track died recently
5211 if (t == 0) {
5212 continue;
5213 }
5214 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005215#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08005216 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005217#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005218 // Only consider last track started for volume and mixer state control.
5219 // In theory an older track could underrun and restart after the new one starts
5220 // but as we only care about the transition phase between two tracks on a
5221 // direct output, it is not a problem to ignore the underrun case.
5222 sp<Track> l = mLatestActiveTrack.promote();
5223 bool last = l.get() == track;
5224
Haynes Mathew George7844f672014-01-15 12:32:55 -08005225 if (track->isInvalid()) {
5226 ALOGW("An invalidated track shouldn't be in active list");
5227 tracksToRemove->add(track);
5228 continue;
5229 }
5230
5231 if (track->mState == TrackBase::IDLE) {
5232 ALOGW("An idle track shouldn't be in active list");
5233 continue;
5234 }
5235
Eric Laurentbfb1b832013-01-07 09:53:42 -08005236 if (track->isPausing()) {
5237 track->setPaused();
5238 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005239 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005240 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005241 mHwPaused = true;
5242 }
5243 // If we were part way through writing the mixbuffer to
5244 // the HAL we must save this until we resume
5245 // BUG - this will be wrong if a different track is made active,
5246 // in that case we want to discard the pending data in the
5247 // mixbuffer and tell the client to present it again when the
5248 // track is resumed
5249 mPausedWriteLength = mCurrentWriteLength;
5250 mPausedBytesRemaining = mBytesRemaining;
5251 mBytesRemaining = 0; // stop writing
5252 }
5253 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005254 } else if (track->isFlushPending()) {
Eric Laurent51716182016-02-29 18:00:56 -08005255 track->mRetryCount = kMaxTrackRetriesOffload;
Haynes Mathew George7844f672014-01-15 12:32:55 -08005256 track->flushAck();
5257 if (last) {
5258 mFlushPending = true;
5259 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005260 } else if (track->isResumePending()){
5261 track->resumeAck();
5262 if (last) {
5263 if (mPausedBytesRemaining) {
5264 // Need to continue write that was interrupted
5265 mCurrentWriteLength = mPausedWriteLength;
5266 mBytesRemaining = mPausedBytesRemaining;
5267 mPausedBytesRemaining = 0;
5268 }
5269 if (mHwPaused) {
5270 doHwResume = true;
5271 mHwPaused = false;
5272 // threadLoop_mix() will handle the case that we need to
5273 // resume an interrupted write
5274 }
5275 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005276 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005277
5278 // Do not handle new data in this iteration even if track->framesReady()
5279 mixerStatus = MIXER_TRACKS_ENABLED;
5280 }
5281 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005282 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005283 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005284 if (track->mFillingUpStatus == Track::FS_FILLED) {
5285 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07005286 // make sure processVolume_l() will apply new volume even if 0
5287 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005288 }
5289
5290 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005291 sp<Track> previousTrack = mPreviousTrack.promote();
5292 if (previousTrack != 0) {
5293 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005294 // Flush any data still being written from last track
5295 mBytesRemaining = 0;
5296 if (mPausedBytesRemaining) {
5297 // Last track was paused so we also need to flush saved
5298 // mixbuffer state and invalidate track so that it will
5299 // re-submit that unwritten data when it is next resumed
5300 mPausedBytesRemaining = 0;
5301 // Invalidate is a bit drastic - would be more efficient
5302 // to have a flag to tell client that some of the
5303 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005304 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005305 }
5306 // flush data already sent to the DSP if changing audio session as audio
5307 // comes from a different source. Also invalidate previous track to force a
5308 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005309 if (previousTrack->sessionId() != track->sessionId()) {
5310 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005311 }
5312 }
5313 }
5314 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005315 // reset retry count
5316 track->mRetryCount = kMaxTrackRetriesOffload;
5317 mActiveTrack = t;
5318 mixerStatus = MIXER_TRACKS_READY;
5319 }
5320 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005321 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005322 if (track->isStopping_1()) {
5323 // Hardware buffer can hold a large amount of audio so we must
5324 // wait for all current track's data to drain before we say
5325 // that the track is stopped.
5326 if (mBytesRemaining == 0) {
5327 // Only start draining when all data in mixbuffer
5328 // has been written
5329 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5330 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005331 // do not drain if no data was ever sent to HAL (mStandby == true)
5332 if (last && !mStandby) {
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005333 // do not modify drain sequence if we are already draining. This happens
5334 // when resuming from pause after drain.
5335 if ((mDrainSequence & 1) == 0) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005336 mSleepTimeUs = 0;
5337 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005338 mixerStatus = MIXER_DRAIN_TRACK;
5339 mDrainSequence += 2;
5340 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005341 if (mHwPaused) {
5342 // It is possible to move from PAUSED to STOPPING_1 without
5343 // a resume so we must ensure hardware is running
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005344 doHwResume = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005345 mHwPaused = false;
5346 }
5347 }
5348 }
5349 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005350 // Drain has completed or we are in standby, signal presentation complete
5351 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005352 track->mState = TrackBase::STOPPED;
5353 size_t audioHALFrames =
5354 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005355 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005356 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005357 track->presentationComplete(framesWritten, audioHALFrames);
5358 track->reset();
5359 tracksToRemove->add(track);
5360 }
5361 } else {
5362 // No buffers for this track. Give it a few chances to
5363 // fill a buffer, then remove it from active list.
5364 if (--(track->mRetryCount) <= 0) {
5365 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5366 track->name());
5367 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005368 // indicate to client process that the track was disabled because of underrun;
5369 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005370 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005371 } else if (last){
5372 mixerStatus = MIXER_TRACKS_ENABLED;
5373 }
5374 }
5375 }
5376 // compute volume for this track
5377 processVolume_l(track, last);
5378 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005379
Eric Laurentea0fade2013-10-04 16:23:48 -07005380 // make sure the pause/flush/resume sequence is executed in the right order.
5381 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5382 // before flush and then resume HW. This can happen in case of pause/flush/resume
5383 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07005384 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07005385 mOutput->stream->pause(mOutput->stream);
5386 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005387 if (mFlushPending) {
5388 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005389 }
Eric Laurentfd477972013-10-25 18:10:40 -07005390 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07005391 mOutput->stream->resume(mOutput->stream);
5392 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005393
Eric Laurentbfb1b832013-01-07 09:53:42 -08005394 // remove all the tracks that need to be...
5395 removeTracks_l(*tracksToRemove);
5396
5397 return mixerStatus;
5398}
5399
Eric Laurentbfb1b832013-01-07 09:53:42 -08005400// must be called with thread mutex locked
5401bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5402{
Eric Laurent3b4529e2013-09-05 18:09:19 -07005403 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5404 mWriteAckSequence, mDrainSequence);
5405 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005406 return true;
5407 }
5408 return false;
5409}
5410
Eric Laurentbfb1b832013-01-07 09:53:42 -08005411bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5412{
5413 Mutex::Autolock _l(mLock);
5414 return waitingAsyncCallback_l();
5415}
5416
5417void AudioFlinger::OffloadThread::flushHw_l()
5418{
Eric Laurente659ef42014-09-29 13:06:46 -07005419 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005420 // Flush anything still waiting in the mixbuffer
5421 mCurrentWriteLength = 0;
5422 mBytesRemaining = 0;
5423 mPausedWriteLength = 0;
5424 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07005425 // reset bytes written count to reflect that DSP buffers are empty after flush.
5426 mBytesWritten = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08005427
Eric Laurentbfb1b832013-01-07 09:53:42 -08005428 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005429 // discard any pending drain or write ack by incrementing sequence
5430 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5431 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005432 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005433 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5434 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005435 }
5436}
5437
Eric Laurent51716182016-02-29 18:00:56 -08005438uint32_t AudioFlinger::OffloadThread::activeSleepTimeUs() const
5439{
5440 uint32_t time;
5441 if (audio_has_proportional_frames(mFormat)) {
5442 time = PlaybackThread::activeSleepTimeUs();
5443 } else {
5444 // sleep time is half the duration of an audio HAL buffer.
5445 // Note: This can be problematic in case of underrun with variable bit rate and
5446 // current rate is much less than initial rate.
5447 time = (uint32_t)max(kDirectMinSleepTimeUs, mBufferDurationUs / 2);
5448 }
5449 return time;
5450}
5451
Eric Laurentbfb1b832013-01-07 09:53:42 -08005452// ----------------------------------------------------------------------------
5453
Eric Laurent81784c32012-11-19 14:55:58 -08005454AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005455 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005456 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07005457 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08005458 mWaitTimeMs(UINT_MAX)
5459{
5460 addOutputTrack(mainThread);
5461}
5462
5463AudioFlinger::DuplicatingThread::~DuplicatingThread()
5464{
5465 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5466 mOutputTracks[i]->destroy();
5467 }
5468}
5469
5470void AudioFlinger::DuplicatingThread::threadLoop_mix()
5471{
5472 // mix buffers...
5473 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08005474 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08005475 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005476 if (mMixerBufferValid) {
5477 memset(mMixerBuffer, 0, mMixerBufferSize);
5478 } else {
5479 memset(mSinkBuffer, 0, mSinkBufferSize);
5480 }
Eric Laurent81784c32012-11-19 14:55:58 -08005481 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005482 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005483 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005484 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005485 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005486}
5487
5488void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5489{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005490 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005491 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005492 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005493 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005494 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005495 }
5496 } else if (mBytesWritten != 0) {
5497 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5498 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005499 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005500 } else {
5501 // flush remaining overflow buffers in output tracks
5502 writeFrames = 0;
5503 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005504 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005505 }
5506}
5507
Eric Laurentbfb1b832013-01-07 09:53:42 -08005508ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005509{
5510 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005511 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005512 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005513 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005514 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005515}
5516
5517void AudioFlinger::DuplicatingThread::threadLoop_standby()
5518{
5519 // DuplicatingThread implements standby by stopping all tracks
5520 for (size_t i = 0; i < outputTracks.size(); i++) {
5521 outputTracks[i]->stop();
5522 }
5523}
5524
5525void AudioFlinger::DuplicatingThread::saveOutputTracks()
5526{
5527 outputTracks = mOutputTracks;
5528}
5529
5530void AudioFlinger::DuplicatingThread::clearOutputTracks()
5531{
5532 outputTracks.clear();
5533}
5534
5535void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5536{
5537 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005538 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5539 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5540 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5541 const size_t frameCount =
5542 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5543 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5544 // from different OutputTracks and their associated MixerThreads (e.g. one may
5545 // nearly empty and the other may be dropping data).
5546
5547 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005548 this,
5549 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005550 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005551 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005552 frameCount,
5553 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08005554 if (outputTrack->cblk() != NULL) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005555 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
Eric Laurent81784c32012-11-19 14:55:58 -08005556 mOutputTracks.add(outputTrack);
Andy Hungc25b84a2015-01-14 19:04:10 -08005557 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005558 updateWaitTime_l();
5559 }
5560}
5561
5562void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5563{
5564 Mutex::Autolock _l(mLock);
5565 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5566 if (mOutputTracks[i]->thread() == thread) {
5567 mOutputTracks[i]->destroy();
5568 mOutputTracks.removeAt(i);
5569 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07005570 if (thread->getOutput() == mOutput) {
5571 mOutput = NULL;
5572 }
Eric Laurent81784c32012-11-19 14:55:58 -08005573 return;
5574 }
5575 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07005576 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005577}
5578
5579// caller must hold mLock
5580void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5581{
5582 mWaitTimeMs = UINT_MAX;
5583 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5584 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5585 if (strong != 0) {
5586 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5587 if (waitTimeMs < mWaitTimeMs) {
5588 mWaitTimeMs = waitTimeMs;
5589 }
5590 }
5591 }
5592}
5593
5594
5595bool AudioFlinger::DuplicatingThread::outputsReady(
5596 const SortedVector< sp<OutputTrack> > &outputTracks)
5597{
5598 for (size_t i = 0; i < outputTracks.size(); i++) {
5599 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5600 if (thread == 0) {
5601 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5602 outputTracks[i].get());
5603 return false;
5604 }
5605 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5606 // see note at standby() declaration
5607 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5608 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5609 thread.get());
5610 return false;
5611 }
5612 }
5613 return true;
5614}
5615
5616uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5617{
5618 return (mWaitTimeMs * 1000) / 2;
5619}
5620
5621void AudioFlinger::DuplicatingThread::cacheParameters_l()
5622{
5623 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5624 updateWaitTime_l();
5625
5626 MixerThread::cacheParameters_l();
5627}
5628
5629// ----------------------------------------------------------------------------
5630// Record
5631// ----------------------------------------------------------------------------
5632
5633AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5634 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005635 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005636 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07005637 audio_devices_t inDevice,
5638 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08005639#ifdef TEE_SINK
5640 , const sp<NBAIO_Sink>& teeSink
5641#endif
5642 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07005643 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005644 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005645 // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005646 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005647#ifdef TEE_SINK
5648 , mTeeSink(teeSink)
5649#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005650 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5651 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005652 // mFastCapture below
5653 , mFastCaptureFutex(0)
5654 // mInputSource
5655 // mPipeSink
5656 // mPipeSource
5657 , mPipeFramesP2(0)
5658 // mPipeMemory
5659 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005660 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005661{
Glenn Kastend7dca052015-03-05 16:05:54 -08005662 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5663 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08005664
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005665 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005666
5667 // create an NBAIO source for the HAL input stream, and negotiate
5668 mInputSource = new AudioStreamInSource(input->stream);
5669 size_t numCounterOffers = 0;
5670 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005671#if !LOG_NDEBUG
5672 ssize_t index =
5673#else
5674 (void)
5675#endif
5676 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005677 ALOG_ASSERT(index == 0);
5678
5679 // initialize fast capture depending on configuration
5680 bool initFastCapture;
5681 switch (kUseFastCapture) {
5682 case FastCapture_Never:
5683 initFastCapture = false;
5684 break;
5685 case FastCapture_Always:
5686 initFastCapture = true;
5687 break;
5688 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07005689 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005690 break;
5691 // case FastCapture_Dynamic:
5692 }
5693
5694 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07005695 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005696 NBAIO_Format format = mInputSource->format();
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005697 size_t pipeFramesP2 = roundup(mSampleRate / 25); // double-buffering of 20 ms each
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005698 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5699 void *pipeBuffer;
5700 const sp<MemoryDealer> roHeap(readOnlyHeap());
5701 sp<IMemory> pipeMemory;
5702 if ((roHeap == 0) ||
5703 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5704 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5705 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5706 goto failed;
5707 }
5708 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5709 memset(pipeBuffer, 0, pipeSize);
5710 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5711 const NBAIO_Format offers[1] = {format};
5712 size_t numCounterOffers = 0;
5713 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5714 ALOG_ASSERT(index == 0);
5715 mPipeSink = pipe;
5716 PipeReader *pipeReader = new PipeReader(*pipe);
5717 numCounterOffers = 0;
5718 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5719 ALOG_ASSERT(index == 0);
5720 mPipeSource = pipeReader;
5721 mPipeFramesP2 = pipeFramesP2;
5722 mPipeMemory = pipeMemory;
5723
5724 // create fast capture
5725 mFastCapture = new FastCapture();
5726 FastCaptureStateQueue *sq = mFastCapture->sq();
5727#ifdef STATE_QUEUE_DUMP
5728 // FIXME
5729#endif
5730 FastCaptureState *state = sq->begin();
5731 state->mCblk = NULL;
5732 state->mInputSource = mInputSource.get();
5733 state->mInputSourceGen++;
5734 state->mPipeSink = pipe;
5735 state->mPipeSinkGen++;
5736 state->mFrameCount = mFrameCount;
5737 state->mCommand = FastCaptureState::COLD_IDLE;
5738 // already done in constructor initialization list
5739 //mFastCaptureFutex = 0;
5740 state->mColdFutexAddr = &mFastCaptureFutex;
5741 state->mColdGen++;
5742 state->mDumpState = &mFastCaptureDumpState;
5743#ifdef TEE_SINK
5744 // FIXME
5745#endif
5746 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
5747 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
5748 sq->end();
5749 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5750
5751 // start the fast capture
5752 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
5753 pid_t tid = mFastCapture->getTid();
Glenn Kasten8379b722016-03-18 14:54:17 -07005754 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005755#ifdef AUDIO_WATCHDOG
5756 // FIXME
5757#endif
5758
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005759 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005760 }
5761failed: ;
5762
5763 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08005764}
5765
Eric Laurent81784c32012-11-19 14:55:58 -08005766AudioFlinger::RecordThread::~RecordThread()
5767{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005768 if (mFastCapture != 0) {
5769 FastCaptureStateQueue *sq = mFastCapture->sq();
5770 FastCaptureState *state = sq->begin();
5771 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5772 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5773 if (old == -1) {
5774 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5775 }
5776 }
5777 state->mCommand = FastCaptureState::EXIT;
5778 sq->end();
5779 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5780 mFastCapture->join();
5781 mFastCapture.clear();
5782 }
5783 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07005784 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07005785 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08005786}
5787
5788void AudioFlinger::RecordThread::onFirstRef()
5789{
Glenn Kastend7dca052015-03-05 16:05:54 -08005790 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08005791}
5792
Eric Laurent81784c32012-11-19 14:55:58 -08005793bool AudioFlinger::RecordThread::threadLoop()
5794{
Eric Laurent81784c32012-11-19 14:55:58 -08005795 nsecs_t lastWarning = 0;
5796
5797 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08005798
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005799reacquire_wakelock:
5800 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08005801 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005802 {
5803 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005804 size_t size = mActiveTracks.size();
5805 activeTracksGen = mActiveTracksGen;
5806 if (size > 0) {
5807 // FIXME an arbitrary choice
5808 activeTrack = mActiveTracks[0];
5809 acquireWakeLock_l(activeTrack->uid());
5810 if (size > 1) {
5811 SortedVector<int> tmp;
5812 for (size_t i = 0; i < size; i++) {
5813 tmp.add(mActiveTracks[i]->uid());
5814 }
5815 updateWakeLockUids_l(tmp);
5816 }
5817 } else {
5818 acquireWakeLock_l(-1);
5819 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005820 }
5821
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005822 // used to request a deferred sleep, to be executed later while mutex is unlocked
5823 uint32_t sleepUs = 0;
5824
5825 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005826 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005827 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07005828
Glenn Kasten5edadd42013-08-14 16:30:49 -07005829 // sleep with mutex unlocked
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005830 if (sleepUs > 0) {
Glenn Kastene7754022014-10-31 12:11:26 -07005831 ATRACE_BEGIN("sleep");
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005832 usleep(sleepUs);
Glenn Kastene7754022014-10-31 12:11:26 -07005833 ATRACE_END();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005834 sleepUs = 0;
Glenn Kasten5edadd42013-08-14 16:30:49 -07005835 }
5836
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005837 // activeTracks accumulates a copy of a subset of mActiveTracks
5838 Vector< sp<RecordTrack> > activeTracks;
5839
Glenn Kasten735f45f2014-08-18 15:51:59 -07005840 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005841 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07005842
Glenn Kasten735f45f2014-08-18 15:51:59 -07005843 // reference to a fast track which is about to be removed
5844 sp<RecordTrack> fastTrackToRemove;
5845
Eric Laurent81784c32012-11-19 14:55:58 -08005846 { // scope for mLock
5847 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08005848
Eric Laurent021cf962014-05-13 10:18:14 -07005849 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005850
Eric Laurent000a4192014-01-29 15:17:32 -08005851 // check exitPending here because checkForNewParameters_l() and
5852 // checkForNewParameters_l() can temporarily release mLock
5853 if (exitPending()) {
5854 break;
5855 }
5856
Glenn Kasten2b806402013-11-20 16:37:38 -08005857 // if no active track(s), then standby and release wakelock
5858 size_t size = mActiveTracks.size();
5859 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07005860 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005861 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08005862 releaseWakeLock_l();
5863 ALOGV("RecordThread: loop stopping");
5864 // go to sleep
5865 mWaitWorkCV.wait(mLock);
5866 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005867 goto reacquire_wakelock;
5868 }
5869
Glenn Kasten2b806402013-11-20 16:37:38 -08005870 if (mActiveTracksGen != activeTracksGen) {
5871 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005872 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08005873 for (size_t i = 0; i < size; i++) {
5874 tmp.add(mActiveTracks[i]->uid());
5875 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005876 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08005877 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005878
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005879 bool doBroadcast = false;
5880 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07005881
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005882 activeTrack = mActiveTracks[i];
5883 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07005884 if (activeTrack->isFastTrack()) {
5885 ALOG_ASSERT(fastTrackToRemove == 0);
5886 fastTrackToRemove = activeTrack;
5887 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005888 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08005889 mActiveTracks.remove(activeTrack);
5890 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005891 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07005892 continue;
5893 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005894
5895 TrackBase::track_state activeTrackState = activeTrack->mState;
5896 switch (activeTrackState) {
5897
5898 case TrackBase::PAUSING:
5899 mActiveTracks.remove(activeTrack);
5900 mActiveTracksGen++;
5901 doBroadcast = true;
5902 size--;
5903 continue;
5904
5905 case TrackBase::STARTING_1:
5906 sleepUs = 10000;
5907 i++;
5908 continue;
5909
5910 case TrackBase::STARTING_2:
5911 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005912 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07005913 activeTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005914 break;
5915
5916 case TrackBase::ACTIVE:
5917 break;
5918
5919 case TrackBase::IDLE:
5920 i++;
5921 continue;
5922
5923 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08005924 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07005925 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005926
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005927 activeTracks.add(activeTrack);
5928 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07005929
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005930 if (activeTrack->isFastTrack()) {
5931 ALOG_ASSERT(!mFastTrackAvail);
5932 ALOG_ASSERT(fastTrack == 0);
5933 fastTrack = activeTrack;
5934 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005935 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005936 if (doBroadcast) {
5937 mStartStopCond.broadcast();
5938 }
5939
5940 // sleep if there are no active tracks to process
5941 if (activeTracks.size() == 0) {
5942 if (sleepUs == 0) {
5943 sleepUs = kRecordThreadSleepUs;
5944 }
5945 continue;
5946 }
5947 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07005948
Eric Laurent81784c32012-11-19 14:55:58 -08005949 lockEffectChains_l(effectChains);
5950 }
5951
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005952 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07005953
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005954 size_t size = effectChains.size();
5955 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005956 // thread mutex is not locked, but effect chain is locked
5957 effectChains[i]->process_l();
5958 }
5959
Glenn Kasten735f45f2014-08-18 15:51:59 -07005960 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005961 if (mFastCapture != 0) {
5962 FastCaptureStateQueue *sq = mFastCapture->sq();
5963 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07005964 bool didModify = false;
5965 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005966 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
5967 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
5968 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5969 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5970 if (old == -1) {
5971 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5972 }
5973 }
5974 state->mCommand = FastCaptureState::READ_WRITE;
5975#if 0 // FIXME
5976 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08005977 FastThreadDumpState::kSamplingNforLowRamDevice :
5978 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005979#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07005980 didModify = true;
5981 }
5982 audio_track_cblk_t *cblkOld = state->mCblk;
5983 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
5984 if (cblkNew != cblkOld) {
5985 state->mCblk = cblkNew;
5986 // block until acked if removing a fast track
5987 if (cblkOld != NULL) {
5988 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
5989 }
5990 didModify = true;
5991 }
5992 sq->end(didModify);
5993 if (didModify) {
5994 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005995#if 0
5996 if (kUseFastCapture == FastCapture_Dynamic) {
5997 mNormalSource = mPipeSource;
5998 }
5999#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006000 }
6001 }
6002
Glenn Kasten735f45f2014-08-18 15:51:59 -07006003 // now run the fast track destructor with thread mutex unlocked
6004 fastTrackToRemove.clear();
6005
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006006 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
6007 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
6008 // slow, then this RecordThread will overrun by not calling HAL read often enough.
6009 // If destination is non-contiguous, first read past the nominal end of buffer, then
6010 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006011
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006012 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006013 ssize_t framesRead;
6014
6015 // If an NBAIO source is present, use it to read the normal capture's data
6016 if (mPipeSource != 0) {
6017 size_t framesToRead = mBufferSize / mFrameSize;
Andy Hung57446612015-04-19 23:56:46 -07006018 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
Glenn Kastend79072e2016-01-06 08:41:20 -08006019 framesToRead);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006020 if (framesRead == 0) {
6021 // since pipe is non-blocking, simulate blocking input
6022 sleepUs = (framesToRead * 1000000LL) / mSampleRate;
6023 }
6024 // otherwise use the HAL / AudioStreamIn directly
6025 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07006026 ATRACE_BEGIN("read");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006027 ssize_t bytesRead = mInput->stream->read(mInput->stream,
Andy Hung57446612015-04-19 23:56:46 -07006028 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize);
Glenn Kastenec6a7032016-03-14 07:40:23 -07006029 ATRACE_END();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006030 if (bytesRead < 0) {
6031 framesRead = bytesRead;
6032 } else {
6033 framesRead = bytesRead / mFrameSize;
6034 }
6035 }
6036
Andy Hung3f0c9022016-01-15 17:49:46 -08006037 // Update server timestamp with server stats
6038 // systemTime() is optional if the hardware supports timestamps.
6039 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
6040 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6041
6042 // Update server timestamp with kernel stats
6043 if (mInput->stream->get_capture_position != nullptr) {
6044 int64_t position, time;
6045 int ret = mInput->stream->get_capture_position(mInput->stream, &position, &time);
6046 if (ret == NO_ERROR) {
6047 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
6048 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
6049 // Note: In general record buffers should tend to be empty in
6050 // a properly running pipeline.
6051 //
6052 // Also, it is not advantageous to call get_presentation_position during the read
6053 // as the read obtains a lock, preventing the timestamp call from executing.
6054 }
6055 }
6056 // Use this to track timestamp information
6057 // ALOGD("%s", mTimestamp.toString().c_str());
6058
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006059 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006060 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006061 // Force input into standby so that it tries to recover at next read attempt
6062 inputStandBy();
6063 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006064 }
6065 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006066 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006067 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006068 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006069
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006070 if (mTeeSink != 0) {
Andy Hung57446612015-04-19 23:56:46 -07006071 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006072 }
6073 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006074 {
6075 size_t part1 = mRsmpInFramesP2 - rear;
6076 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07006077 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006078 (framesRead - part1) * mFrameSize);
6079 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006080 }
6081 rear = mRsmpInRear += framesRead;
6082
6083 size = activeTracks.size();
6084 // loop over each active track
6085 for (size_t i = 0; i < size; i++) {
6086 activeTrack = activeTracks[i];
6087
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006088 // skip fast tracks, as those are handled directly by FastCapture
6089 if (activeTrack->isFastTrack()) {
6090 continue;
6091 }
6092
Andy Hung73c02e42015-03-29 01:13:58 -07006093 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07006094 // TODO: Update the activeTrack buffer converter in case of reconfigure.
6095
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006096 enum {
6097 OVERRUN_UNKNOWN,
6098 OVERRUN_TRUE,
6099 OVERRUN_FALSE
6100 } overrun = OVERRUN_UNKNOWN;
6101
6102 // loop over getNextBuffer to handle circular sink
6103 for (;;) {
6104
6105 activeTrack->mSink.frameCount = ~0;
6106 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
6107 size_t framesOut = activeTrack->mSink.frameCount;
6108 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
6109
Andy Hung73c02e42015-03-29 01:13:58 -07006110 // check available frames and handle overrun conditions
6111 // if the record track isn't draining fast enough.
6112 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006113 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07006114 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
6115 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006116 overrun = OVERRUN_TRUE;
6117 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006118 if (framesOut == 0 || framesIn == 0) {
6119 break;
6120 }
6121
Andy Hung6770c6f2015-04-07 13:43:36 -07006122 // Don't allow framesOut to be larger than what is possible with resampling
6123 // from framesIn.
6124 // This isn't strictly necessary but helps limit buffer resizing in
6125 // RecordBufferConverter. TODO: remove when no longer needed.
6126 framesOut = min(framesOut,
6127 destinationFramesPossible(
6128 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07006129 // process frames from the RecordThread buffer provider to the RecordTrack buffer
6130 framesOut = activeTrack->mRecordBufferConverter->convert(
6131 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006132
6133 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
6134 overrun = OVERRUN_FALSE;
6135 }
6136
6137 if (activeTrack->mFramesToDrop == 0) {
6138 if (framesOut > 0) {
6139 activeTrack->mSink.frameCount = framesOut;
6140 activeTrack->releaseBuffer(&activeTrack->mSink);
6141 }
6142 } else {
6143 // FIXME could do a partial drop of framesOut
6144 if (activeTrack->mFramesToDrop > 0) {
6145 activeTrack->mFramesToDrop -= framesOut;
6146 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006147 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006148 }
6149 } else {
6150 activeTrack->mFramesToDrop += framesOut;
6151 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
6152 activeTrack->mSyncStartEvent->isCancelled()) {
6153 ALOGW("Synced record %s, session %d, trigger session %d",
6154 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
6155 activeTrack->sessionId(),
6156 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08006157 activeTrack->mSyncStartEvent->triggerSession() :
6158 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006159 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006160 }
6161 }
6162 }
6163
6164 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006165 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006166 }
6167 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006168
6169 switch (overrun) {
6170 case OVERRUN_TRUE:
6171 // client isn't retrieving buffers fast enough
6172 if (!activeTrack->setOverflow()) {
6173 nsecs_t now = systemTime();
6174 // FIXME should lastWarning per track?
6175 if ((now - lastWarning) > kWarningThrottleNs) {
6176 ALOGW("RecordThread: buffer overflow");
6177 lastWarning = now;
6178 }
6179 }
6180 break;
6181 case OVERRUN_FALSE:
6182 activeTrack->clearOverflow();
6183 break;
6184 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006185 break;
6186 }
6187
Andy Hung3f0c9022016-01-15 17:49:46 -08006188 // update frame information and push timestamp out
6189 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08006190 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08006191 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
6192 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006193 }
6194
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006195unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08006196 // enable changes in effect chain
6197 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006198 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08006199 }
6200
Glenn Kasten93e471f2013-08-19 08:40:07 -07006201 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08006202
6203 {
6204 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07006205 for (size_t i = 0; i < mTracks.size(); i++) {
6206 sp<RecordTrack> track = mTracks[i];
6207 track->invalidate();
6208 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006209 mActiveTracks.clear();
6210 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08006211 mStartStopCond.broadcast();
6212 }
6213
6214 releaseWakeLock();
6215
6216 ALOGV("RecordThread %p exiting", this);
6217 return false;
6218}
6219
Glenn Kasten93e471f2013-08-19 08:40:07 -07006220void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08006221{
6222 if (!mStandby) {
6223 inputStandBy();
6224 mStandby = true;
6225 }
6226}
6227
6228void AudioFlinger::RecordThread::inputStandBy()
6229{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006230 // Idle the fast capture if it's currently running
6231 if (mFastCapture != 0) {
6232 FastCaptureStateQueue *sq = mFastCapture->sq();
6233 FastCaptureState *state = sq->begin();
6234 if (!(state->mCommand & FastCaptureState::IDLE)) {
6235 state->mCommand = FastCaptureState::COLD_IDLE;
6236 state->mColdFutexAddr = &mFastCaptureFutex;
6237 state->mColdGen++;
6238 mFastCaptureFutex = 0;
6239 sq->end();
6240 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
6241 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
6242#if 0
6243 if (kUseFastCapture == FastCapture_Dynamic) {
6244 // FIXME
6245 }
6246#endif
6247#ifdef AUDIO_WATCHDOG
6248 // FIXME
6249#endif
6250 } else {
6251 sq->end(false /*didModify*/);
6252 }
6253 }
Eric Laurent81784c32012-11-19 14:55:58 -08006254 mInput->stream->common.standby(&mInput->stream->common);
6255}
6256
Glenn Kasten05997e22014-03-13 15:08:33 -07006257// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07006258sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08006259 const sp<AudioFlinger::Client>& client,
6260 uint32_t sampleRate,
6261 audio_format_t format,
6262 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08006263 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08006264 audio_session_t sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07006265 size_t *notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006266 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07006267 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08006268 pid_t tid,
6269 status_t *status)
6270{
Glenn Kasten74935e42013-12-19 08:56:45 -08006271 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08006272 sp<RecordTrack> track;
6273 status_t lStatus;
6274
Glenn Kasten90e58b12013-07-31 16:16:02 -07006275 // client expresses a preference for FAST, but we get the final say
6276 if (*flags & IAudioFlinger::TRACK_FAST) {
6277 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07006278 // we formerly checked for a callback handler (non-0 tid),
6279 // but that is no longer required for TRANSFER_OBTAIN mode
6280 //
Glenn Kasten74105912014-07-03 12:28:53 -07006281 // frame count is not specified, or is exactly the pipe depth
6282 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006283 // PCM data
6284 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006285 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006286 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006287 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006288 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006289 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07006290 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006291 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006292 hasFastCapture() &&
6293 // there are sufficient fast track slots available
6294 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07006295 ) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006296 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
Glenn Kasten90e58b12013-07-31 16:16:02 -07006297 frameCount, mFrameCount);
6298 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006299 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
Glenn Kasten74105912014-07-03 12:28:53 -07006300 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006301 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07006302 frameCount, mFrameCount, mPipeFramesP2,
6303 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
6304 hasFastCapture(), tid, mFastTrackAvail);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006305 *flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kasten74105912014-07-03 12:28:53 -07006306 }
6307 }
6308
6309 // compute track buffer size in frames, and suggest the notification frame count
6310 if (*flags & IAudioFlinger::TRACK_FAST) {
6311 // fast track: frame count is exactly the pipe depth
6312 frameCount = mPipeFramesP2;
6313 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
6314 *notificationFrames = mFrameCount;
6315 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006316 // not fast track: max notification period is resampled equivalent of one HAL buffer time
6317 // or 20 ms if there is a fast capture
6318 // TODO This could be a roundupRatio inline, and const
6319 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
6320 * sampleRate + mSampleRate - 1) / mSampleRate;
6321 // minimum number of notification periods is at least kMinNotifications,
6322 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
6323 static const size_t kMinNotifications = 3;
6324 static const uint32_t kMinMs = 30;
6325 // TODO This could be a roundupRatio inline
6326 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
6327 // TODO This could be a roundupRatio inline
6328 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
6329 maxNotificationFrames;
6330 const size_t minFrameCount = maxNotificationFrames *
6331 max(kMinNotifications, minNotificationsByMs);
6332 frameCount = max(frameCount, minFrameCount);
6333 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
6334 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07006335 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07006336 }
Glenn Kasten74935e42013-12-19 08:56:45 -08006337 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07006338
Glenn Kasten15e57982013-09-24 11:52:37 -07006339 lStatus = initCheck();
6340 if (lStatus != NO_ERROR) {
6341 ALOGE("createRecordTrack_l() audio driver not initialized");
6342 goto Exit;
6343 }
Eric Laurent81784c32012-11-19 14:55:58 -08006344
6345 { // scope for mLock
6346 Mutex::Autolock _l(mLock);
6347
6348 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07006349 format, channelMask, frameCount, NULL, sessionId, uid,
6350 *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08006351
Glenn Kasten03003332013-08-06 15:40:54 -07006352 lStatus = track->initCheck();
6353 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07006354 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08006355 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08006356 goto Exit;
6357 }
6358 mTracks.add(track);
6359
6360 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6361 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6362 mAudioFlinger->btNrecIsOff();
6363 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6364 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006365
6366 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
6367 pid_t callingPid = IPCThreadState::self()->getCallingPid();
6368 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
6369 // so ask activity manager to do this on our behalf
6370 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
6371 }
Eric Laurent81784c32012-11-19 14:55:58 -08006372 }
Glenn Kasten05997e22014-03-13 15:08:33 -07006373
Eric Laurent81784c32012-11-19 14:55:58 -08006374 lStatus = NO_ERROR;
6375
6376Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07006377 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08006378 return track;
6379}
6380
6381status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6382 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08006383 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08006384{
6385 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6386 sp<ThreadBase> strongMe = this;
6387 status_t status = NO_ERROR;
6388
6389 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006390 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006391 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006392 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08006393 triggerSession,
6394 recordTrack->sessionId(),
6395 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006396 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08006397 // Sync event can be cancelled by the trigger session if the track is not in a
6398 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006399 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006400 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006401 } else {
6402 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006403 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006404 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08006405 }
6406 }
6407
6408 {
Glenn Kasten47c20702013-08-13 15:37:35 -07006409 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08006410 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006411 if (mActiveTracks.indexOf(recordTrack) >= 0) {
6412 if (recordTrack->mState == TrackBase::PAUSING) {
6413 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006414 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006415 } else {
6416 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08006417 }
6418 return status;
6419 }
6420
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006421 // TODO consider other ways of handling this, such as changing the state to :STARTING and
6422 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6423 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006424 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08006425 mActiveTracks.add(recordTrack);
6426 mActiveTracksGen++;
Eric Laurent83b88082014-06-20 18:31:16 -07006427 status_t status = NO_ERROR;
6428 if (recordTrack->isExternalTrack()) {
6429 mLock.unlock();
Glenn Kastend848eb42016-03-08 13:42:11 -08006430 status = AudioSystem::startInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006431 mLock.lock();
6432 // FIXME should verify that recordTrack is still in mActiveTracks
6433 if (status != NO_ERROR) {
6434 mActiveTracks.remove(recordTrack);
6435 mActiveTracksGen++;
6436 recordTrack->clearSyncStartEvent();
6437 ALOGV("RecordThread::start error %d", status);
6438 return status;
6439 }
Eric Laurent81784c32012-11-19 14:55:58 -08006440 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006441 // Catch up with current buffer indices if thread is already running.
6442 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
6443 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6444 // see previously buffered data before it called start(), but with greater risk of overrun.
6445
Andy Hung73c02e42015-03-29 01:13:58 -07006446 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07006447 // clear any converter state as new data will be discontinuous
6448 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006449 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08006450 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08006451 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08006452 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006453 ALOGV("Record failed to start");
6454 status = BAD_VALUE;
6455 goto startError;
6456 }
Eric Laurent81784c32012-11-19 14:55:58 -08006457 return status;
6458 }
Glenn Kasten7c027242012-12-26 14:43:16 -08006459
Eric Laurent81784c32012-11-19 14:55:58 -08006460startError:
Eric Laurent83b88082014-06-20 18:31:16 -07006461 if (recordTrack->isExternalTrack()) {
Glenn Kastend848eb42016-03-08 13:42:11 -08006462 AudioSystem::stopInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006463 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006464 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006465 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08006466 return status;
6467}
6468
Eric Laurent81784c32012-11-19 14:55:58 -08006469void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6470{
6471 sp<SyncEvent> strongEvent = event.promote();
6472
6473 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08006474 sp<RefBase> ptr = strongEvent->cookie().promote();
6475 if (ptr != 0) {
6476 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6477 recordTrack->handleSyncStartEvent(strongEvent);
6478 }
Eric Laurent81784c32012-11-19 14:55:58 -08006479 }
6480}
6481
Glenn Kastena8356f62013-07-25 14:37:52 -07006482bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08006483 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07006484 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006485 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08006486 return false;
6487 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006488 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006489 recordTrack->mState = TrackBase::PAUSING;
6490 // do not wait for mStartStopCond if exiting
6491 if (exitPending()) {
6492 return true;
6493 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006494 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08006495 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006496 // if we have been restarted, recordTrack is in mActiveTracks here
6497 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006498 ALOGV("Record stopped OK");
6499 return true;
6500 }
6501 return false;
6502}
6503
Glenn Kasten0f11b512014-01-31 16:18:54 -08006504bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08006505{
6506 return false;
6507}
6508
Glenn Kasten0f11b512014-01-31 16:18:54 -08006509status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006510{
6511#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6512 if (!isValidSyncEvent(event)) {
6513 return BAD_VALUE;
6514 }
6515
Glenn Kastend848eb42016-03-08 13:42:11 -08006516 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08006517 status_t ret = NAME_NOT_FOUND;
6518
6519 Mutex::Autolock _l(mLock);
6520
6521 for (size_t i = 0; i < mTracks.size(); i++) {
6522 sp<RecordTrack> track = mTracks[i];
6523 if (eventSession == track->sessionId()) {
6524 (void) track->setSyncEvent(event);
6525 ret = NO_ERROR;
6526 }
6527 }
6528 return ret;
6529#else
6530 return BAD_VALUE;
6531#endif
6532}
6533
6534// destroyTrack_l() must be called with ThreadBase::mLock held
6535void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6536{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006537 track->terminate();
6538 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006539 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006540 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006541 removeTrack_l(track);
6542 }
6543}
6544
6545void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6546{
6547 mTracks.remove(track);
6548 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006549 if (track->isFastTrack()) {
6550 ALOG_ASSERT(!mFastTrackAvail);
6551 mFastTrackAvail = true;
6552 }
Eric Laurent81784c32012-11-19 14:55:58 -08006553}
6554
6555void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6556{
6557 dumpInternals(fd, args);
6558 dumpTracks(fd, args);
6559 dumpEffectChains(fd, args);
6560}
6561
6562void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6563{
Elliott Hughes87cebad2014-05-22 10:14:43 -07006564 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08006565
Glenn Kasten44182c22015-03-05 17:12:23 -08006566 dumpBase(fd, args);
6567
6568 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006569 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006570 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006571 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006572 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08006573
Glenn Kasten2f90c512015-12-02 11:40:09 -08006574 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
6575 // while we are dumping it. It may be inconsistent, but it won't mutate!
6576 // This is a large object so we place it on the heap.
6577 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
6578 const FastCaptureDumpState *copy = new FastCaptureDumpState(mFastCaptureDumpState);
6579 copy->dump(fd);
6580 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08006581}
6582
Glenn Kasten0f11b512014-01-31 16:18:54 -08006583void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006584{
6585 const size_t SIZE = 256;
6586 char buffer[SIZE];
6587 String8 result;
6588
Marco Nelissenb2208842014-02-07 14:00:50 -08006589 size_t numtracks = mTracks.size();
6590 size_t numactive = mActiveTracks.size();
6591 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006592 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006593 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006594 dprintf(fd, " of which %zu are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006595 RecordTrack::appendDumpHeader(result);
6596 for (size_t i = 0; i < numtracks ; ++i) {
6597 sp<RecordTrack> track = mTracks[i];
6598 if (track != 0) {
6599 bool active = mActiveTracks.indexOf(track) >= 0;
6600 if (active) {
6601 numactiveseen++;
6602 }
6603 track->dump(buffer, SIZE, active);
6604 result.append(buffer);
6605 }
Eric Laurent81784c32012-11-19 14:55:58 -08006606 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006607 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006608 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006609 }
6610
Marco Nelissenb2208842014-02-07 14:00:50 -08006611 if (numactiveseen != numactive) {
6612 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6613 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006614 result.append(buffer);
6615 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006616 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006617 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006618 if (mTracks.indexOf(track) < 0) {
6619 track->dump(buffer, SIZE, true);
6620 result.append(buffer);
6621 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006622 }
Eric Laurent81784c32012-11-19 14:55:58 -08006623
6624 }
6625 write(fd, result.string(), result.size());
6626}
6627
Andy Hung73c02e42015-03-29 01:13:58 -07006628
6629void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
6630{
6631 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6632 RecordThread *recordThread = (RecordThread *) threadBase.get();
6633 mRsmpInFront = recordThread->mRsmpInRear;
6634 mRsmpInUnrel = 0;
6635}
6636
6637void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
6638 size_t *framesAvailable, bool *hasOverrun)
6639{
6640 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6641 RecordThread *recordThread = (RecordThread *) threadBase.get();
6642 const int32_t rear = recordThread->mRsmpInRear;
6643 const int32_t front = mRsmpInFront;
6644 const ssize_t filled = rear - front;
6645
6646 size_t framesIn;
6647 bool overrun = false;
6648 if (filled < 0) {
6649 // should not happen, but treat like a massive overrun and re-sync
6650 framesIn = 0;
6651 mRsmpInFront = rear;
6652 overrun = true;
6653 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
6654 framesIn = (size_t) filled;
6655 } else {
6656 // client is not keeping up with server, but give it latest data
6657 framesIn = recordThread->mRsmpInFrames;
6658 mRsmpInFront = /* front = */ rear - framesIn;
6659 overrun = true;
6660 }
6661 if (framesAvailable != NULL) {
6662 *framesAvailable = framesIn;
6663 }
6664 if (hasOverrun != NULL) {
6665 *hasOverrun = overrun;
6666 }
6667}
6668
Eric Laurent81784c32012-11-19 14:55:58 -08006669// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006670status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08006671 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006672{
Andy Hung73c02e42015-03-29 01:13:58 -07006673 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006674 if (threadBase == 0) {
6675 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006676 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006677 return NOT_ENOUGH_DATA;
6678 }
6679 RecordThread *recordThread = (RecordThread *) threadBase.get();
6680 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07006681 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07006682 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006683 // FIXME should not be P2 (don't want to increase latency)
6684 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006685 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07006686 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006687 front &= recordThread->mRsmpInFramesP2 - 1;
6688 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07006689 if (part1 > (size_t) filled) {
6690 part1 = filled;
6691 }
6692 size_t ask = buffer->frameCount;
6693 ALOG_ASSERT(ask > 0);
6694 if (part1 > ask) {
6695 part1 = ask;
6696 }
6697 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07006698 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07006699 buffer->raw = NULL;
6700 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07006701 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07006702 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08006703 }
6704
Andy Hung57446612015-04-19 23:56:46 -07006705 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07006706 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07006707 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08006708 return NO_ERROR;
6709}
6710
6711// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006712void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
6713 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006714{
Glenn Kasten85948432013-08-19 12:09:05 -07006715 size_t stepCount = buffer->frameCount;
6716 if (stepCount == 0) {
6717 return;
6718 }
Andy Hung73c02e42015-03-29 01:13:58 -07006719 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
6720 mRsmpInUnrel -= stepCount;
6721 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006722 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006723 buffer->frameCount = 0;
6724}
6725
Andy Hung97a893e2015-03-29 01:03:07 -07006726AudioFlinger::RecordThread::RecordBufferConverter::RecordBufferConverter(
6727 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6728 uint32_t srcSampleRate,
6729 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6730 uint32_t dstSampleRate) :
6731 mSrcChannelMask(AUDIO_CHANNEL_INVALID), // updateParameters will set following vars
6732 // mSrcFormat
6733 // mSrcSampleRate
6734 // mDstChannelMask
6735 // mDstFormat
6736 // mDstSampleRate
6737 // mSrcChannelCount
6738 // mDstChannelCount
6739 // mDstFrameSize
6740 mBuf(NULL), mBufFrames(0), mBufFrameSize(0),
Andy Hungd330ee42015-04-20 13:23:41 -07006741 mResampler(NULL),
6742 mIsLegacyDownmix(false),
6743 mIsLegacyUpmix(false),
6744 mRequiresFloat(false),
6745 mInputConverterProvider(NULL)
Andy Hung97a893e2015-03-29 01:03:07 -07006746{
6747 (void)updateParameters(srcChannelMask, srcFormat, srcSampleRate,
6748 dstChannelMask, dstFormat, dstSampleRate);
6749}
6750
6751AudioFlinger::RecordThread::RecordBufferConverter::~RecordBufferConverter() {
6752 free(mBuf);
6753 delete mResampler;
Andy Hungd330ee42015-04-20 13:23:41 -07006754 delete mInputConverterProvider;
Andy Hung97a893e2015-03-29 01:03:07 -07006755}
6756
6757size_t AudioFlinger::RecordThread::RecordBufferConverter::convert(void *dst,
6758 AudioBufferProvider *provider, size_t frames)
6759{
Andy Hungd330ee42015-04-20 13:23:41 -07006760 if (mInputConverterProvider != NULL) {
6761 mInputConverterProvider->setBufferProvider(provider);
6762 provider = mInputConverterProvider;
6763 }
6764
6765 if (mResampler == NULL) {
Andy Hung97a893e2015-03-29 01:03:07 -07006766 ALOGVV("NO RESAMPLING sampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6767 mSrcSampleRate, mSrcFormat, mDstFormat);
6768
6769 AudioBufferProvider::Buffer buffer;
6770 for (size_t i = frames; i > 0; ) {
6771 buffer.frameCount = i;
Glenn Kastend79072e2016-01-06 08:41:20 -08006772 status_t status = provider->getNextBuffer(&buffer);
Andy Hung97a893e2015-03-29 01:03:07 -07006773 if (status != OK || buffer.frameCount == 0) {
6774 frames -= i; // cannot fill request.
6775 break;
6776 }
Andy Hungd330ee42015-04-20 13:23:41 -07006777 // format convert to destination buffer
6778 convertNoResampler(dst, buffer.raw, buffer.frameCount);
Andy Hung97a893e2015-03-29 01:03:07 -07006779
6780 dst = (int8_t*)dst + buffer.frameCount * mDstFrameSize;
6781 i -= buffer.frameCount;
6782 provider->releaseBuffer(&buffer);
6783 }
6784 } else {
6785 ALOGVV("RESAMPLING mSrcSampleRate:%u mDstSampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6786 mSrcSampleRate, mDstSampleRate, mSrcFormat, mDstFormat);
6787
Andy Hungd330ee42015-04-20 13:23:41 -07006788 // reallocate buffer if needed
6789 if (mBufFrameSize != 0 && mBufFrames < frames) {
6790 free(mBuf);
6791 mBufFrames = frames;
6792 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6793 }
Andy Hung97a893e2015-03-29 01:03:07 -07006794 // resampler accumulates, but we only have one source track
Andy Hungd330ee42015-04-20 13:23:41 -07006795 memset(mBuf, 0, frames * mBufFrameSize);
6796 frames = mResampler->resample((int32_t*)mBuf, frames, provider);
6797 // format convert to destination buffer
6798 convertResampler(dst, mBuf, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006799 }
6800 return frames;
6801}
6802
6803status_t AudioFlinger::RecordThread::RecordBufferConverter::updateParameters(
6804 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6805 uint32_t srcSampleRate,
6806 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6807 uint32_t dstSampleRate)
6808{
6809 // quick evaluation if there is any change.
6810 if (mSrcFormat == srcFormat
6811 && mSrcChannelMask == srcChannelMask
6812 && mSrcSampleRate == srcSampleRate
6813 && mDstFormat == dstFormat
6814 && mDstChannelMask == dstChannelMask
6815 && mDstSampleRate == dstSampleRate) {
6816 return NO_ERROR;
6817 }
6818
Andy Hungdb4c0312015-05-06 08:46:52 -07006819 ALOGV("RecordBufferConverter updateParameters srcMask:%#x dstMask:%#x"
6820 " srcFormat:%#x dstFormat:%#x srcRate:%u dstRate:%u",
6821 srcChannelMask, dstChannelMask, srcFormat, dstFormat, srcSampleRate, dstSampleRate);
Andy Hung97a893e2015-03-29 01:03:07 -07006822 const bool valid =
6823 audio_is_input_channel(srcChannelMask)
6824 && audio_is_input_channel(dstChannelMask)
6825 && audio_is_valid_format(srcFormat) && audio_is_linear_pcm(srcFormat)
6826 && audio_is_valid_format(dstFormat) && audio_is_linear_pcm(dstFormat)
6827 && (srcSampleRate <= dstSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX)
6828 ; // no upsampling checks for now
6829 if (!valid) {
6830 return BAD_VALUE;
6831 }
6832
6833 mSrcFormat = srcFormat;
6834 mSrcChannelMask = srcChannelMask;
6835 mSrcSampleRate = srcSampleRate;
6836 mDstFormat = dstFormat;
6837 mDstChannelMask = dstChannelMask;
6838 mDstSampleRate = dstSampleRate;
6839
6840 // compute derived parameters
6841 mSrcChannelCount = audio_channel_count_from_in_mask(srcChannelMask);
6842 mDstChannelCount = audio_channel_count_from_in_mask(dstChannelMask);
6843 mDstFrameSize = mDstChannelCount * audio_bytes_per_sample(mDstFormat);
6844
Andy Hungd330ee42015-04-20 13:23:41 -07006845 // do we need to resample?
6846 delete mResampler;
6847 mResampler = NULL;
6848 if (mSrcSampleRate != mDstSampleRate) {
6849 mResampler = AudioResampler::create(AUDIO_FORMAT_PCM_FLOAT,
6850 mSrcChannelCount, mDstSampleRate);
6851 mResampler->setSampleRate(mSrcSampleRate);
6852 mResampler->setVolume(AudioMixer::UNITY_GAIN_FLOAT, AudioMixer::UNITY_GAIN_FLOAT);
6853 }
6854
6855 // are we running legacy channel conversion modes?
6856 mIsLegacyDownmix = (mSrcChannelMask == AUDIO_CHANNEL_IN_STEREO
6857 || mSrcChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK)
6858 && mDstChannelMask == AUDIO_CHANNEL_IN_MONO;
6859 mIsLegacyUpmix = mSrcChannelMask == AUDIO_CHANNEL_IN_MONO
6860 && (mDstChannelMask == AUDIO_CHANNEL_IN_STEREO
6861 || mDstChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK);
6862
6863 // do we need to process in float?
6864 mRequiresFloat = mResampler != NULL || mIsLegacyDownmix || mIsLegacyUpmix;
6865
6866 // do we need a staging buffer to convert for destination (we can still optimize this)?
6867 // we use mBufFrameSize > 0 to indicate both frame size as well as buffer necessity
6868 if (mResampler != NULL) {
6869 mBufFrameSize = max(mSrcChannelCount, FCC_2)
6870 * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
Andy Hunga97630b2015-07-22 23:27:24 -07006871 } else if (mIsLegacyUpmix || mIsLegacyDownmix) { // legacy modes always float
Andy Hungd330ee42015-04-20 13:23:41 -07006872 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
6873 } else if (mSrcChannelMask != mDstChannelMask && mDstFormat != mSrcFormat) {
Andy Hung97a893e2015-03-29 01:03:07 -07006874 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(mSrcFormat);
6875 } else {
6876 mBufFrameSize = 0;
6877 }
6878 mBufFrames = 0; // force the buffer to be resized.
6879
Andy Hungd330ee42015-04-20 13:23:41 -07006880 // do we need an input converter buffer provider to give us float?
6881 delete mInputConverterProvider;
6882 mInputConverterProvider = NULL;
6883 if (mRequiresFloat && mSrcFormat != AUDIO_FORMAT_PCM_FLOAT) {
6884 mInputConverterProvider = new ReformatBufferProvider(
6885 audio_channel_count_from_in_mask(mSrcChannelMask),
6886 mSrcFormat,
6887 AUDIO_FORMAT_PCM_FLOAT,
6888 256 /* provider buffer frame count */);
6889 }
6890
6891 // do we need a remixer to do channel mask conversion
6892 if (!mIsLegacyDownmix && !mIsLegacyUpmix && mSrcChannelMask != mDstChannelMask) {
6893 (void) memcpy_by_index_array_initialization_from_channel_mask(
6894 mIdxAry, ARRAY_SIZE(mIdxAry), mDstChannelMask, mSrcChannelMask);
Andy Hung97a893e2015-03-29 01:03:07 -07006895 }
6896 return NO_ERROR;
6897}
6898
Andy Hungd330ee42015-04-20 13:23:41 -07006899void AudioFlinger::RecordThread::RecordBufferConverter::convertNoResampler(
6900 void *dst, const void *src, size_t frames)
Andy Hung97a893e2015-03-29 01:03:07 -07006901{
Andy Hungd330ee42015-04-20 13:23:41 -07006902 // src is native type unless there is legacy upmix or downmix, whereupon it is float.
Andy Hung97a893e2015-03-29 01:03:07 -07006903 if (mBufFrameSize != 0 && mBufFrames < frames) {
6904 free(mBuf);
6905 mBufFrames = frames;
6906 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6907 }
Andy Hungd330ee42015-04-20 13:23:41 -07006908 // do we need to do legacy upmix and downmix?
6909 if (mIsLegacyUpmix || mIsLegacyDownmix) {
Andy Hung97a893e2015-03-29 01:03:07 -07006910 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07006911 if (mIsLegacyUpmix) {
6912 upmix_to_stereo_float_from_mono_float((float *)dstBuf,
6913 (const float *)src, frames);
6914 } else /*mIsLegacyDownmix */ {
6915 downmix_to_mono_float_from_stereo_float((float *)dstBuf,
6916 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006917 }
Andy Hungd330ee42015-04-20 13:23:41 -07006918 if (mBuf != NULL) {
6919 memcpy_by_audio_format(dst, mDstFormat, mBuf, AUDIO_FORMAT_PCM_FLOAT,
6920 frames * mDstChannelCount);
6921 }
6922 return;
6923 }
6924 // do we need to do channel mask conversion?
6925 if (mSrcChannelMask != mDstChannelMask) {
Andy Hung97a893e2015-03-29 01:03:07 -07006926 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07006927 memcpy_by_index_array(dstBuf, mDstChannelCount,
6928 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mSrcFormat), frames);
6929 if (dstBuf == dst) {
6930 return; // format is the same
6931 }
6932 }
6933 // convert to destination buffer
6934 const void *convertBuf = mBuf != NULL ? mBuf : src;
6935 memcpy_by_audio_format(dst, mDstFormat, convertBuf, mSrcFormat,
6936 frames * mDstChannelCount);
6937}
6938
6939void AudioFlinger::RecordThread::RecordBufferConverter::convertResampler(
6940 void *dst, /*not-a-const*/ void *src, size_t frames)
6941{
6942 // src buffer format is ALWAYS float when entering this routine
6943 if (mIsLegacyUpmix) {
6944 ; // mono to stereo already handled by resampler
6945 } else if (mIsLegacyDownmix
6946 || (mSrcChannelMask == mDstChannelMask && mSrcChannelCount == 1)) {
6947 // the resampler outputs stereo for mono input channel (a feature?)
6948 // must convert to mono
6949 downmix_to_mono_float_from_stereo_float((float *)src,
6950 (const float *)src, frames);
6951 } else if (mSrcChannelMask != mDstChannelMask) {
6952 // convert to mono channel again for channel mask conversion (could be skipped
6953 // with further optimization).
Andy Hung97a893e2015-03-29 01:03:07 -07006954 if (mSrcChannelCount == 1) {
Andy Hungd330ee42015-04-20 13:23:41 -07006955 downmix_to_mono_float_from_stereo_float((float *)src,
6956 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006957 }
Andy Hungd330ee42015-04-20 13:23:41 -07006958 // convert to destination format (in place, OK as float is larger than other types)
6959 if (mDstFormat != AUDIO_FORMAT_PCM_FLOAT) {
6960 memcpy_by_audio_format(src, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
6961 frames * mSrcChannelCount);
6962 }
6963 // channel convert and save to dst
6964 memcpy_by_index_array(dst, mDstChannelCount,
6965 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mDstFormat), frames);
6966 return;
Andy Hung97a893e2015-03-29 01:03:07 -07006967 }
Andy Hungd330ee42015-04-20 13:23:41 -07006968 // convert to destination format and save to dst
6969 memcpy_by_audio_format(dst, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
6970 frames * mDstChannelCount);
Andy Hung97a893e2015-03-29 01:03:07 -07006971}
6972
Eric Laurent10351942014-05-08 18:49:52 -07006973bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
6974 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006975{
6976 bool reconfig = false;
6977
Eric Laurent10351942014-05-08 18:49:52 -07006978 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006979
Eric Laurent10351942014-05-08 18:49:52 -07006980 audio_format_t reqFormat = mFormat;
6981 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07006982 // 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 -07006983 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
6984
6985 AudioParameter param = AudioParameter(keyValuePair);
6986 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07006987
6988 // scope for AutoPark extends to end of method
6989 AutoPark<FastCapture> park(mFastCapture);
6990
Eric Laurent10351942014-05-08 18:49:52 -07006991 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
6992 // channel count change can be requested. Do we mandate the first client defines the
6993 // HAL sampling rate and channel count or do we allow changes on the fly?
6994 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6995 samplingRate = value;
6996 reconfig = true;
6997 }
6998 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07006999 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07007000 status = BAD_VALUE;
7001 } else {
7002 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08007003 reconfig = true;
7004 }
Eric Laurent10351942014-05-08 18:49:52 -07007005 }
7006 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
7007 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07007008 if (!audio_is_input_channel(mask) ||
7009 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007010 status = BAD_VALUE;
7011 } else {
7012 channelMask = mask;
7013 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007014 }
Eric Laurent10351942014-05-08 18:49:52 -07007015 }
7016 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7017 // do not accept frame count changes if tracks are open as the track buffer
7018 // size depends on frame count and correct behavior would not be guaranteed
7019 // if frame count is changed after track creation
7020 if (mActiveTracks.size() > 0) {
7021 status = INVALID_OPERATION;
7022 } else {
7023 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007024 }
Eric Laurent10351942014-05-08 18:49:52 -07007025 }
7026 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7027 // forward device change to effects that have requested to be
7028 // aware of attached audio device.
7029 for (size_t i = 0; i < mEffectChains.size(); i++) {
7030 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08007031 }
Eric Laurent81784c32012-11-19 14:55:58 -08007032
Eric Laurent10351942014-05-08 18:49:52 -07007033 // store input device and output device but do not forward output device to audio HAL.
7034 // Note that status is ignored by the caller for output device
7035 // (see AudioFlinger::setParameters()
7036 if (audio_is_output_devices(value)) {
7037 mOutDevice = value;
7038 status = BAD_VALUE;
7039 } else {
7040 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07007041 if (value != AUDIO_DEVICE_NONE) {
7042 mPrevInDevice = value;
7043 }
Eric Laurent10351942014-05-08 18:49:52 -07007044 // disable AEC and NS if the device is a BT SCO headset supporting those
7045 // pre processings
7046 if (mTracks.size() > 0) {
7047 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7048 mAudioFlinger->btNrecIsOff();
7049 for (size_t i = 0; i < mTracks.size(); i++) {
7050 sp<RecordTrack> track = mTracks[i];
7051 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7052 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08007053 }
7054 }
7055 }
Eric Laurent10351942014-05-08 18:49:52 -07007056 }
7057 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
7058 mAudioSource != (audio_source_t)value) {
7059 // forward device change to effects that have requested to be
7060 // aware of attached audio device.
7061 for (size_t i = 0; i < mEffectChains.size(); i++) {
7062 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08007063 }
Eric Laurent10351942014-05-08 18:49:52 -07007064 mAudioSource = (audio_source_t)value;
7065 }
Glenn Kastene198c362013-08-13 09:13:36 -07007066
Eric Laurent10351942014-05-08 18:49:52 -07007067 if (status == NO_ERROR) {
7068 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7069 keyValuePair.string());
7070 if (status == INVALID_OPERATION) {
7071 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08007072 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7073 keyValuePair.string());
Eric Laurent10351942014-05-08 18:49:52 -07007074 }
7075 if (reconfig) {
7076 if (status == BAD_VALUE &&
Andy Hung97a893e2015-03-29 01:03:07 -07007077 audio_is_linear_pcm(mInput->stream->common.get_format(&mInput->stream->common)) &&
7078 audio_is_linear_pcm(reqFormat) &&
Eric Laurent10351942014-05-08 18:49:52 -07007079 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
Andy Hung97a893e2015-03-29 01:03:07 -07007080 <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate)) &&
Andy Hunge5412692014-05-16 11:25:07 -07007081 audio_channel_count_from_in_mask(
Andy Hungd1abb8f2015-05-05 23:42:34 -07007082 mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007083 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007084 }
Eric Laurent10351942014-05-08 18:49:52 -07007085 if (status == NO_ERROR) {
7086 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007087 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08007088 }
7089 }
Eric Laurent81784c32012-11-19 14:55:58 -08007090 }
Eric Laurent10351942014-05-08 18:49:52 -07007091
Eric Laurent81784c32012-11-19 14:55:58 -08007092 return reconfig;
7093}
7094
7095String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
7096{
Eric Laurent81784c32012-11-19 14:55:58 -08007097 Mutex::Autolock _l(mLock);
7098 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07007099 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08007100 }
7101
Glenn Kastend8ea6992013-07-16 14:17:15 -07007102 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
7103 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08007104 free(s);
7105 return out_s8;
7106}
7107
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007108void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007109 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7110
7111 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08007112
7113 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007114 case AUDIO_INPUT_OPENED:
7115 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07007116 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07007117 desc->mChannelMask = mChannelMask;
7118 desc->mSamplingRate = mSampleRate;
7119 desc->mFormat = mFormat;
7120 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07007121 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07007122 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007123 break;
7124
Eric Laurent73e26b62015-04-27 16:55:58 -07007125 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08007126 default:
7127 break;
7128 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007129 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08007130}
7131
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007132void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007133{
Eric Laurent81784c32012-11-19 14:55:58 -08007134 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
7135 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Andy Hunge5412692014-05-16 11:25:07 -07007136 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Andy Hungd330ee42015-04-20 13:23:41 -07007137 if (mChannelCount > FCC_8) {
7138 ALOGE("HAL channel count %d > %d", mChannelCount, FCC_8);
7139 }
Andy Hung463be252014-07-10 16:56:07 -07007140 mHALFormat = mInput->stream->common.get_format(&mInput->stream->common);
7141 mFormat = mHALFormat;
Andy Hungd330ee42015-04-20 13:23:41 -07007142 if (!audio_is_linear_pcm(mFormat)) {
7143 ALOGE("HAL format %#x is not linear pcm", mFormat);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07007144 }
Eric Laurent665470b2014-07-03 16:37:08 -07007145 mFrameSize = audio_stream_in_frame_size(mInput->stream);
Glenn Kasten548efc92012-11-29 08:48:51 -08007146 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
7147 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007148 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08007149 // 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 -07007150 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08007151 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007152 // A larger value should allow more old data to be read after a track calls start(),
7153 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07007154 //
7155 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08007156 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07007157 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07007158 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07007159 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007160
7161 // TODO optimize audio capture buffer sizes ...
7162 // Here we calculate the size of the sliding buffer used as a source
7163 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
7164 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
7165 // be better to have it derived from the pipe depth in the long term.
7166 // The current value is higher than necessary. However it should not add to latency.
7167
Glenn Kasten85948432013-08-19 12:09:05 -07007168 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Andy Hung0a01c2f2015-09-21 12:44:54 -07007169 size_t bufferSize = (mRsmpInFramesP2 + mFrameCount - 1) * mFrameSize;
7170 (void)posix_memalign(&mRsmpInBuffer, 32, bufferSize);
7171 memset(mRsmpInBuffer, 0, bufferSize); // if posix_memalign fails, will segv here.
Eric Laurent81784c32012-11-19 14:55:58 -08007172
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007173 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
7174 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08007175}
7176
Glenn Kasten5f972c02014-01-13 09:59:31 -08007177uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08007178{
7179 Mutex::Autolock _l(mLock);
7180 if (initCheck() != NO_ERROR) {
7181 return 0;
7182 }
7183
7184 return mInput->stream->get_input_frames_lost(mInput->stream);
7185}
7186
Glenn Kastend848eb42016-03-08 13:42:11 -08007187uint32_t AudioFlinger::RecordThread::hasAudioSession(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08007188{
7189 Mutex::Autolock _l(mLock);
7190 uint32_t result = 0;
7191 if (getEffectChain_l(sessionId) != 0) {
7192 result = EFFECT_SESSION;
7193 }
7194
7195 for (size_t i = 0; i < mTracks.size(); ++i) {
7196 if (sessionId == mTracks[i]->sessionId()) {
7197 result |= TRACK_SESSION;
7198 break;
7199 }
7200 }
7201
7202 return result;
7203}
7204
Glenn Kastend848eb42016-03-08 13:42:11 -08007205KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08007206{
Glenn Kastend848eb42016-03-08 13:42:11 -08007207 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08007208 Mutex::Autolock _l(mLock);
7209 for (size_t j = 0; j < mTracks.size(); ++j) {
7210 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08007211 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08007212 if (ids.indexOfKey(sessionId) < 0) {
7213 ids.add(sessionId, true);
7214 }
7215 }
7216 return ids;
7217}
7218
7219AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7220{
7221 Mutex::Autolock _l(mLock);
7222 AudioStreamIn *input = mInput;
7223 mInput = NULL;
7224 return input;
7225}
7226
7227// this method must always be called either with ThreadBase mLock held or inside the thread loop
7228audio_stream_t* AudioFlinger::RecordThread::stream() const
7229{
7230 if (mInput == NULL) {
7231 return NULL;
7232 }
7233 return &mInput->stream->common;
7234}
7235
7236status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7237{
7238 // only one chain per input thread
7239 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07007240 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08007241 return INVALID_OPERATION;
7242 }
7243 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07007244 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08007245 chain->setInBuffer(NULL);
7246 chain->setOutBuffer(NULL);
7247
7248 checkSuspendOnAddEffectChain_l(chain);
7249
Eric Laurent1b928682014-10-02 19:41:47 -07007250 // make sure enabled pre processing effects state is communicated to the HAL as we
7251 // just moved them to a new input stream.
7252 chain->syncHalEffectsState();
7253
Eric Laurent81784c32012-11-19 14:55:58 -08007254 mEffectChains.add(chain);
7255
7256 return NO_ERROR;
7257}
7258
7259size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7260{
7261 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7262 ALOGW_IF(mEffectChains.size() != 1,
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007263 "removeEffectChain_l() %p invalid chain size %zu on thread %p",
Eric Laurent81784c32012-11-19 14:55:58 -08007264 chain.get(), mEffectChains.size(), this);
7265 if (mEffectChains.size() == 1) {
7266 mEffectChains.removeAt(0);
7267 }
7268 return 0;
7269}
7270
Eric Laurent1c333e22014-05-20 10:48:17 -07007271status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7272 audio_patch_handle_t *handle)
7273{
7274 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007275
7276 // store new device and send to effects
7277 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07007278 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07007279 for (size_t i = 0; i < mEffectChains.size(); i++) {
7280 mEffectChains[i]->setDevice_l(mInDevice);
7281 }
7282
7283 // disable AEC and NS if the device is a BT SCO headset supporting those
7284 // pre processings
7285 if (mTracks.size() > 0) {
7286 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7287 mAudioFlinger->btNrecIsOff();
7288 for (size_t i = 0; i < mTracks.size(); i++) {
7289 sp<RecordTrack> track = mTracks[i];
7290 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7291 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
7292 }
7293 }
7294
7295 // store new source and send to effects
7296 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7297 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07007298 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07007299 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07007300 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007301 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007302
Eric Laurent054d9d32015-04-24 08:48:48 -07007303 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007304 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
7305 status = hwDevice->create_audio_patch(hwDevice,
7306 patch->num_sources,
7307 patch->sources,
7308 patch->num_sinks,
7309 patch->sinks,
7310 handle);
7311 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007312 char *address;
7313 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7314 address = audio_device_address_to_parameter(
7315 patch->sources[0].ext.device.type,
7316 patch->sources[0].ext.device.address);
7317 } else {
7318 address = (char *)calloc(1, 1);
7319 }
7320 AudioParameter param = AudioParameter(String8(address));
7321 free(address);
7322 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING),
7323 (int)patch->sources[0].ext.device.type);
7324 param.addInt(String8(AUDIO_PARAMETER_STREAM_INPUT_SOURCE),
7325 (int)patch->sinks[0].ext.mix.usecase.source);
7326 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7327 param.toString().string());
7328 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07007329 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007330
Eric Laurente8726fe2015-06-26 09:39:24 -07007331 if (mInDevice != mPrevInDevice) {
7332 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7333 mPrevInDevice = mInDevice;
7334 }
Eric Laurent296fb132015-05-01 11:38:42 -07007335
Eric Laurent1c333e22014-05-20 10:48:17 -07007336 return status;
7337}
7338
7339status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7340{
7341 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007342
7343 mInDevice = AUDIO_DEVICE_NONE;
7344
Eric Laurent1c333e22014-05-20 10:48:17 -07007345 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
7346 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
7347 status = hwDevice->release_audio_patch(hwDevice, handle);
7348 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007349 AudioParameter param;
7350 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
7351 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7352 param.toString().string());
Eric Laurent1c333e22014-05-20 10:48:17 -07007353 }
7354 return status;
7355}
7356
Eric Laurent83b88082014-06-20 18:31:16 -07007357void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
7358{
7359 Mutex::Autolock _l(mLock);
7360 mTracks.add(record);
7361}
7362
7363void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
7364{
7365 Mutex::Autolock _l(mLock);
7366 destroyTrack_l(record);
7367}
7368
7369void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
7370{
7371 ThreadBase::getAudioPortConfig(config);
7372 config->role = AUDIO_PORT_ROLE_SINK;
7373 config->ext.mix.hw_module = mInput->audioHwDev->handle();
7374 config->ext.mix.usecase.source = mAudioSource;
7375}
Eric Laurent1c333e22014-05-20 10:48:17 -07007376
Glenn Kasten63238ef2015-03-02 15:50:29 -08007377} // namespace android